diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2022-02-02 12:21:57 +0100 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2022-02-12 08:13:00 +0000 |
commit | 606d85f2a5386472314d39923da28c70c60dc8e7 (patch) | |
tree | a8f4d7bf997f349f45605e6058259fba0630e4d7 /chromium/chrome/browser/extensions | |
parent | 5786336dda477d04fb98483dca1a5426eebde2d7 (diff) |
BASELINE: Update Chromium to 96.0.4664.181
Change-Id: I762cd1da89d73aa6313b4a753fe126c34833f046
Reviewed-by: Allan Sandfeld Jensen <allan.jensen@qt.io>
Diffstat (limited to 'chromium/chrome/browser/extensions')
392 files changed, 9581 insertions, 4121 deletions
diff --git a/chromium/chrome/browser/extensions/BUILD.gn b/chromium/chrome/browser/extensions/BUILD.gn index 3c3358ae9fa..0bff3d62207 100644 --- a/chromium/chrome/browser/extensions/BUILD.gn +++ b/chromium/chrome/browser/extensions/BUILD.gn @@ -410,6 +410,10 @@ static_library("extensions") { "api/tabs/windows_util.h", "api/top_sites/top_sites_api.cc", "api/top_sites/top_sites_api.h", + "api/web_authentication_proxy/web_authentication_proxy_api.cc", + "api/web_authentication_proxy/web_authentication_proxy_api.h", + "api/web_authentication_proxy/web_authentication_proxy_service.cc", + "api/web_authentication_proxy/web_authentication_proxy_service.h", "api/web_navigation/frame_navigation_state.cc", "api/web_navigation/frame_navigation_state.h", "api/web_navigation/web_navigation_api.cc", @@ -797,6 +801,7 @@ static_library("extensions") { "//chrome/browser/safe_browsing:metrics_collector", "//chrome/browser/web_applications", "//components/safe_browsing/content/browser", + "//components/safe_browsing/core/browser:safe_browsing_metrics_collector", "//components/site_engagement/core/mojom:mojo_bindings", "//components/webapps/browser", @@ -846,7 +851,6 @@ static_library("extensions") { "//components/password_manager/core/browser:affiliation", "//components/password_manager/core/browser/leak_detection", "//components/payments/core", - "//components/pdf/browser", "//components/performance_manager", "//components/permissions", "//components/policy:generated", @@ -950,7 +954,7 @@ static_library("extensions") { if (is_chromeos_ash) { deps += [ - "//chromeos/resources:media_app_bundle_resources_grit", + "//ash/webui/resources:media_app_bundle_resources_grit", "//ui/display/manager", ] } @@ -988,6 +992,8 @@ static_library("extensions") { "api/printing/printing_api_utils.cc", "api/printing/printing_api_utils.h", ] + + deps += [ "//printing/backend" ] } deps += [ "//chromeos/crosapi/cpp", @@ -1052,6 +1058,8 @@ static_library("extensions") { "api/media_perception_private/media_perception_api_delegate_chromeos.h", "api/networking_private/networking_private_ui_delegate_chromeos.cc", "api/networking_private/networking_private_ui_delegate_chromeos.h", + "api/quick_unlock_private/quick_unlock_private_api.cc", + "api/quick_unlock_private/quick_unlock_private_api.h", "api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc", "api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.h", "api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc", @@ -1086,6 +1094,7 @@ static_library("extensions") { deps += [ "//ash", "//ash/components/enhanced_network_tts/mojom", + "//ash/components/quick_answers/public/cpp:prefs", "//ash/constants", "//ash/keyboard/ui:resources_grit_grit", "//ash/public/cpp", @@ -1097,10 +1106,8 @@ static_library("extensions") { "//chromeos/attestation", "//chromeos/components/camera_app_ui", "//chromeos/components/camera_app_ui:mojo_bindings", - "//chromeos/components/camera_app_ui/resources:chrome_camera_app", "//chromeos/components/chromebox_for_meetings/buildflags", "//chromeos/components/proximity_auth", - "//chromeos/components/quick_answers/public/cpp:prefs", "//chromeos/components/remote_apps/mojom", "//chromeos/cryptohome", "//chromeos/dbus", @@ -1110,6 +1117,8 @@ static_library("extensions") { "//chromeos/dbus/update_engine", "//chromeos/dbus/util", "//chromeos/disks", + "//chromeos/language/language_packs", + "//chromeos/language/public/mojom", "//chromeos/login/auth", "//chromeos/login/login_state", "//chromeos/network", @@ -1133,7 +1142,7 @@ static_library("extensions") { "//media/capture/video/chromeos/mojom:cros_camera", "//third_party/protobuf:protobuf_lite", "//ui/accessibility", - "//ui/base/ime/chromeos", + "//ui/base/ime/ash", "//ui/chromeos", "//ui/chromeos/events", "//ui/file_manager:file_manager_gen_resources", @@ -1141,17 +1150,34 @@ static_library("extensions") { "//ui/ozone", "//ui/views", ] - if (enable_nacl) { - deps += [ "//chrome/browser/resources/chromeos/zip_archiver" ] - } if (is_cfm) { deps += [ "//chromeos/services/chromebox_for_meetings/public/cpp", "//chromeos/services/chromebox_for_meetings/public/mojom", ] } + } else if (is_chromeos_lacros) { + sources += [ + "api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc", + "api/enterprise_reporting_private/chrome_desktop_report_request_helper.h", + "api/enterprise_reporting_private/keychain_data_helper_mac.h", + "api/enterprise_reporting_private/keychain_data_helper_mac.mm", + "api/image_writer_private/operation_nonchromeos.cc", + "api/image_writer_private/removable_storage_provider_linux.cc", + "api/tabs/tabs_util_chromeos.cc", + "chrome_kiosk_delegate.cc", + "preinstalled_apps.cc", + "preinstalled_apps.h", + ] + deps += [ + "//chromeos/ui/base", + "//components/enterprise", + "//components/enterprise/common/proto:connectors_proto", + "//components/keep_alive_registry", + ] } else { assert(!is_chromeos_ash) + assert(!is_chromeos_lacros) sources += [ "api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc", "api/enterprise_reporting_private/chrome_desktop_report_request_helper.h", @@ -1168,7 +1194,7 @@ static_library("extensions") { "//components/enterprise/common/proto:connectors_proto", "//components/keep_alive_registry", ] - if (is_linux || is_chromeos) { + if (is_linux) { sources += [ "api/image_writer_private/removable_storage_provider_linux.cc" ] } @@ -1180,12 +1206,6 @@ static_library("extensions") { } } - if (use_x11) { - sources += [ - "global_shortcut_listener_x11.cc", - "global_shortcut_listener_x11.h", - ] - } if (use_ozone) { deps += [ "//ui/ozone" ] sources += [ @@ -1194,10 +1214,6 @@ static_library("extensions") { ] } - if (use_x11 || use_ozone) { - sources += [ "global_shortcut_listener_linux.cc" ] - } - if (is_mac) { sources += [ "api/image_writer_private/removable_storage_provider_mac.cc", @@ -1217,14 +1233,6 @@ static_library("extensions") { if (use_udev) { deps += [ "//device/udev_linux" ] } - - if (use_x11) { - deps += [ - "//ui/events:events_base", - "//ui/events/platform", - "//ui/events/platform/x11", - ] - } } if (is_win) { @@ -1268,8 +1276,6 @@ static_library("extensions") { } if (enable_basic_printing && (is_win || is_mac || is_linux || is_chromeos)) { - # Needed by files which include //chrome/browser/service_sandbox_type.h. - # Inclusion of print_backend_service_manager.h depends on this. # TODO(crbug.com/1213762) Replace this with more accurate dependency # once //chrome/browser/printing build is able to be cleanly targeted. deps += [ "//chrome/services/printing/public/mojom" ] @@ -1284,6 +1290,7 @@ static_library("extensions") { if (enable_pdf) { deps += [ + "//components/pdf/browser", "//pdf:buildflags", "//pdf:features", ] diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc index c858e311384..654aaa341e7 100644 --- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc +++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.cc @@ -22,9 +22,6 @@ #include "content/public/browser/browser_context.h" #include "extensions/browser/extension_system_provider.h" #include "extensions/browser/extensions_browser_client.h" -#include "extensions/common/features/feature.h" -#include "extensions/common/features/feature_provider.h" -#include "extensions/common/hashed_extension_id.h" namespace extensions { @@ -74,14 +71,6 @@ void ActivityLogAPI::Shutdown() { activity_log_->RemoveObserver(this); } -// static -bool ActivityLogAPI::IsExtensionAllowlisted(const std::string& extension_id) { - // TODO(devlin): Pass in a HashedExtensionId to avoid this conversion. - return FeatureProvider::GetPermissionFeatures() - ->GetFeature("activityLogPrivate") - ->IsIdInAllowlist(HashedExtensionId(extension_id)); -} - void ActivityLogAPI::OnListenerAdded(const EventListenerInfo& details) { if (activity_log_->has_listeners()) return; @@ -112,7 +101,7 @@ void ActivityLogAPI::OnExtensionActivity(scoped_refptr<Action> activity) { ExtensionFunction::ResponseAction ActivityLogPrivateGetExtensionActivitiesFunction::Run() { std::unique_ptr<activity_log_private::GetExtensionActivities::Params> params( - activity_log_private::GetExtensionActivities::Params::Create(*args_)); + activity_log_private::GetExtensionActivities::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); // Get the arguments in the right format. @@ -180,7 +169,7 @@ void ActivityLogPrivateGetExtensionActivitiesFunction::OnLookupCompleted( ExtensionFunction::ResponseAction ActivityLogPrivateDeleteActivitiesFunction::Run() { std::unique_ptr<activity_log_private::DeleteActivities::Params> params( - activity_log_private::DeleteActivities::Params::Create(*args_)); + activity_log_private::DeleteActivities::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); // Put the arguments in the right format. @@ -201,7 +190,7 @@ ExtensionFunction::ResponseAction ActivityLogPrivateDeleteActivitiesByExtensionFunction::Run() { std::unique_ptr<activity_log_private::DeleteActivitiesByExtension::Params> params(activity_log_private::DeleteActivitiesByExtension::Params::Create( - *args_)); + args())); EXTENSION_FUNCTION_VALIDATE(params); ActivityLog* activity_log = ActivityLog::GetInstance(browser_context()); @@ -220,7 +209,7 @@ ActivityLogPrivateDeleteDatabaseFunction::Run() { ExtensionFunction::ResponseAction ActivityLogPrivateDeleteUrlsFunction::Run() { std::unique_ptr<activity_log_private::DeleteUrls::Params> params( - activity_log_private::DeleteUrls::Params::Create(*args_)); + activity_log_private::DeleteUrls::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); // Put the arguments in the right format. diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h index 8df08619da3..5fac6632420 100644 --- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h +++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_api.h @@ -39,9 +39,6 @@ class ActivityLogAPI : public BrowserContextKeyedAPI, void Shutdown() override; - // Lookup whether the extension ID is allowlisted. - static bool IsExtensionAllowlisted(const std::string& extension_id); - private: friend class BrowserContextKeyedAPIFactory<ActivityLogAPI>; static const char* service_name() { return "ActivityLogPrivateAPI"; } diff --git a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc index 47c9a7ccc3c..25f85acdaf3 100644 --- a/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/activity_log_private/activity_log_private_apitest.cc @@ -58,9 +58,9 @@ class ActivityLogApiTest : public ExtensionApiTest { base::CommandLine saved_cmdline_; }; -#if !defined(NDEBUG) || defined(ADDRESS_SANITIZER) -// TODO(crbug.com/299393): This test is very long and can time out in debug or -// ASAN builds. +#if !defined(NDEBUG) +// TODO(crbug.com/299393): This test is very long and can time out in debug +// builds. #define MAYBE_TriggerEvent DISABLED_TriggerEvent #else #define MAYBE_TriggerEvent TriggerEvent diff --git a/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc b/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc index c48d4230d0b..a6e8ab13cbe 100644 --- a/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc +++ b/chromium/chrome/browser/extensions/api/alarms/alarms_apitest.cc @@ -20,7 +20,7 @@ using ContextType = ExtensionApiTest::ContextType; class AlarmsApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - AlarmsApiTest() = default; + AlarmsApiTest() : ExtensionApiTest(GetParam()) {} ~AlarmsApiTest() override = default; AlarmsApiTest& operator=(const AlarmsApiTest&) = delete; AlarmsApiTest(const AlarmsApiTest&) = delete; @@ -39,10 +39,8 @@ class AlarmsApiTest : public ExtensionApiTest, } const Extension* LoadAlarmsExtensionIncognito(const char* path) { - return LoadExtension( - test_data_dir_.AppendASCII("alarms").AppendASCII(path), - {.allow_in_incognito = true, - .load_as_service_worker = GetParam() == ContextType::kServiceWorker}); + return LoadExtension(test_data_dir_.AppendASCII("alarms").AppendASCII(path), + {.allow_in_incognito = true}); } }; diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc index 393bdfaa821..94083530d3f 100644 --- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc +++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.cc @@ -160,7 +160,7 @@ namespace extensions { ExtensionFunction::ResponseAction AutofillPrivateSaveAddressFunction::Run() { std::unique_ptr<api::autofill_private::SaveAddress::Params> parameters = - api::autofill_private::SaveAddress::Params::Create(*args_); + api::autofill_private::SaveAddress::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); autofill::PersonalDataManager* personal_data = @@ -310,7 +310,7 @@ ExtensionFunction::ResponseAction AutofillPrivateGetAddressComponentsFunction::Run() { std::unique_ptr<api::autofill_private::GetAddressComponents::Params> parameters = - api::autofill_private::GetAddressComponents::Params::Create(*args_); + api::autofill_private::GetAddressComponents::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); std::vector<std::vector<::i18n::addressinput::AddressUiComponent>> lines; @@ -361,7 +361,7 @@ ExtensionFunction::ResponseAction AutofillPrivateGetAddressListFunction::Run() { ExtensionFunction::ResponseAction AutofillPrivateSaveCreditCardFunction::Run() { std::unique_ptr<api::autofill_private::SaveCreditCard::Params> parameters = - api::autofill_private::SaveCreditCard::Params::Create(*args_); + api::autofill_private::SaveCreditCard::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); autofill::PersonalDataManager* personal_data = @@ -442,7 +442,7 @@ ExtensionFunction::ResponseAction AutofillPrivateSaveCreditCardFunction::Run() { ExtensionFunction::ResponseAction AutofillPrivateRemoveEntryFunction::Run() { std::unique_ptr<api::autofill_private::RemoveEntry::Params> parameters = - api::autofill_private::RemoveEntry::Params::Create(*args_); + api::autofill_private::RemoveEntry::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); autofill::PersonalDataManager* personal_data = @@ -463,7 +463,7 @@ ExtensionFunction::ResponseAction AutofillPrivateValidatePhoneNumbersFunction::Run() { std::unique_ptr<api::autofill_private::ValidatePhoneNumbers::Params> parameters = - api::autofill_private::ValidatePhoneNumbers::Params::Create(*args_); + api::autofill_private::ValidatePhoneNumbers::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); api::autofill_private::ValidatePhoneParams* params = ¶meters->params; @@ -485,7 +485,7 @@ AutofillPrivateValidatePhoneNumbersFunction::Run() { ExtensionFunction::ResponseAction AutofillPrivateMaskCreditCardFunction::Run() { std::unique_ptr<api::autofill_private::MaskCreditCard::Params> parameters = - api::autofill_private::MaskCreditCard::Params::Create(*args_); + api::autofill_private::MaskCreditCard::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); autofill::PersonalDataManager* personal_data = @@ -591,7 +591,7 @@ AutofillPrivateSetCreditCardFIDOAuthEnabledStateFunction::Run() { std::unique_ptr< api::autofill_private::SetCreditCardFIDOAuthEnabledState::Params> parameters = api::autofill_private::SetCreditCardFIDOAuthEnabledState:: - Params::Create(*args_); + Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); credit_card_access_manager->OnSettingsPageFIDOAuthToggled( diff --git a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc index 9a5466760e5..4005412d0a2 100644 --- a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc +++ b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc @@ -26,7 +26,6 @@ #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/tracing_controller.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/content_features.h" #include "content/public/test/browser_test.h" #include "extensions/browser/api/automation_internal/automation_event_router.h" #include "extensions/common/api/automation_internal.h" @@ -81,12 +80,6 @@ class AutomationApiTest : public ExtensionApiTest { } public: - void SetUp() override { - scoped_feature_list_.InitAndEnableFeature( - features::kExperimentalAccessibilityLabels); - ExtensionApiTest::SetUp(); - } - void SetUpOnMainThread() override { ExtensionApiTest::SetUpOnMainThread(); host_resolver()->AddRule("*", "127.0.0.1"); @@ -108,7 +101,7 @@ class AutomationApiCanvasTest : public AutomationApiTest { IN_PROC_BROWSER_TEST_F(AutomationApiTest, TestRendererAccessibilityEnabled) { StartEmbeddedTestServer(); const GURL url = GetURLForPath(kDomain, "/index.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_EQ(1, browser()->tab_strip_model()->count()); content::WebContents* const tab = @@ -136,7 +129,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, SanityCheck) { IN_PROC_BROWSER_TEST_F(AutomationApiTest, ImageLabels) { StartEmbeddedTestServer(); const GURL url = GetURLForPath(kDomain, "/index.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Enable image labels. browser()->profile()->GetPrefs()->SetBoolean( @@ -161,7 +154,13 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, ImageLabels) { EXPECT_EQ(expected_mode, web_contents->GetAccessibilityMode()); } -IN_PROC_BROWSER_TEST_F(AutomationApiTest, GetTreeByTabId) { +// Flaky on Mac: crbug.com/1248445 +#if defined(OS_MAC) +#define MAYBE_GetTreeByTabId DISABLED_GetTreeByTabId +#else +#define MAYBE_GetTreeByTabId GetTreeByTabId +#endif +IN_PROC_BROWSER_TEST_F(AutomationApiTest, MAYBE_GetTreeByTabId) { StartEmbeddedTestServer(); ASSERT_TRUE( RunExtensionTest("automation/tests/tabs", {.page_url = "tab_id.html"})) @@ -224,8 +223,8 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, TableProperties) { << message_; } -// Flaky on Mac: crbug.com/1235249 -#if defined(OS_MAC) +// Flaky on Mac and Windows: crbug.com/1235249 +#if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_TabsAutomationBooleanPermissions \ DISABLED_TabsAutomationBooleanPermissions #else @@ -239,8 +238,8 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, << message_; } -// Flaky on Mac: crbug.com/1235249 -#if defined(OS_MAC) +// Flaky on Mac and Windows: crbug.com/1235249 +#if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_TabsAutomationBooleanActions \ DISABLED_TabsAutomationBooleanActions #else @@ -268,8 +267,8 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, << message_; } -// Flaky on Mac: crbug.com/1235249 -#if defined(OS_MAC) +// Flaky on Mac and Windows: crbug.com/1235249 +#if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_CloseTab DISABLED_CloseTab #else #define MAYBE_CloseTab CloseTab @@ -397,14 +396,6 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, EnumValidity) { } #if defined(USE_AURA) - -IN_PROC_BROWSER_TEST_F(AutomationApiTest, IframeNav) { - StartEmbeddedTestServer(); - ASSERT_TRUE(RunExtensionTest("automation/tests/desktop", - {.page_url = "iframenav.html"})) - << message_; -} - IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopNotRequested) { ASSERT_TRUE(RunExtensionTest("automation/tests/tabs", {.page_url = "desktop_not_requested.html"})) @@ -650,6 +641,13 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_TextareaAppendPerf) { // the time spent in the renderer code. ASSERT_LT(automation_total_dur, renderer_total_dur * 2); } + +IN_PROC_BROWSER_TEST_F(AutomationApiTest, IframeNav) { + StartEmbeddedTestServer(); + ASSERT_TRUE(RunExtensionTest("automation/tests/desktop", + {.page_url = "iframenav.html"})) + << message_; +} #endif // BUILDFLAG(IS_CHROMEOS_ASH) #if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS) diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc index 020cad94e04..9b0e5439cc7 100644 --- a/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc +++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/bookmark_manager_private_api.cc @@ -333,7 +333,7 @@ ExtensionFunction::ResponseValue ClipboardBookmarkManagerFunction::CopyOrCut( ExtensionFunction::ResponseValue BookmarkManagerPrivateCopyFunction::RunOnReady() { - std::unique_ptr<Copy::Params> params(Copy::Params::Create(*args_)); + std::unique_ptr<Copy::Params> params(Copy::Params::Create(args())); if (!params) return BadMessage(); return CopyOrCut(false, params->id_list); @@ -344,7 +344,7 @@ BookmarkManagerPrivateCutFunction::RunOnReady() { if (!EditBookmarksEnabled()) return Error(bookmark_keys::kEditBookmarksDisabled); - std::unique_ptr<Cut::Params> params(Cut::Params::Create(*args_)); + std::unique_ptr<Cut::Params> params(Cut::Params::Create(args())); if (!params) return BadMessage(); return CopyOrCut(true, params->id_list); @@ -355,7 +355,7 @@ BookmarkManagerPrivatePasteFunction::RunOnReady() { if (!EditBookmarksEnabled()) return Error(bookmark_keys::kEditBookmarksDisabled); - std::unique_ptr<Paste::Params> params(Paste::Params::Create(*args_)); + std::unique_ptr<Paste::Params> params(Paste::Params::Create(args())); if (!params) return BadMessage(); BookmarkModel* model = @@ -390,7 +390,7 @@ BookmarkManagerPrivatePasteFunction::RunOnReady() { ExtensionFunction::ResponseValue BookmarkManagerPrivateCanPasteFunction::RunOnReady() { - std::unique_ptr<CanPaste::Params> params(CanPaste::Params::Create(*args_)); + std::unique_ptr<CanPaste::Params> params(CanPaste::Params::Create(args())); if (!params) return BadMessage(); @@ -413,7 +413,7 @@ BookmarkManagerPrivateSortChildrenFunction::RunOnReady() { return Error(bookmark_keys::kEditBookmarksDisabled); std::unique_ptr<SortChildren::Params> params( - SortChildren::Params::Create(*args_)); + SortChildren::Params::Create(args())); if (!params) return BadMessage(); @@ -433,12 +433,7 @@ BookmarkManagerPrivateStartDragFunction::RunOnReady() { return Error(bookmark_keys::kEditBookmarksDisabled); content::WebContents* web_contents = GetSenderWebContents(); - if (GetViewType(web_contents) != mojom::ViewType::kTabContents) { - NOTREACHED(); - return Error(kUnknownErrorDoNotUse); - } - - std::unique_ptr<StartDrag::Params> params(StartDrag::Params::Create(*args_)); + std::unique_ptr<StartDrag::Params> params(StartDrag::Params::Create(args())); if (!params) return BadMessage(); @@ -466,7 +461,7 @@ BookmarkManagerPrivateDropFunction::RunOnReady() { if (!EditBookmarksEnabled()) return Error(bookmark_keys::kEditBookmarksDisabled); - std::unique_ptr<Drop::Params> params(Drop::Params::Create(*args_)); + std::unique_ptr<Drop::Params> params(Drop::Params::Create(args())); if (!params) return BadMessage(); @@ -479,20 +474,19 @@ BookmarkManagerPrivateDropFunction::RunOnReady() { return Error(error); content::WebContents* web_contents = GetSenderWebContents(); - DCHECK_EQ(mojom::ViewType::kTabContents, GetViewType(web_contents)); - size_t drop_index; - if (params->index) + if (params->index) { drop_index = static_cast<size_t>(*params->index); - else + CHECK(drop_index >= 0 && drop_index <= drop_parent->children().size()); + } else { drop_index = drop_parent->children().size(); + } BookmarkManagerPrivateDragEventRouter* router = BookmarkManagerPrivateDragEventRouter::FromWebContents(web_contents); - DCHECK(router); const BookmarkNodeData* drag_data = router->GetBookmarkNodeData(); - DCHECK_NE(nullptr, drag_data) << "Somehow we're dropping null bookmark data"; + CHECK_NE(nullptr, drag_data) << "Somehow we're dropping null bookmark data"; const bool copy = false; chrome::DropBookmarks( GetProfile(), *drag_data, drop_parent, drop_index, copy); @@ -504,7 +498,7 @@ BookmarkManagerPrivateDropFunction::RunOnReady() { ExtensionFunction::ResponseValue BookmarkManagerPrivateGetSubtreeFunction::RunOnReady() { std::unique_ptr<GetSubtree::Params> params( - GetSubtree::Params::Create(*args_)); + GetSubtree::Params::Create(args())); if (!params) return BadMessage(); @@ -536,7 +530,7 @@ BookmarkManagerPrivateRemoveTreesFunction::RunOnReady() { return Error(bookmark_keys::kEditBookmarksDisabled); std::unique_ptr<RemoveTrees::Params> params( - RemoveTrees::Params::Create(*args_)); + RemoveTrees::Params::Create(args())); if (!params) return BadMessage(); @@ -575,6 +569,6 @@ BookmarkManagerPrivateRedoFunction::RunOnReady() { return NoArguments(); } -WEB_CONTENTS_USER_DATA_KEY_IMPL(BookmarkManagerPrivateDragEventRouter) +WEB_CONTENTS_USER_DATA_KEY_IMPL(BookmarkManagerPrivateDragEventRouter); } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc index 5cc052d294e..3db10e5480b 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc @@ -29,7 +29,7 @@ using ContextType = ExtensionApiTest::ContextType; class BookmarksApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - BookmarksApiTest() = default; + BookmarksApiTest() : ExtensionApiTest(GetParam()) {} ~BookmarksApiTest() override = default; BookmarksApiTest(const BookmarksApiTest&) = delete; BookmarksApiTest& operator=(const BookmarksApiTest&) = delete; @@ -64,10 +64,7 @@ IN_PROC_BROWSER_TEST_P(BookmarksApiTest, Bookmarks) { profile->GetPrefs()->Set(bookmarks::prefs::kManagedBookmarks, list); ASSERT_EQ(2u, managed->managed_node()->children().size()); - ASSERT_TRUE(RunExtensionTest( - "bookmarks", {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker})) - << message_; + ASSERT_TRUE(RunExtensionTest("bookmarks")) << message_; } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc index b93d8c3acac..9ca2f32f519 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc @@ -414,7 +414,7 @@ void BookmarksAPI::OnListenerAdded(const EventListenerInfo& details) { ExtensionFunction::ResponseValue BookmarksGetFunction::RunOnReady() { std::unique_ptr<api::bookmarks::Get::Params> params( - api::bookmarks::Get::Params::Create(*args_)); + api::bookmarks::Get::Params::Create(args())); if (!params) return BadMessage(); @@ -446,7 +446,7 @@ ExtensionFunction::ResponseValue BookmarksGetFunction::RunOnReady() { ExtensionFunction::ResponseValue BookmarksGetChildrenFunction::RunOnReady() { std::unique_ptr<api::bookmarks::GetChildren::Params> params( - api::bookmarks::GetChildren::Params::Create(*args_)); + api::bookmarks::GetChildren::Params::Create(args())); if (!params) return BadMessage(); @@ -466,7 +466,7 @@ ExtensionFunction::ResponseValue BookmarksGetChildrenFunction::RunOnReady() { ExtensionFunction::ResponseValue BookmarksGetRecentFunction::RunOnReady() { std::unique_ptr<api::bookmarks::GetRecent::Params> params( - api::bookmarks::GetRecent::Params::Create(*args_)); + api::bookmarks::GetRecent::Params::Create(args())); if (!params) return BadMessage(); if (params->number_of_items < 1) { @@ -500,7 +500,7 @@ ExtensionFunction::ResponseValue BookmarksGetTreeFunction::RunOnReady() { ExtensionFunction::ResponseValue BookmarksGetSubTreeFunction::RunOnReady() { std::unique_ptr<api::bookmarks::GetSubTree::Params> params( - api::bookmarks::GetSubTree::Params::Create(*args_)); + api::bookmarks::GetSubTree::Params::Create(args())); if (!params) return BadMessage(); @@ -517,7 +517,7 @@ ExtensionFunction::ResponseValue BookmarksGetSubTreeFunction::RunOnReady() { ExtensionFunction::ResponseValue BookmarksSearchFunction::RunOnReady() { std::unique_ptr<api::bookmarks::Search::Params> params( - api::bookmarks::Search::Params::Create(*args_)); + api::bookmarks::Search::Params::Create(args())); if (!params) return BadMessage(); @@ -562,7 +562,7 @@ ExtensionFunction::ResponseValue BookmarksRemoveFunctionBase::RunOnReady() { return Error(bookmark_api_constants::kEditBookmarksDisabled); std::unique_ptr<api::bookmarks::Remove::Params> params( - api::bookmarks::Remove::Params::Create(*args_)); + api::bookmarks::Remove::Params::Create(args())); if (!params) return BadMessage(); @@ -594,7 +594,7 @@ ExtensionFunction::ResponseValue BookmarksCreateFunction::RunOnReady() { return Error(bookmark_api_constants::kEditBookmarksDisabled); std::unique_ptr<api::bookmarks::Create::Params> params( - api::bookmarks::Create::Params::Create(*args_)); + api::bookmarks::Create::Params::Create(args())); if (!params) return BadMessage(); @@ -616,7 +616,7 @@ ExtensionFunction::ResponseValue BookmarksMoveFunction::RunOnReady() { return Error(bookmark_api_constants::kEditBookmarksDisabled); std::unique_ptr<api::bookmarks::Move::Params> params( - api::bookmarks::Move::Params::Create(*args_)); + api::bookmarks::Move::Params::Create(args())); if (!params) return BadMessage(); @@ -668,7 +668,7 @@ ExtensionFunction::ResponseValue BookmarksUpdateFunction::RunOnReady() { return Error(bookmark_api_constants::kEditBookmarksDisabled); std::unique_ptr<api::bookmarks::Update::Params> params( - api::bookmarks::Update::Params::Create(*args_)); + api::bookmarks::Update::Params::Create(args())); if (!params) return BadMessage(); diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc b/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc index 382c2e5849b..58ef964569a 100644 --- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc +++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_controller_brlapi.cc @@ -33,13 +33,11 @@ namespace { // Delay between detecting a directory update and trying to connect // to the brlapi. -constexpr base::TimeDelta kConnectionDelay = - base::TimeDelta::FromMilliseconds(500); +constexpr base::TimeDelta kConnectionDelay = base::Milliseconds(500); // How long to periodically retry connecting after a brltty restart. // Some displays are slow to connect. -constexpr base::TimeDelta kConnectRetryTimeout = - base::TimeDelta::FromSeconds(20); +constexpr base::TimeDelta kConnectRetryTimeout = base::Seconds(20); } // namespace diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc index 40e9c04cd8f..aaeafaa4ba5 100644 --- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc +++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.cc @@ -160,7 +160,7 @@ BrailleDisplayPrivateWriteDotsFunction:: } bool BrailleDisplayPrivateWriteDotsFunction::Prepare() { - params_ = WriteDots::Params::Create(*args_); + params_ = WriteDots::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_); EXTENSION_FUNCTION_VALIDATE( params_->cells.size() >= @@ -183,8 +183,9 @@ BrailleDisplayPrivateUpdateBluetoothBrailleDisplayAddressFunction::Run() { NOTREACHED(); return RespondNow(Error("Unsupported on this platform.")); #else - std::string address; - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &address)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 1); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); + const std::string& address = args()[0].GetString(); ash::AccessibilityManager::Get()->UpdateBluetoothBrailleDisplayAddress( address); return RespondNow(NoArguments()); diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc index 315a86502c5..8951285895f 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.cc @@ -290,19 +290,17 @@ ExtensionFunction::ResponseAction BrowsingDataRemoverFunction::Run() { DCHECK(profile); // Grab the initial |options| parameter, and parse out the arguments. - base::DictionaryValue* options; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &options)); - DCHECK(options); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 1); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_dict()); + const base::Value& options = args()[0]; - EXTENSION_FUNCTION_VALIDATE( - ParseOriginTypeMask(*options, &origin_type_mask_)); + EXTENSION_FUNCTION_VALIDATE(ParseOriginTypeMask(options, &origin_type_mask_)); // If |ms_since_epoch| isn't set, default it to 0. - double ms_since_epoch; - if (!options->GetDouble(extension_browsing_data_api_constants::kSinceKey, - &ms_since_epoch)) { - ms_since_epoch = 0; - } + double ms_since_epoch = + options.FindDoubleKey(extension_browsing_data_api_constants::kSinceKey) + .value_or(0); + // base::Time takes a double that represents seconds since epoch. JavaScript // gives developers milliseconds, so do a quick conversion before populating // the object. @@ -310,10 +308,10 @@ ExtensionFunction::ResponseAction BrowsingDataRemoverFunction::Run() { EXTENSION_FUNCTION_VALIDATE(GetRemovalMask(&removal_mask_)); - base::Value* origins = - options->FindKeyOfType(extension_browsing_data_api_constants::kOriginsKey, - base::Value::Type::LIST); - base::Value* exclude_origins = options->FindKeyOfType( + const base::Value* origins = + options.FindKeyOfType(extension_browsing_data_api_constants::kOriginsKey, + base::Value::Type::LIST); + const base::Value* exclude_origins = options.FindKeyOfType( extension_browsing_data_api_constants::kExcludeOriginsKey, base::Value::Type::LIST); @@ -416,54 +414,63 @@ void BrowsingDataRemoverFunction::StartRemoving() { } bool BrowsingDataRemoverFunction::ParseOriginTypeMask( - const base::DictionaryValue& options, + const base::Value& options, uint64_t* origin_type_mask) { + DCHECK(options.is_dict()); + // Parse the |options| dictionary to generate the origin set mask. Default to // UNPROTECTED_WEB if the developer doesn't specify anything. *origin_type_mask = content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB; - const base::DictionaryValue* d = nullptr; - if (options.HasKey(extension_browsing_data_api_constants::kOriginTypesKey)) { - if (!options.GetDictionary( - extension_browsing_data_api_constants::kOriginTypesKey, &d)) { + const base::Value* origin_type_dict = + options.FindKey(extension_browsing_data_api_constants::kOriginTypesKey); + if (!origin_type_dict) + return true; + + if (!origin_type_dict->is_dict()) + return false; + + const base::Value* option = nullptr; + + // The developer specified something! Reset to 0 and parse the dictionary. + *origin_type_mask = 0; + + // Unprotected web. + option = origin_type_dict->FindKey( + extension_browsing_data_api_constants::kUnprotectedWebKey); + if (option) { + if (!option->is_bool()) return false; - } - bool value; - - // The developer specified something! Reset to 0 and parse the dictionary. - *origin_type_mask = 0; - - // Unprotected web. - if (d->HasKey(extension_browsing_data_api_constants::kUnprotectedWebKey)) { - if (!d->GetBoolean( - extension_browsing_data_api_constants::kUnprotectedWebKey, - &value)) { - return false; - } - *origin_type_mask |= - value ? content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB : 0; - } - // Protected web. - if (d->HasKey(extension_browsing_data_api_constants::kProtectedWebKey)) { - if (!d->GetBoolean( - extension_browsing_data_api_constants::kProtectedWebKey, - &value)) { - return false; - } - *origin_type_mask |= - value ? content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB : 0; - } + *origin_type_mask |= + option->GetBool() + ? content::BrowsingDataRemover::ORIGIN_TYPE_UNPROTECTED_WEB + : 0; + } - // Extensions. - if (d->HasKey(extension_browsing_data_api_constants::kExtensionsKey)) { - if (!d->GetBoolean(extension_browsing_data_api_constants::kExtensionsKey, - &value)) { - return false; - } - *origin_type_mask |= - value ? chrome_browsing_data_remover::ORIGIN_TYPE_EXTENSION : 0; - } + // Protected web. + option = origin_type_dict->FindKey( + extension_browsing_data_api_constants::kProtectedWebKey); + if (option) { + if (!option->is_bool()) + return false; + + *origin_type_mask |= + option->GetBool() + ? content::BrowsingDataRemover::ORIGIN_TYPE_PROTECTED_WEB + : 0; + } + + // Extensions. + option = origin_type_dict->FindKey( + extension_browsing_data_api_constants::kExtensionsKey); + if (option) { + if (!option->is_bool()) + return false; + + *origin_type_mask |= + option->GetBool() ? chrome_browsing_data_remover::ORIGIN_TYPE_EXTENSION + : 0; } return true; @@ -495,18 +502,15 @@ bool BrowsingDataRemoverFunction::ParseOrigins(const base::Value& list_value, // Returns false if parse was not successful, i.e. if 'dataToRemove' is not // present or any data-type keys don't have supported (boolean) values. bool BrowsingDataRemoveFunction::GetRemovalMask(uint64_t* removal_mask) { - base::DictionaryValue* data_to_remove; - if (!args_->GetDictionary(1, &data_to_remove)) + if (args().size() <= 1 || !args()[1].is_dict()) return false; *removal_mask = 0; - for (base::DictionaryValue::Iterator i(*data_to_remove); - !i.IsAtEnd(); - i.Advance()) { - if (!i.value().is_bool()) + for (const auto kv : args()[1].DictItems()) { + if (!kv.second.is_bool()) return false; - if (i.value().GetBool()) - *removal_mask |= MaskForKey(i.key().c_str()); + if (kv.second.GetBool()) + *removal_mask |= MaskForKey(kv.first.c_str()); } return true; diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h index 6d84cfdeb60..04f9b7d61b4 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_api.h @@ -125,7 +125,8 @@ class BrowsingDataRemoverFunction // Parse the developer-provided |origin_types| object into |origin_type_mask| // that can be used with the BrowsingDataRemover. // Returns true if parsing was successful. - bool ParseOriginTypeMask(const base::DictionaryValue& options, + // Pre-condition: `options` is a dictionary. + bool ParseOriginTypeMask(const base::Value& options, uint64_t* origin_type_mask); // Parses the developer-provided list of origins into |result|. diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc index ea119c1216b..2371bb84121 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_unittest.cc @@ -62,12 +62,6 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase { remover_ = profile()->GetBrowsingDataRemover(); remover_->SetEmbedderDelegate(&delegate_); - - // TODO(crbug.com/1182630): This can be removed once crbug.com/1182630 is - // fixed. Make sure quota manager for storage partition is finished - // initializing. - profile()->GetDefaultStoragePartition(); - task_environment()->RunUntilIdle(); } void TearDown() override { @@ -154,8 +148,8 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase { EXPECT_TRUE(result_value->GetAsDictionary(&result)); base::DictionaryValue* options; EXPECT_TRUE(result->GetDictionary("options", &options)); - double since; - EXPECT_TRUE(options->GetDouble("since", &since)); + absl::optional<double> since = options->FindDoubleKey("since"); + ASSERT_TRUE(since); double expected_since = 0; if (since_pref != browsing_data::TimePeriod::ALL_TIME) { @@ -167,7 +161,7 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase { // second, so we'll make sure the requested start time is within 10 seconds. // Since the smallest selectable period is an hour, that should be // sufficient. - EXPECT_LE(expected_since, since + 10.0 * 1000.0); + EXPECT_LE(expected_since, *since + 10.0 * 1000.0); } void SetPrefsAndVerifySettings(int data_type_flags, diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc index 4116e8c5941..ddec95aaff4 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.cc @@ -28,13 +28,13 @@ #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" #include "third_party/boringssl/src/include/openssl/ssl.h" -namespace api_cp = extensions::api::certificate_provider; -namespace api_cpi = extensions::api::certificate_provider_internal; -using PinCodeType = chromeos::security_token_pin::CodeType; -using PinErrorLabel = chromeos::security_token_pin::ErrorLabel; - namespace { +namespace api_cp = ::extensions::api::certificate_provider; +namespace api_cpi = ::extensions::api::certificate_provider_internal; +using PinCodeType = ::ash::security_token_pin::CodeType; +using PinErrorLabel = ::ash::security_token_pin::ErrorLabel; + PinErrorLabel GetErrorLabelForDialog(api_cp::PinRequestErrorType error_type) { switch (error_type) { case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_INVALID_PIN: @@ -283,7 +283,7 @@ CertificateProviderInternalReportCertificatesFunction:: ExtensionFunction::ResponseAction CertificateProviderInternalReportCertificatesFunction::Run() { std::unique_ptr<api_cpi::ReportCertificates::Params> params( - api_cpi::ReportCertificates::Params::Create(*args_)); + api_cpi::ReportCertificates::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); ash::CertificateProviderService* const service = @@ -336,7 +336,7 @@ CertificateProviderStopPinRequestFunction:: ExtensionFunction::ResponseAction CertificateProviderStopPinRequestFunction::Run() { std::unique_ptr<api_cp::StopPinRequest::Params> params( - api_cp::StopPinRequest::Params::Create(*args_)); + api_cp::StopPinRequest::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); // TODO(crbug.com/1046860): Remove logging after stabilizing the feature. @@ -419,7 +419,7 @@ void CertificateProviderRequestPinFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristic::Config short_limit_config = { api::certificate_provider::kMaxClosedDialogsPerMinute - 1, - base::TimeDelta::FromMinutes(1)}; + base::Minutes(1)}; heuristics->push_back(std::make_unique<QuotaService::TimedLimit>( short_limit_config, std::make_unique<RequestPinExceptFirstQuotaBucketMapper>(), @@ -427,7 +427,7 @@ void CertificateProviderRequestPinFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristic::Config long_limit_config = { api::certificate_provider::kMaxClosedDialogsPer10Minutes - 1, - base::TimeDelta::FromMinutes(10)}; + base::Minutes(10)}; heuristics->push_back(std::make_unique<QuotaService::TimedLimit>( long_limit_config, std::make_unique<RequestPinExceptFirstQuotaBucketMapper>(), @@ -436,7 +436,7 @@ void CertificateProviderRequestPinFunction::GetQuotaLimitHeuristics( ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() { std::unique_ptr<api_cp::RequestPin::Params> params( - api_cp::RequestPin::Params::Create(*args_)); + api_cp::RequestPin::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const api_cp::PinRequestType pin_request_type = @@ -524,7 +524,7 @@ CertificateProviderSetCertificatesFunction:: ExtensionFunction::ResponseAction CertificateProviderSetCertificatesFunction::Run() { std::unique_ptr<api_cp::SetCertificates::Params> params( - api_cp::SetCertificates::Params::Create(*args_)); + api_cp::SetCertificates::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); if (!params->details.client_certificates.empty() && params->details.error) { @@ -576,7 +576,7 @@ CertificateProviderInternalReportSignatureFunction:: ExtensionFunction::ResponseAction CertificateProviderInternalReportSignatureFunction::Run() { std::unique_ptr<api_cpi::ReportSignature::Params> params( - api_cpi::ReportSignature::Params::Create(*args_)); + api_cpi::ReportSignature::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); ash::CertificateProviderService* const service = @@ -605,7 +605,7 @@ CertificateProviderReportSignatureFunction:: ExtensionFunction::ResponseAction CertificateProviderReportSignatureFunction::Run() { std::unique_ptr<api_cp::ReportSignature::Params> params( - api_cp::ReportSignature::Params::Create(*args_)); + api_cp::ReportSignature::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); if (params->details.signature && !params->details.signature->empty() && diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc index 11c6ad33fe3..a6b7a0d09e7 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_apitest.cc @@ -21,6 +21,7 @@ #include "base/memory/scoped_refptr.h" #include "base/path_service.h" #include "base/run_loop.h" +#include "base/scoped_observation.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" @@ -42,9 +43,6 @@ #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" -#include "content/public/browser/notification_details.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_source.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/browser_test.h" @@ -52,15 +50,17 @@ #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" #include "crypto/rsa_private_key.h" +#include "extensions/browser/api/test/test_api_observer.h" +#include "extensions/browser/api/test/test_api_observer_registry.h" #include "extensions/browser/disable_reason.h" +#include "extensions/browser/extension_host_test_helper.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" -#include "extensions/browser/notification_types.h" #include "extensions/browser/process_manager.h" #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/common/extension.h" +#include "extensions/common/mojom/view_type.mojom.h" #include "extensions/test/extension_test_message_listener.h" -#include "extensions/test/test_background_page_first_load_observer.h" #include "net/cert/x509_certificate.h" #include "net/http/http_status_code.h" #include "net/ssl/client_cert_identity.h" @@ -175,8 +175,28 @@ std::string GetCertFingerprint1(const net::X509Certificate& cert) { return base::ToLowerASCII(base::HexEncode(hash, base::kSHA1Length)); } -class CertificateProviderApiTest : public extensions::ExtensionApiTest, - public content::NotificationObserver { +// Generates a gtest failure whenever extension JS reports failure. +class JsFailureObserver : public extensions::TestApiObserver { + public: + JsFailureObserver() { + test_api_observation_.Observe( + extensions::TestApiObserverRegistry::GetInstance()); + } + ~JsFailureObserver() override = default; + + void OnTestFailed(content::BrowserContext* browser_context, + const std::string& message) override { + ADD_FAILURE() << "Received failure notification from the JS side: " + << message; + } + + private: + base::ScopedObservation<extensions::TestApiObserverRegistry, + extensions::TestApiObserver> + test_api_observation_{this}; +}; + +class CertificateProviderApiTest : public extensions::ExtensionApiTest { public: CertificateProviderApiTest() {} @@ -194,9 +214,7 @@ class CertificateProviderApiTest : public extensions::ExtensionApiTest, // Observe all assertion failures in the JS code, even those that happen // when there's no active `ResultCatcher`. - notification_registrar_.Add(this, - extensions::NOTIFICATION_EXTENSION_TEST_FAILED, - content::NotificationService::AllSources()); + js_failure_observer_ = std::make_unique<JsFailureObserver>(); // Set up the AutoSelectCertificateForUrls policy to avoid the client // certificate selection dialog. @@ -281,14 +299,6 @@ class CertificateProviderApiTest : public extensions::ExtensionApiTest, private: const char* const kClientCertUrl = "/client-cert"; - // content::NotificationObserver: - void Observe(int type, - const content::NotificationSource&, - const content::NotificationDetails&) override { - DCHECK_EQ(type, extensions::NOTIFICATION_EXTENSION_TEST_FAILED); - ADD_FAILURE() << "Received failure notification from the JS side"; - } - std::unique_ptr<net::test_server::HttpResponse> OnHttpsServerRequested( const net::test_server::HttpRequest& request) const { if (request.relative_url != kClientCertUrl) @@ -304,7 +314,7 @@ class CertificateProviderApiTest : public extensions::ExtensionApiTest, return response; } - content::NotificationRegistrar notification_registrar_; + std::unique_ptr<JsFailureObserver> js_failure_observer_; std::unique_ptr<net::EmbeddedTestServer> https_server_; }; @@ -318,8 +328,8 @@ class CertificateProviderApiMockedExtensionTest extension_path_ = test_data_dir_.AppendASCII("certificate_provider"); extension_ = LoadExtension(extension_path_); - ui_test_utils::NavigateToURL(browser(), - extension_->GetResourceURL("basic.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension_->GetResourceURL("basic.html"))); extension_contents_ = browser()->tab_strip_model()->GetActiveWebContents(); @@ -510,8 +520,8 @@ class CertificateProviderRequestPinTest : public CertificateProviderApiTest { } void NavigateTo(const std::string& test_page_file_name) { - ui_test_utils::NavigateToURL( - browser(), extension_->GetResourceURL(test_page_file_name)); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension_->GetResourceURL(test_page_file_name))); } ash::RequestPinView* GetActivePinDialogView() { @@ -936,9 +946,10 @@ IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, LazyBackgroundPage) { // Load the test extension. TestCertificateProviderExtension test_certificate_provider_extension( profile()); - extensions::TestBackgroundPageFirstLoadObserver - test_background_page_first_load_observer( - profile(), TestCertificateProviderExtension::extension_id()); + extensions::ExtensionHostTestHelper host_helper( + profile(), TestCertificateProviderExtension::extension_id()); + host_helper.RestrictToType( + extensions::mojom::ViewType::kExtensionBackgroundPage); const extensions::Extension* const extension = LoadExtension(base::PathService::CheckedGet(chrome::DIR_TEST_DATA) .AppendASCII("extensions") @@ -946,7 +957,7 @@ IN_PROC_BROWSER_TEST_F(CertificateProviderApiTest, LazyBackgroundPage) { .AppendASCII("extension")); ASSERT_TRUE(extension); EXPECT_EQ(extension->id(), TestCertificateProviderExtension::extension_id()); - test_background_page_first_load_observer.Wait(); + host_helper.WaitForHostCompletedFirstLoad(); // Navigate to the page that requests the client authentication. Use the // incognito profile in order to force re-authentication in the later request diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc index ff81674b20e..d96a8df0b0b 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc @@ -39,13 +39,12 @@ #include "chrome/browser/guest_view/web_view/chrome_web_view_permission_helper_delegate.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" -#include "chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.h" #include "chrome/browser/ui/webui/devtools_ui.h" #include "chrome/common/buildflags.h" #include "chrome/common/url_constants.h" #include "chrome/common/webui_url_constants.h" -#include "components/pdf/browser/pdf_web_contents_helper.h" #include "components/signin/core/browser/signin_header_helper.h" +#include "components/value_store/value_store_factory.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" @@ -60,8 +59,8 @@ #include "extensions/browser/guest_view/web_view/web_view_guest.h" #include "extensions/browser/guest_view/web_view/web_view_permission_helper.h" #include "extensions/browser/supervised_user_extensions_delegate.h" -#include "extensions/browser/value_store/value_store_factory.h" #include "google_apis/gaia/gaia_urls.h" +#include "pdf/buildflags.h" #include "printing/buildflags/buildflags.h" #include "services/network/public/mojom/fetch_api.mojom-shared.h" #include "url/gurl.h" @@ -77,6 +76,11 @@ #include "chrome/browser/extensions/clipboard_extension_helper_chromeos.h" #endif +#if BUILDFLAG(ENABLE_PDF) +#include "chrome/browser/ui/pdf/chrome_pdf_web_contents_helper_client.h" +#include "components/pdf/browser/pdf_web_contents_helper.h" +#endif + #if BUILDFLAG(ENABLE_PRINTING) #include "chrome/browser/printing/printing_init.h" #endif @@ -95,7 +99,7 @@ ChromeExtensionsAPIClient::~ChromeExtensionsAPIClient() {} void ChromeExtensionsAPIClient::AddAdditionalValueStoreCaches( content::BrowserContext* context, - const scoped_refptr<ValueStoreFactory>& factory, + const scoped_refptr<value_store::ValueStoreFactory>& factory, const scoped_refptr<base::ObserverListThreadSafe<SettingsObserver>>& observers, std::map<settings_namespace::Namespace, ValueStoreCache*>* caches) { @@ -114,8 +118,10 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers( #if BUILDFLAG(ENABLE_PRINTING) printing::InitializePrinting(web_contents); #endif +#if BUILDFLAG(ENABLE_PDF) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents, std::make_unique<ChromePDFWebContentsHelperClient>()); +#endif extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents); diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h index f9cab008394..3a8310801c6 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h @@ -20,12 +20,17 @@ class ClipboardExtensionHelper; class ChromeExtensionsAPIClient : public ExtensionsAPIClient { public: ChromeExtensionsAPIClient(); + + ChromeExtensionsAPIClient(const ChromeExtensionsAPIClient&) = delete; + ChromeExtensionsAPIClient& operator=(const ChromeExtensionsAPIClient&) = + delete; + ~ChromeExtensionsAPIClient() override; // ExtensionsApiClient implementation. void AddAdditionalValueStoreCaches( content::BrowserContext* context, - const scoped_refptr<ValueStoreFactory>& factory, + const scoped_refptr<value_store::ValueStoreFactory>& factory, const scoped_refptr<base::ObserverListThreadSafe<SettingsObserver>>& observers, std::map<settings_namespace::Namespace, ValueStoreCache*>* caches) @@ -113,8 +118,6 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient { #endif std::unique_ptr<extensions::ChromeAutomationInternalApiDelegate> extensions_automation_api_delegate_; - - DISALLOW_COPY_AND_ASSIGN(ChromeExtensionsAPIClient); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc index 3e0894094e2..e5b923b2eb4 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client_unittest.cc @@ -19,9 +19,12 @@ class ChromeExtensionsAPIClientTest : public testing::Test { public: ChromeExtensionsAPIClientTest() = default; + ChromeExtensionsAPIClientTest(const ChromeExtensionsAPIClientTest&) = delete; + ChromeExtensionsAPIClientTest& operator=( + const ChromeExtensionsAPIClientTest&) = delete; + private: content::BrowserTaskEnvironment task_environment_; - DISALLOW_COPY_AND_ASSIGN(ChromeExtensionsAPIClientTest); }; TEST_F(ChromeExtensionsAPIClientTest, ShouldHideResponseHeader) { diff --git a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc index 7bcc6848f6f..ad5c00727f1 100644 --- a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc +++ b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.cc @@ -23,7 +23,7 @@ namespace command_line_private = api::command_line_private; ExtensionFunction::ResponseAction CommandLinePrivateHasSwitchFunction::Run() { std::unique_ptr<command_line_private::HasSwitch::Params> params( - command_line_private::HasSwitch::Params::Create(*args_)); + command_line_private::HasSwitch::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); if (params->name.empty()) diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.h b/chromium/chrome/browser/extensions/api/commands/command_service.h index 161b2e30126..620234bd409 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.h +++ b/chromium/chrome/browser/extensions/api/commands/command_service.h @@ -91,6 +91,10 @@ class CommandService : public BrowserContextKeyedAPI, // Constructs a CommandService object for the given profile. explicit CommandService(content::BrowserContext* context); + + CommandService(const CommandService&) = delete; + CommandService& operator=(const CommandService&) = delete; + ~CommandService() override; // BrowserContextKeyedAPI implementation. @@ -225,8 +229,6 @@ class CommandService : public BrowserContextKeyedAPI, extension_registry_observation_{this}; base::ObserverList<Observer>::Unchecked observers_; - - DISALLOW_COPY_AND_ASSIGN(CommandService); }; template <> diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc index c354df6f150..a570018293f 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.cc @@ -55,19 +55,17 @@ namespace pref_keys = extensions::preference_api_constants; namespace { -bool RemoveContentType(base::ListValue* args, +bool RemoveContentType(std::vector<base::Value>& args, ContentSettingsType* content_type) { - base::Value::ListView args_view = args->GetList(); - - if (args_view.empty() || !args_view[0].is_string()) + if (args.empty() || !args[0].is_string()) return false; // Not a ref since we remove the underlying value after. - std::string content_type_str = args_view[0].GetString(); + std::string content_type_str = args[0].GetString(); // We remove the ContentSettingsType parameter since this is added by the // renderer, and is not part of the JSON schema. - args->EraseListIter(args_view.begin()); + args.erase(args.begin()); *content_type = extensions::content_settings_helpers::StringToContentSettingsType( content_type_str); @@ -81,9 +79,9 @@ namespace extensions { ExtensionFunction::ResponseAction ContentSettingsContentSettingClearFunction::Run() { ContentSettingsType content_type; - EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); + EXTENSION_FUNCTION_VALIDATE(RemoveContentType(mutable_args(), &content_type)); - std::unique_ptr<Clear::Params> params(Clear::Params::Create(*args_)); + std::unique_ptr<Clear::Params> params(Clear::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); ExtensionPrefsScope scope = kExtensionPrefsScopeRegular; @@ -115,9 +113,9 @@ ContentSettingsContentSettingClearFunction::Run() { ExtensionFunction::ResponseAction ContentSettingsContentSettingGetFunction::Run() { ContentSettingsType content_type; - EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); + EXTENSION_FUNCTION_VALIDATE(RemoveContentType(mutable_args(), &content_type)); - std::unique_ptr<Get::Params> params(Get::Params::Create(*args_)); + std::unique_ptr<Get::Params> params(Get::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); @@ -183,9 +181,9 @@ ContentSettingsContentSettingGetFunction::Run() { ExtensionFunction::ResponseAction ContentSettingsContentSettingSetFunction::Run() { ContentSettingsType content_type; - EXTENSION_FUNCTION_VALIDATE(RemoveContentType(args_.get(), &content_type)); + EXTENSION_FUNCTION_VALIDATE(RemoveContentType(mutable_args(), &content_type)); - std::unique_ptr<Set::Params> params(Set::Params::Create(*args_)); + std::unique_ptr<Set::Params> params(Set::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string primary_error; diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc index a6bf54ae80e..1c14d572486 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_apitest.cc @@ -50,7 +50,9 @@ using ContextType = ExtensionApiTest::ContextType; class ExtensionContentSettingsApiTest : public ExtensionApiTest { public: - ExtensionContentSettingsApiTest() = default; + explicit ExtensionContentSettingsApiTest( + ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) {} ~ExtensionContentSettingsApiTest() override = default; ExtensionContentSettingsApiTest(const ExtensionContentSettingsApiTest&) = delete; @@ -233,19 +235,13 @@ class ExtensionContentSettingsApiTestWithContextType : public ExtensionContentSettingsApiTest, public testing::WithParamInterface<ContextType> { public: - ExtensionContentSettingsApiTestWithContextType() = default; + ExtensionContentSettingsApiTestWithContextType() + : ExtensionContentSettingsApiTest(GetParam()) {} ~ExtensionContentSettingsApiTestWithContextType() override = default; ExtensionContentSettingsApiTestWithContextType( const ExtensionContentSettingsApiTestWithContextType&) = delete; ExtensionContentSettingsApiTestWithContextType& operator=( const ExtensionContentSettingsApiTestWithContextType&) = delete; - - protected: - bool RunLazyTest(const char* extension_name) { - return RunExtensionTest( - extension_name, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -255,8 +251,7 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, ExtensionContentSettingsApiTestWithContextType, ::testing::Values(ContextType::kServiceWorker)); -IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiTestWithContextType, - Standard) { +IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, Standard) { CheckContentSettingsDefault(); static constexpr char kExtensionPath[] = "content_settings/standard"; @@ -292,7 +287,7 @@ IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiTestWithContextType, IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiTestWithContextType, ClearProperlyGranular) { const char kExtensionPath[] = "content_settings/clearproperlygranular"; - EXPECT_TRUE(RunLazyTest(kExtensionPath)) << message_; + EXPECT_TRUE(RunExtensionTest(kExtensionPath)) << message_; } // Tests if changing permissions in incognito mode keeps the previous state of @@ -341,7 +336,7 @@ IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiTestWithContextType, EmbeddedSettingsMetric) { base::HistogramTester histogram_tester; const char kExtensionPath[] = "content_settings/embeddedsettingsmetric"; - EXPECT_TRUE(RunLazyTest(kExtensionPath)) << message_; + EXPECT_TRUE(RunExtensionTest(kExtensionPath)) << message_; size_t num_values = 0; int images_type = ContentSettingTypeToHistogramValue( @@ -366,8 +361,7 @@ IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiTestWithContextType, "ContentSettings.ExtensionNonEmbeddedSettingSet", 2); } -IN_PROC_BROWSER_TEST_P(ExtensionContentSettingsApiTestWithContextType, - ConsoleErrorTest) { +IN_PROC_BROWSER_TEST_F(ExtensionContentSettingsApiTest, ConsoleErrorTest) { constexpr char kExtensionPath[] = "content_settings/disablepluginsapi"; const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII(kExtensionPath)); diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc index da7ec8a3230..64416847f95 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.cc @@ -20,8 +20,7 @@ CustomExtensionProvider::CustomExtensionProvider( extensions_settings_->AddObserver(this); } -CustomExtensionProvider::~CustomExtensionProvider() { -} +CustomExtensionProvider::~CustomExtensionProvider() = default; std::unique_ptr<RuleIterator> CustomExtensionProvider::GetRuleIterator( ContentSettingsType content_type, @@ -49,8 +48,10 @@ void CustomExtensionProvider::OnContentSettingChanged( bool incognito) { if (incognito_ != incognito) return; - // TODO(markusheintz): Be more concise. - NotifyObservers(ContentSettingsPattern(), ContentSettingsPattern(), + // TODO(1245927): Be more concise and use the type/pattern that actually + // changed. + NotifyObservers(ContentSettingsPattern::Wildcard(), + ContentSettingsPattern::Wildcard(), ContentSettingsType::DEFAULT); } diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h index 0d0f6982cda..83bbe5e51d7 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_custom_extension_provider.h @@ -22,6 +22,9 @@ class CustomExtensionProvider : public ObservableProvider, extensions_settings, bool incognito); + CustomExtensionProvider(const CustomExtensionProvider&) = delete; + CustomExtensionProvider& operator=(const CustomExtensionProvider&) = delete; + ~CustomExtensionProvider() override; // ProviderInterface methods: @@ -52,8 +55,6 @@ class CustomExtensionProvider : public ObservableProvider, // The backend storing content setting rules defined by extensions. scoped_refptr<extensions::ContentSettingsStore> extensions_settings_; - - DISALLOW_COPY_AND_ASSIGN(CustomExtensionProvider); }; } // namespace content_settings diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.h index ce32761a495..366b1663c64 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.h +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.h @@ -24,6 +24,10 @@ class ContentSettingsService : public BrowserContextKeyedAPI, public EarlyExtensionPrefsObserver { public: explicit ContentSettingsService(content::BrowserContext* context); + + ContentSettingsService(const ContentSettingsService&) = delete; + ContentSettingsService& operator=(const ContentSettingsService&) = delete; + ~ContentSettingsService() override; scoped_refptr<ContentSettingsStore> content_settings_store() const { @@ -61,8 +65,6 @@ class ContentSettingsService : public BrowserContextKeyedAPI, scoped_refptr<ContentSettingsStore> content_settings_store_; base::ScopedObservation<ExtensionPrefs, ExtensionPrefsObserver> scoped_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(ContentSettingsService); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h index d55cf77c667..714eb5d6cc2 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_store.h @@ -52,6 +52,9 @@ class ContentSettingsStore ContentSettingsStore(); + ContentSettingsStore(const ContentSettingsStore&) = delete; + ContentSettingsStore& operator=(const ContentSettingsStore&) = delete; + // ////////////////////////////////////////////////////////////////////////// std::unique_ptr<content_settings::RuleIterator> GetRuleIterator( @@ -148,8 +151,6 @@ class ContentSettingsStore base::ObserverList<Observer, false>::Unchecked observers_; mutable base::Lock lock_; - - DISALLOW_COPY_AND_ASSIGN(ContentSettingsStore); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc b/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc index 86291367f06..0d209fec96a 100644 --- a/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc +++ b/chromium/chrome/browser/extensions/api/context_menus/context_menu_apitest.cc @@ -32,7 +32,9 @@ using ContextType = ExtensionBrowserTest::ContextType; class ExtensionContextMenuApiTest : public ExtensionApiTest { public: - ExtensionContextMenuApiTest() = default; + explicit ExtensionContextMenuApiTest( + ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) {} ~ExtensionContextMenuApiTest() override = default; ExtensionContextMenuApiTest(const ExtensionContextMenuApiTest&) = delete; ExtensionContextMenuApiTest& operator=(const ExtensionContextMenuApiTest&) = @@ -43,19 +45,13 @@ class ExtensionContextMenuApiTestWithContextType : public ExtensionContextMenuApiTest, public testing::WithParamInterface<ContextType> { public: - ExtensionContextMenuApiTestWithContextType() = default; + ExtensionContextMenuApiTestWithContextType() + : ExtensionContextMenuApiTest(GetParam()) {} ~ExtensionContextMenuApiTestWithContextType() override = default; ExtensionContextMenuApiTestWithContextType( const ExtensionContextMenuApiTestWithContextType&) = delete; ExtensionContextMenuApiTestWithContextType& operator=( const ExtensionContextMenuApiTestWithContextType&) = delete; - - protected: - bool RunTest(const char* path) { - return RunExtensionTest( - path, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -78,7 +74,7 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, ::testing::Values(ContextType::kServiceWorker)); IN_PROC_BROWSER_TEST_P(ExtensionContextMenuApiLazyTest, ContextMenus) { - ASSERT_TRUE(RunTest("context_menus/event_page")) << message_; + ASSERT_TRUE(RunExtensionTest("context_menus/event_page")) << message_; } // crbug.com/51436 -- creating context menus from multiple script contexts @@ -86,40 +82,41 @@ IN_PROC_BROWSER_TEST_P(ExtensionContextMenuApiLazyTest, ContextMenus) { IN_PROC_BROWSER_TEST_P(ExtensionContextMenuApiTestWithContextType, ContextMenusFromMultipleContexts) { ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(RunTest("context_menus/add_from_multiple_contexts")) << message_; + ASSERT_TRUE(RunExtensionTest("context_menus/add_from_multiple_contexts")) + << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; { // Tell the extension to update the page action state. ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - extension->GetResourceURL("popup.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension->GetResourceURL("popup.html"))); ASSERT_TRUE(catcher.GetNextResult()); } { // Tell the extension to update the page action state again. ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - extension->GetResourceURL("popup2.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension->GetResourceURL("popup2.html"))); ASSERT_TRUE(catcher.GetNextResult()); } } IN_PROC_BROWSER_TEST_P(ExtensionContextMenuApiTestWithContextType, ContextMenusBasics) { - ASSERT_TRUE(RunTest("context_menus/basics")) << message_; + ASSERT_TRUE(RunExtensionTest("context_menus/basics")) << message_; } IN_PROC_BROWSER_TEST_P(ExtensionContextMenuApiTestWithContextType, ContextMenusNoPerms) { - ASSERT_TRUE(RunTest("context_menus/no_perms")) << message_; + ASSERT_TRUE(RunExtensionTest("context_menus/no_perms")) << message_; } IN_PROC_BROWSER_TEST_P(ExtensionContextMenuApiTestWithContextType, ContextMenusMultipleIds) { - ASSERT_TRUE(RunTest("context_menus/item_ids")) << message_; + ASSERT_TRUE(RunExtensionTest("context_menus/item_ids")) << message_; } class ExtensionContextMenuVisibilityApiTest @@ -128,6 +125,11 @@ class ExtensionContextMenuVisibilityApiTest ExtensionContextMenuVisibilityApiTest() : top_level_model_(nullptr), menu_(nullptr), top_level_index_(-1) {} + ExtensionContextMenuVisibilityApiTest( + const ExtensionContextMenuVisibilityApiTest&) = delete; + ExtensionContextMenuVisibilityApiTest& operator=( + const ExtensionContextMenuVisibilityApiTest&) = delete; + void SetUpTestExtension() { extension_ = LoadExtension( test_data_dir_.AppendASCII("context_menus/item_visibility/")); @@ -219,8 +221,6 @@ class ExtensionContextMenuVisibilityApiTest const Extension* extension_; std::unique_ptr<TestRenderViewContextMenu> menu_; int top_level_index_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionContextMenuVisibilityApiTest); }; // Tests showing a single visible menu item in the top-level menu model, which diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc index 42ced3edb2a..7cb0d794259 100644 --- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc +++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.cc @@ -33,7 +33,7 @@ ExtensionFunction::ResponseAction ContextMenusCreateFunction::Run() { MenuItem::Id id(browser_context()->IsOffTheRecord(), MenuItem::ExtensionKey(extension_id())); std::unique_ptr<api::context_menus::Create::Params> params( - api::context_menus::Create::Params::Create(*args_)); + api::context_menus::Create::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (params->create_properties.id.get()) { @@ -43,10 +43,14 @@ ExtensionFunction::ResponseAction ContextMenusCreateFunction::Run() { return RespondNow(Error(kIdRequiredError)); // The Generated Id is added by context_menus_custom_bindings.js. - base::DictionaryValue* properties = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &properties)); - EXTENSION_FUNCTION_VALIDATE(properties->GetInteger( - extensions::context_menus_api_helpers::kGeneratedIdKey, &id.uid)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 1); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_dict()); + + const base::Value& properties = args()[0]; + absl::optional<int> result = properties.FindIntKey( + extensions::context_menus_api_helpers::kGeneratedIdKey); + EXTENSION_FUNCTION_VALIDATE(result); + id.uid = *result; } std::string error; @@ -62,7 +66,7 @@ ExtensionFunction::ResponseAction ContextMenusUpdateFunction::Run() { MenuItem::Id item_id(browser_context()->IsOffTheRecord(), MenuItem::ExtensionKey(extension_id())); std::unique_ptr<api::context_menus::Update::Params> params( - api::context_menus::Update::Params::Create(*args_)); + api::context_menus::Update::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (params->id.as_string) @@ -83,7 +87,7 @@ ExtensionFunction::ResponseAction ContextMenusUpdateFunction::Run() { ExtensionFunction::ResponseAction ContextMenusRemoveFunction::Run() { std::unique_ptr<api::context_menus::Remove::Params> params( - api::context_menus::Remove::Params::Create(*args_)); + api::context_menus::Remove::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); MenuManager* manager = MenuManager::Get(browser_context()); diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h index b2e1ddfcf50..982d6df922d 100644 --- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h +++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api_helpers.h @@ -256,7 +256,6 @@ bool UpdateMenuItem(const PropertyWithEnumT& update_properties, } // Parent id. - MenuItem* parent = NULL; std::unique_ptr<MenuItem::Id> parent_id( GetParentId(update_properties, browser_context->IsOffTheRecord(), item_id.extension_key)); @@ -275,7 +274,7 @@ bool UpdateMenuItem(const PropertyWithEnumT& update_properties, // There is no need to call ItemUpdated if ChangeParent is called because // all sanitation is taken care of in ChangeParent. - if (!parent && radio_item_updated && !menu_manager->ItemUpdated(item->id())) + if (radio_item_updated && !menu_manager->ItemUpdated(item->id())) return false; menu_manager->WriteToStorage(extension, item_id.extension_key); diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc index 3681911292a..54de40c46de 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc @@ -86,6 +86,11 @@ network::mojom::CookieManager* ParseStoreCookieManager( ->GetCookieManagerForBrowserProcess(); } +template <typename T> +T OrDefault(const std::unique_ptr<T>& ptr, T fallback) { + return ptr.get() ? *ptr : fallback; +} + } // namespace CookiesEventRouter::CookieChangeListener::CookieChangeListener( @@ -229,7 +234,7 @@ CookiesGetFunction::CookiesGetFunction() = default; CookiesGetFunction::~CookiesGetFunction() = default; ExtensionFunction::ResponseAction CookiesGetFunction::Run() { - parsed_args_ = api::cookies::Get::Params::Create(*args_); + parsed_args_ = api::cookies::Get::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parsed_args_.get()); // Read/validate input parameters. @@ -238,8 +243,7 @@ ExtensionFunction::ResponseAction CookiesGetFunction::Run() { return RespondNow(Error(std::move(error))); std::string store_id = - parsed_args_->details.store_id.get() ? *parsed_args_->details.store_id - : std::string(); + OrDefault(parsed_args_->details.store_id, std::string()); network::mojom::CookieManager* cookie_manager = ParseStoreCookieManager( browser_context(), include_incognito_information(), &store_id, &error); if (!cookie_manager) @@ -285,7 +289,7 @@ CookiesGetAllFunction::~CookiesGetAllFunction() { } ExtensionFunction::ResponseAction CookiesGetAllFunction::Run() { - parsed_args_ = api::cookies::GetAll::Params::Create(*args_); + parsed_args_ = api::cookies::GetAll::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parsed_args_.get()); std::string error; @@ -296,8 +300,7 @@ ExtensionFunction::ResponseAction CookiesGetAllFunction::Run() { } std::string store_id = - parsed_args_->details.store_id.get() ? *parsed_args_->details.store_id - : std::string(); + OrDefault(parsed_args_->details.store_id, std::string()); network::mojom::CookieManager* cookie_manager = ParseStoreCookieManager( browser_context(), include_incognito_information(), &store_id, &error); if (!cookie_manager) @@ -364,7 +367,7 @@ CookiesSetFunction::~CookiesSetFunction() { } ExtensionFunction::ResponseAction CookiesSetFunction::Run() { - parsed_args_ = api::cookies::Set::Params::Create(*args_); + parsed_args_ = api::cookies::Set::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parsed_args_.get()); // Read/validate input parameters. @@ -373,8 +376,7 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() { return RespondNow(Error(std::move(error))); std::string store_id = - parsed_args_->details.store_id.get() ? *parsed_args_->details.store_id - : std::string(); + OrDefault(parsed_args_->details.store_id, std::string()); network::mojom::CookieManager* cookie_manager = ParseStoreCookieManager( browser_context(), include_incognito_information(), &store_id, &error); if (!cookie_manager) @@ -413,30 +415,22 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() { } // TODO(crbug.com/1144181): Add support for SameParty attribute. - // clang-format off std::unique_ptr<net::CanonicalCookie> cc( net::CanonicalCookie::CreateSanitizedCookie( - url_, parsed_args_->details.name.get() ? *parsed_args_->details.name - : std::string(), - parsed_args_->details.value.get() ? *parsed_args_->details.value - : std::string(), - parsed_args_->details.domain.get() ? *parsed_args_->details.domain - : std::string(), - parsed_args_->details.path.get() ? *parsed_args_->details.path - : std::string(), - base::Time(), - expiration_time, - base::Time(), - parsed_args_->details.secure.get() ? *parsed_args_->details.secure - : false, - parsed_args_->details.http_only.get() ? - *parsed_args_->details.http_only : - false, - same_site, - net::COOKIE_PRIORITY_DEFAULT, - /*same_party=*/false, + url_, // + OrDefault(parsed_args_->details.name, std::string()), // + OrDefault(parsed_args_->details.value, std::string()), // + OrDefault(parsed_args_->details.domain, std::string()), // + OrDefault(parsed_args_->details.path, std::string()), // + base::Time(), // + expiration_time, // + base::Time(), // + OrDefault(parsed_args_->details.secure, false), // + OrDefault(parsed_args_->details.http_only, false), // + same_site, // + net::COOKIE_PRIORITY_DEFAULT, // + /*same_party=*/false, // /*partition_key=*/absl::nullopt)); - // clang-format on if (!cc) { // Return error through callbacks so that the proper error message // is generated. @@ -482,9 +476,7 @@ void CookiesSetFunction::GetCookieListCallback( state_ = GET_COMPLETED; if (!success_) { - std::string name = parsed_args_->details.name.get() - ? *parsed_args_->details.name - : std::string(); + std::string name = OrDefault(parsed_args_->details.name, std::string()); Respond(Error(ErrorUtils::FormatErrorMessage( cookies_api_constants::kCookieSetFailedError, name))); return; @@ -496,9 +488,7 @@ void CookiesSetFunction::GetCookieListCallback( // Return the first matching cookie. Relies on the fact that the // CookieMonster returns them in canonical order (longest path, then // earliest creation time). - std::string name = - parsed_args_->details.name.get() ? *parsed_args_->details.name - : std::string(); + std::string name = OrDefault(parsed_args_->details.name, std::string()); if (cookie_with_access_result.cookie.Name() == name) { api::cookies::Cookie api_cookie = cookies_helpers::CreateCookie( cookie_with_access_result.cookie, *parsed_args_->details.store_id); @@ -517,7 +507,7 @@ CookiesRemoveFunction::~CookiesRemoveFunction() { } ExtensionFunction::ResponseAction CookiesRemoveFunction::Run() { - parsed_args_ = api::cookies::Remove::Params::Create(*args_); + parsed_args_ = api::cookies::Remove::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parsed_args_.get()); // Read/validate input parameters. @@ -526,8 +516,7 @@ ExtensionFunction::ResponseAction CookiesRemoveFunction::Run() { return RespondNow(Error(std::move(error))); std::string store_id = - parsed_args_->details.store_id.get() ? *parsed_args_->details.store_id - : std::string(); + OrDefault(parsed_args_->details.store_id, std::string()); network::mojom::CookieManager* cookie_manager = ParseStoreCookieManager( browser_context(), include_incognito_information(), &store_id, &error); if (!cookie_manager) @@ -588,11 +577,11 @@ ExtensionFunction::ResponseAction CookiesGetAllCookieStoresFunction::Run() { } // Return a list of all cookie stores with at least one open tab. std::vector<api::cookies::CookieStore> cookie_stores; - if (original_tab_ids->GetSize() > 0) { + if (original_tab_ids->GetList().size() > 0) { cookie_stores.push_back(cookies_helpers::CreateCookieStore( original_profile, std::move(original_tab_ids))); } - if (incognito_tab_ids.get() && incognito_tab_ids->GetSize() > 0 && + if (incognito_tab_ids.get() && incognito_tab_ids->GetList().size() > 0 && incognito_profile) { cookie_stores.push_back(cookies_helpers::CreateCookieStore( incognito_profile, std::move(incognito_tab_ids))); diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h index e2debead521..b358e2c8413 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h @@ -36,6 +36,10 @@ namespace extensions { class CookiesEventRouter : public BrowserListObserver { public: explicit CookiesEventRouter(content::BrowserContext* context); + + CookiesEventRouter(const CookiesEventRouter&) = delete; + CookiesEventRouter& operator=(const CookiesEventRouter&) = delete; + ~CookiesEventRouter() override; // BrowserListObserver: @@ -50,6 +54,10 @@ class CookiesEventRouter : public BrowserListObserver { class CookieChangeListener : public network::mojom::CookieChangeListener { public: CookieChangeListener(CookiesEventRouter* router, bool otr); + + CookieChangeListener(const CookieChangeListener&) = delete; + CookieChangeListener& operator=(const CookieChangeListener&) = delete; + ~CookieChangeListener() override; // network::mojom::CookieChangeListener: @@ -58,8 +66,6 @@ class CookiesEventRouter : public BrowserListObserver { private: CookiesEventRouter* router_; bool otr_; - - DISALLOW_COPY_AND_ASSIGN(CookieChangeListener); }; void MaybeStartListening(); @@ -88,8 +94,6 @@ class CookiesEventRouter : public BrowserListObserver { CookieChangeListener otr_listener_{this, true}; mojo::Receiver<network::mojom::CookieChangeListener> otr_receiver_{ &otr_listener_}; - - DISALLOW_COPY_AND_ASSIGN(CookiesEventRouter); }; // Implements the cookies.get() extension function. @@ -202,6 +206,10 @@ class CookiesGetAllCookieStoresFunction : public ExtensionFunction { class CookiesAPI : public BrowserContextKeyedAPI, public EventRouter::Observer { public: explicit CookiesAPI(content::BrowserContext* context); + + CookiesAPI(const CookiesAPI&) = delete; + CookiesAPI& operator=(const CookiesAPI&) = delete; + ~CookiesAPI() override; // KeyedService implementation. @@ -226,8 +234,6 @@ class CookiesAPI : public BrowserContextKeyedAPI, public EventRouter::Observer { // Created lazily upon OnListenerAdded. std::unique_ptr<CookiesEventRouter> cookies_event_router_; - - DISALLOW_COPY_AND_ASSIGN(CookiesAPI); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc index bcd54de4807..4c3027cdac9 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_apitest.cc @@ -35,7 +35,7 @@ class CookiesApiTest : public ExtensionApiTest, public testing::WithParamInterface< std::tuple<ContextType, SameSiteCookieSemantics>> { public: - CookiesApiTest() = default; + CookiesApiTest() : ExtensionApiTest(std::get<0>(GetParam())) {} ~CookiesApiTest() override = default; CookiesApiTest(const CookiesApiTest&) = delete; CookiesApiTest& operator=(const CookiesApiTest&) = delete; @@ -66,11 +66,8 @@ class CookiesApiTest : public ExtensionApiTest, bool RunTest(const char* extension_name, bool allow_in_incognito = false, const char* custom_arg = nullptr) { - return RunExtensionTest( - extension_name, {.custom_arg = custom_arg}, - {.allow_in_incognito = allow_in_incognito, - .load_as_service_worker = - GetContextType() == ContextType::kServiceWorker}); + return RunExtensionTest(extension_name, {.custom_arg = custom_arg}, + {.allow_in_incognito = allow_in_incognito}); } ContextType GetContextType() { return std::get<0>(GetParam()); } diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc index 34c7ec7e1b8..ee30e706cfa 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc @@ -152,6 +152,7 @@ void GetCookieListFromManager( const GURL& url, network::mojom::CookieManager::GetCookieListCallback callback) { manager->GetCookieList(url, net::CookieOptions::MakeAllInclusive(), + net::CookiePartitionKeychain::Todo(), std::move(callback)); } @@ -201,8 +202,7 @@ void AppendToTabIdList(Browser* browser, base::ListValue* tab_ids) { DCHECK(tab_ids); TabStripModel* tab_strip = browser->tab_strip_model(); for (int i = 0; i < tab_strip->count(); ++i) { - tab_ids->AppendInteger( - ExtensionTabUtil::GetTabId(tab_strip->GetWebContentsAt(i))); + tab_ids->Append(ExtensionTabUtil::GetTabId(tab_strip->GetWebContentsAt(i))); } } diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc index 1c319733df3..ff2856a8e37 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc @@ -9,6 +9,7 @@ #include <memory> #include <utility> +#include <vector> #include "base/cxx17_backports.h" #include "base/values.h" @@ -173,10 +174,10 @@ TEST_F(ExtensionCookiesTest, DomainMatching) { for (size_t i = 0; i < base::size(tests); ++i) { // Build up the Params struct. - base::ListValue args; - auto dict = std::make_unique<base::DictionaryValue>(); - dict->SetString(keys::kDomainKey, std::string(tests[i].filter)); - args.Set(0, std::move(dict)); + std::vector<base::Value> args; + base::Value dict(base::Value::Type::DICTIONARY); + dict.SetStringKey(keys::kDomainKey, std::string(tests[i].filter)); + args.emplace_back(std::move(dict)); std::unique_ptr<GetAll::Params> params(GetAll::Params::Create(args)); cookies_helpers::MatchFilter filter(¶ms->details); diff --git a/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.cc b/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.cc index decc0a91a3b..db6864af8c2 100644 --- a/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.cc +++ b/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.cc @@ -26,7 +26,7 @@ WindowType GetWindowType(content::WebContents* web_contents) { return WindowType::kNoBrowser; if (!browser->app_controller()) return WindowType::kRegularTabbed; - if (browser->app_controller()->is_for_system_web_app()) + if (browser->app_controller()->system_app()) return WindowType::kSystemWebApp; return WindowType::kWebApp; } @@ -47,7 +47,7 @@ ExtensionFunction::ResponseAction CrashReportPrivateReportErrorFunction::Run() { return RespondNow(NoArguments()); } - const auto params = crash_report_private::ReportError::Params::Create(*args_); + const auto params = crash_report_private::ReportError::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); auto processor = JsErrorReportProcessor::Get(); diff --git a/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.h b/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.h index 4e52219c01f..6b237288dcb 100644 --- a/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.h +++ b/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_api.h @@ -15,6 +15,12 @@ namespace api { class CrashReportPrivateReportErrorFunction : public ExtensionFunction { public: CrashReportPrivateReportErrorFunction(); + + CrashReportPrivateReportErrorFunction( + const CrashReportPrivateReportErrorFunction&) = delete; + CrashReportPrivateReportErrorFunction& operator=( + const CrashReportPrivateReportErrorFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("crashReportPrivate.reportError", CRASHREPORTPRIVATE_REPORTERROR) @@ -24,8 +30,6 @@ class CrashReportPrivateReportErrorFunction : public ExtensionFunction { private: void OnReportComplete(); - - DISALLOW_COPY_AND_ASSIGN(CrashReportPrivateReportErrorFunction); }; } // namespace api diff --git a/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_apitest.cc b/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_apitest.cc index 8ffaeb0d929..39fb26344c7 100644 --- a/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/crash_report_private/crash_report_private_apitest.cc @@ -40,6 +40,11 @@ constexpr const char* kTestExtensionId = "jjeoclcdfjddkdjokiejckgcildcflpp"; class CrashReportPrivateApiTest : public ExtensionApiTest { public: CrashReportPrivateApiTest() = default; + + CrashReportPrivateApiTest(const CrashReportPrivateApiTest&) = delete; + CrashReportPrivateApiTest& operator=(const CrashReportPrivateApiTest&) = + delete; + ~CrashReportPrivateApiTest() override = default; void SetUpOnMainThread() override { @@ -88,9 +93,6 @@ class CrashReportPrivateApiTest : public ExtensionApiTest { const Extension* extension_; std::unique_ptr<MockCrashEndpoint> crash_endpoint_; std::unique_ptr<ScopedMockChromeJsErrorReportProcessor> processor_; - - private: - DISALLOW_COPY_AND_ASSIGN(CrashReportPrivateApiTest); }; IN_PROC_BROWSER_TEST_F(CrashReportPrivateApiTest, Basic) { diff --git a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc index 4190dc3f2cf..02bdea187ad 100644 --- a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc +++ b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc @@ -11,6 +11,7 @@ #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/permissions/attestation_permission_request.h" #include "chrome/browser/profiles/profile.h" @@ -23,10 +24,15 @@ #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "crypto/sha2.h" +#include "device/fido/features.h" #include "device/fido/filter.h" #include "extensions/browser/extension_api_frame_id_map.h" +#include "extensions/browser/pref_names.h" #include "extensions/common/error_utils.h" +#include "extensions/common/extension_features.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" +#include "third_party/blink/public/common/origin_trials/trial_token_validator.h" +#include "third_party/blink/public/mojom/devtools/console_message.mojom-shared.h" #include "url/origin.h" #if defined(OS_WIN) @@ -34,6 +40,10 @@ #include "device/fido/win/webauthn_api.h" #endif // defined(OS_WIN) +#if BUILDFLAG(IS_CHROMEOS_ASH) +#include "chrome/browser/ash/profiles/profile_helper.h" +#endif + namespace extensions { namespace api { @@ -97,7 +107,7 @@ CryptotokenPrivateCanOriginAssertAppIdFunction:: ExtensionFunction::ResponseAction CryptotokenPrivateCanOriginAssertAppIdFunction::Run() { std::unique_ptr<cryptotoken_private::CanOriginAssertAppId::Params> params = - cryptotoken_private::CanOriginAssertAppId::Params::Create(*args_); + cryptotoken_private::CanOriginAssertAppId::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params); const GURL origin_url(params->security_origin); @@ -155,7 +165,7 @@ CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction::Run() { std::unique_ptr<cryptotoken_private::IsAppIdHashInEnterpriseContext::Params> params( cryptotoken_private::IsAppIdHashInEnterpriseContext::Params::Create( - *args_)); + args())); EXTENSION_FUNCTION_VALIDATE(params); Profile* const profile = Profile::FromBrowserContext(browser_context()); @@ -174,7 +184,7 @@ CryptotokenPrivateCanAppIdGetAttestationFunction:: ExtensionFunction::ResponseAction CryptotokenPrivateCanAppIdGetAttestationFunction::Run() { std::unique_ptr<cryptotoken_private::CanAppIdGetAttestation::Params> params = - cryptotoken_private::CanAppIdGetAttestation::Params::Create(*args_); + cryptotoken_private::CanAppIdGetAttestation::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params); const GURL origin_url(params->options.origin); @@ -264,10 +274,104 @@ void CryptotokenPrivateCanAppIdGetAttestationFunction::Complete(bool result) { Respond(OneArgument(base::Value(result))); } +CryptotokenPrivateCanMakeU2fApiRequestFunction:: + CryptotokenPrivateCanMakeU2fApiRequestFunction() = default; + +ExtensionFunction::ResponseAction +CryptotokenPrivateCanMakeU2fApiRequestFunction::Run() { + auto params = + cryptotoken_private::CanMakeU2fApiRequest::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params); + +#if BUILDFLAG(IS_CHROMEOS_ASH) + // The `chrome.tabs` API doesn't work in Chrome OS sign-in contexts (e.g. + // device login with some SAML provider making a U2F request). This means that + // in these contexts we can't figure out the sender frame of the original U2F + // API request and therefore can't show a permission prompt or check for + // origin trial enrollment. Hence, just let these requests succeed without + // further checks. + if (!ash::ProfileHelper::IsRegularProfile( + Profile::FromBrowserContext(browser_context()))) { + DCHECK_EQ(params->options.tab_id, api::tabs::TAB_ID_NONE); + return RespondNow(OneArgument(base::Value(true))); + } +#endif + + content::WebContents* web_contents = nullptr; + if (!ExtensionTabUtil::GetTabById(params->options.tab_id, browser_context(), + true /* include incognito windows */, + &web_contents)) { + return RespondNow(Error("cannot find specified tab")); + } + + content::RenderFrameHost* frame = RenderFrameHostForTabAndFrameId( + browser_context(), params->options.tab_id, params->options.frame_id); + if (!frame) { + return RespondNow(Error("cannot find frame")); + } + frame->AddMessageToConsole( + blink::mojom::ConsoleMessageLevel::kWarning, + R"(The U2F Security Key API is deprecated and will be removed soon. If you own this website, please migrate to the Web Authentication API. For more information see https://groups.google.com/a/chromium.org/g/blink-dev/c/xHC3AtU_65A/m/yg20tsVFBAAJ)"); + + blink::TrialTokenValidator validator; + const net::HttpResponseHeaders* response_headers = + frame->GetLastResponseHeaders(); + const bool u2f_api_origin_trial_enabled = + (response_headers && validator.RequestEnablesFeature( + frame->GetLastCommittedURL(), response_headers, + extension_misc::kCryptotokenDeprecationTrialName, + base::Time::Now())); + const bool u2f_api_enterprise_policy_enabled = + Profile::FromBrowserContext(browser_context()) + ->GetPrefs() + ->GetBoolean(extensions::pref_names::kU2fSecurityKeyApiEnabled); + + DCHECK( + base::FeatureList::IsEnabled(extensions_features::kU2FSecurityKeyAPI) || + u2f_api_enterprise_policy_enabled || u2f_api_origin_trial_enabled); + + // Don't show a permission prompt if its feature flag is disabled, or if the + // site enrolled in the deprecation trial (since they're obviously aware of + // the deprecation), or if the enterprise policy to override U2F + // deprecation-related changes has been enabled. + // + // Also don't show the prompt in "non-regular" ChromeOS profiles, which + // includes CrOS SAML sign-in context that doesn't support permission prompts + // (crbug.com/1257293). + if (!base::FeatureList::IsEnabled(device::kU2fPermissionPrompt) || + u2f_api_enterprise_policy_enabled || u2f_api_origin_trial_enabled) { + return RespondNow(OneArgument(base::Value(true))); + } + + permissions::PermissionRequestManager* permission_request_manager = + permissions::PermissionRequestManager::FromWebContents(web_contents); + if (!permission_request_manager) { + return RespondNow(Error("no PermissionRequestManager")); + } + + const GURL origin_url(params->options.origin); + if (!origin_url.is_valid()) { + return RespondNow(Error(extensions::ErrorUtils::FormatErrorMessage( + "invalid origin", params->options.origin))); + } + + permission_request_manager->AddRequest( + frame, NewU2fApiPermissionRequest( + url::Origin::Create(origin_url), + base::BindOnce( + &CryptotokenPrivateCanMakeU2fApiRequestFunction::Complete, + this))); + return RespondLater(); +} + +void CryptotokenPrivateCanMakeU2fApiRequestFunction::Complete(bool result) { + Respond(OneArgument(base::Value(result))); +} + ExtensionFunction::ResponseAction CryptotokenPrivateRecordRegisterRequestFunction::Run() { auto params = - cryptotoken_private::RecordRegisterRequest::Params::Create(*args_); + cryptotoken_private::RecordRegisterRequest::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params); content::RenderFrameHost* frame = RenderFrameHostForTabAndFrameId( @@ -283,7 +387,7 @@ CryptotokenPrivateRecordRegisterRequestFunction::Run() { ExtensionFunction::ResponseAction CryptotokenPrivateRecordSignRequestFunction::Run() { - auto params = cryptotoken_private::RecordSignRequest::Params::Create(*args_); + auto params = cryptotoken_private::RecordSignRequest::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params); content::RenderFrameHost* frame = RenderFrameHostForTabAndFrameId( diff --git a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h index eae0cfabe46..6cebc13bb2f 100644 --- a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h +++ b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h @@ -28,7 +28,7 @@ class CryptotokenPrivateCanOriginAssertAppIdFunction DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canOriginAssertAppId", CRYPTOTOKENPRIVATE_CANORIGINASSERTAPPID) protected: - ~CryptotokenPrivateCanOriginAssertAppIdFunction() override {} + ~CryptotokenPrivateCanOriginAssertAppIdFunction() override = default; ResponseAction Run() override; }; @@ -41,7 +41,8 @@ class CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction CRYPTOTOKENPRIVATE_ISAPPIDHASHINENTERPRISECONTEXT) protected: - ~CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction() override {} + ~CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction() override = + default; ResponseAction Run() override; }; @@ -53,7 +54,20 @@ class CryptotokenPrivateCanAppIdGetAttestationFunction CRYPTOTOKENPRIVATE_CANAPPIDGETATTESTATION) protected: - ~CryptotokenPrivateCanAppIdGetAttestationFunction() override {} + ~CryptotokenPrivateCanAppIdGetAttestationFunction() override = default; + ResponseAction Run() override; + void Complete(bool result); +}; + +class CryptotokenPrivateCanMakeU2fApiRequestFunction + : public ExtensionFunction { + public: + CryptotokenPrivateCanMakeU2fApiRequestFunction(); + DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canMakeU2fApiRequest", + CRYPTOTOKENPRIVATE_CANMAKEU2FAPIREQUEST) + + protected: + ~CryptotokenPrivateCanMakeU2fApiRequestFunction() override = default; ResponseAction Run() override; void Complete(bool result); }; diff --git a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc index f5da7d52b89..f500beea391 100644 --- a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_api_unittest.cc @@ -21,8 +21,11 @@ #include "components/permissions/test/mock_permission_prompt_factory.h" #include "components/sessions/content/session_tab_helper.h" #include "crypto/sha2.h" +#include "device/fido/features.h" #include "extensions/browser/api_test_utils.h" #include "extensions/browser/extension_function_dispatcher.h" +#include "extensions/browser/pref_names.h" +#include "extensions/common/extension_features.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) @@ -40,7 +43,7 @@ bool GetSingleBooleanResult(ExtensionFunction* function, bool* result) { return false; } - if (result_list->GetSize() != 1u) { + if (result_list->GetList().size() != 1u) { ADD_FAILURE() << "Invalid number of results."; return false; } @@ -67,8 +70,8 @@ class CryptoTokenPrivateApiTest : public extensions::ExtensionApiUnittest { function->set_has_callback(true); auto args = std::make_unique<base::ListValue>(); - args->AppendString(origin); - args->AppendString(app_id); + args->Append(origin); + args->Append(app_id); if (!extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), api_test_utils::NONE)) { @@ -176,12 +179,12 @@ TEST_F(CryptoTokenPrivateApiTest, RecordRegisterRequest) { auto function = base::MakeRefCounted< api::CryptotokenPrivateRecordRegisterRequestFunction>(); auto args = std::make_unique<base::ListValue>(); - args->AppendInteger(tab_id); - args->AppendInteger(0 /* top-level frame */); + args->Append(tab_id); + args->Append(0 /* top-level frame */); ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), base::ListValue::From(std::move(args)), browser(), api_test_utils::NONE)); - ASSERT_EQ(function->GetResultList()->GetSize(), 0u); + ASSERT_EQ(function->GetResultList()->GetList().size(), 0u); web_feature_waiter.Wait(); } @@ -202,12 +205,12 @@ TEST_F(CryptoTokenPrivateApiTest, RecordSignRequest) { auto function = base::MakeRefCounted<api::CryptotokenPrivateRecordSignRequestFunction>(); auto args = std::make_unique<base::ListValue>(); - args->AppendInteger(tab_id); - args->AppendInteger(0 /* top-level frame */); + args->Append(tab_id); + args->Append(0 /* top-level frame */); ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), base::ListValue::From(std::move(args)), browser(), api_test_utils::NONE)); - ASSERT_EQ(function->GetResultList()->GetSize(), 0u); + ASSERT_EQ(function->GetResultList()->GetList().size(), 0u); web_feature_waiter.Wait(); } @@ -216,12 +219,14 @@ TEST_F(CryptoTokenPrivateApiTest, RecordSignRequest) { class CryptoTokenPermissionTest : public ExtensionApiUnittest { public: CryptoTokenPermissionTest() = default; + + CryptoTokenPermissionTest(const CryptoTokenPermissionTest&) = delete; + CryptoTokenPermissionTest& operator=(const CryptoTokenPermissionTest&) = + delete; + ~CryptoTokenPermissionTest() override = default; void SetUp() override { - feature_list_.InitWithFeatures({features::kSecurityKeyAttestationPrompt}, - {}); - ExtensionApiUnittest::SetUp(); const GURL url("http://example.com"); AddTab(browser(), url); @@ -265,6 +270,7 @@ class CryptoTokenPermissionTest : public ExtensionApiUnittest { base::Value::DictStorage dict; dict.emplace("appId", app_id); dict.emplace("tabId", tab_id_); + dict.emplace("frameId", -1); // Ignored. dict.emplace("origin", app_id); auto args = std::make_unique<base::Value>(base::Value::Type::LIST); args->Append(base::Value(std::move(dict))); @@ -276,15 +282,49 @@ class CryptoTokenPermissionTest : public ExtensionApiUnittest { return GetSingleBooleanResult(function.get(), out_result); } - private: + // CanMakeU2fApiRequest calls the cryptotoken private API of the same name + // for |origin| and sets |*out_result| to the result. If |bubble_action| is + // not |NONE| then it waits for the permissions prompt to be shown and + // performs the given action. Otherwise, the call is expected to be + // synchronous. + bool CanMakeU2fApiRequest( + const std::string& origin, + permissions::PermissionRequestManager::AutoResponseType bubble_action, + bool* out_result) { + if (bubble_action != permissions::PermissionRequestManager::NONE) { + prompt_factory_->set_response_type(bubble_action); + auto* web_contents = browser()->tab_strip_model()->GetWebContentsAt(0); + prompt_factory_->DocumentOnLoadCompletedInMainFrame( + web_contents->GetMainFrame()); + } + + auto function = base::MakeRefCounted< + api::CryptotokenPrivateCanMakeU2fApiRequestFunction>(); + function->set_has_callback(true); + + base::Value::DictStorage dict; + dict.emplace("appId", origin); + dict.emplace("tabId", tab_id_); + dict.emplace("frameId", 0 /* main frame */); + dict.emplace("origin", origin); + auto args = std::make_unique<base::Value>(base::Value::Type::LIST); + args->Append(base::Value(std::move(dict))); + auto args_list = base::ListValue::From(std::move(args)); + + extension_function_test_utils::RunFunction( + function.get(), std::move(args_list), browser(), api_test_utils::NONE); + + return GetSingleBooleanResult(function.get(), out_result); + } + base::test::ScopedFeatureList feature_list_; + + private: int tab_id_ = -1; std::unique_ptr<permissions::MockPermissionPromptFactory> prompt_factory_; - - DISALLOW_COPY_AND_ASSIGN(CryptoTokenPermissionTest); }; -TEST_F(CryptoTokenPermissionTest, Prompt) { +TEST_F(CryptoTokenPermissionTest, AttestationPrompt) { #if defined(OS_WIN) // TODO(crbug.com/1225335) This test is failing on WIN10_20H2. if (base::win::OSInfo::GetInstance()->version() >= @@ -311,7 +351,7 @@ TEST_F(CryptoTokenPermissionTest, Prompt) { } } -TEST_F(CryptoTokenPermissionTest, PolicyOverridesPrompt) { +TEST_F(CryptoTokenPermissionTest, PolicyOverridesAttestationPrompt) { const std::string example_com("https://example.com"); base::Value::ListStorage permitted_list; permitted_list.emplace_back(example_com); @@ -326,4 +366,53 @@ TEST_F(CryptoTokenPermissionTest, PolicyOverridesPrompt) { EXPECT_TRUE(result); } +TEST_F(CryptoTokenPermissionTest, RequestPrompt) { + const std::vector<permissions::PermissionRequestManager::AutoResponseType> + actions = { + permissions::PermissionRequestManager::ACCEPT_ALL, + permissions::PermissionRequestManager::DENY_ALL, + permissions::PermissionRequestManager::DISMISS, + }; + + for (const auto& action : actions) { + SCOPED_TRACE(action); + + bool result = false; + ASSERT_TRUE(CanMakeU2fApiRequest("https://test.com", action, &result)); + // The result should only be positive if the user accepted the permissions + // prompt. + EXPECT_EQ(action == permissions::PermissionRequestManager::ACCEPT_ALL, + result); + } +} + +TEST_F(CryptoTokenPermissionTest, FeatureFlagOverridesRequestPrompt) { + // Disabling the permission prompt feature flag should suppress it. + feature_list_.InitAndDisableFeature(device::kU2fPermissionPrompt); + bool result = false; + ASSERT_TRUE(CanMakeU2fApiRequest("https://test.com", + permissions::PermissionRequestManager::NONE, + &result)); + EXPECT_TRUE(result); +} + +TEST_F(CryptoTokenPermissionTest, EnterprisePolicyOverridesRequestPrompt) { + // Setting the deprecation override policy should cause the prompt to be + // suppressed. This should be true even when the API has been + // default-disabled, because the policy overrides that too. + for (bool api_enabled : {false, true}) { + SCOPED_TRACE(api_enabled); + feature_list_.InitWithFeatureState(extensions_features::kU2FSecurityKeyAPI, + api_enabled); + browser()->profile()->GetPrefs()->Set( + extensions::pref_names::kU2fSecurityKeyApiEnabled, base::Value(true)); + bool result = false; + ASSERT_TRUE(CanMakeU2fApiRequest( + "https://test.com", permissions::PermissionRequestManager::NONE, + &result)); + EXPECT_TRUE(result); + feature_list_.Reset(); + } +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_browsertest.cc b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_browsertest.cc new file mode 100644 index 00000000000..eaa2bb59636 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/cryptotoken_private/cryptotoken_private_browsertest.cc @@ -0,0 +1,405 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/base_switches.h" +#include "base/strings/strcat.h" +#include "base/strings/string_util.h" +#include "base/test/scoped_feature_list.h" +#include "base/test/with_feature_override.h" +#include "build/build_config.h" +#include "chrome/browser/extensions/component_loader.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/test/base/in_process_browser_test.h" +#include "chrome/test/base/ui_test_utils.h" +#include "components/embedder_support/switches.h" +#include "components/permissions/permission_request_manager.h" +#include "components/permissions/test/permission_request_observer.h" +#include "components/prefs/pref_service.h" +#include "content/public/browser/render_frame_host.h" +#include "content/public/browser/web_contents.h" +#include "content/public/test/browser_test.h" +#include "content/public/test/browser_test_utils.h" +#include "content/public/test/url_loader_interceptor.h" +#include "device/fido/features.h" +#include "extensions/browser/pref_names.h" +#include "extensions/common/extension_features.h" +#include "net/dns/mock_host_resolver.h" +#include "net/test/embedded_test_server/default_handlers.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "net/test/embedded_test_server/http_request.h" +#include "net/test/embedded_test_server/http_response.h" +#include "testing/gmock/include/gmock/gmock-matchers.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace extensions { + +namespace { + +constexpr char kCryptoTokenExtensionId[] = "kmendfapggjehodndflmmgagdbamhnfd"; + +// Origin for running tests with an Origin Trial token. Hostname needs to be +// from `net::EmbeddedTestServer::CERT_TEST_NAMES`. +constexpr char kOriginTrialOrigin[] = "https://a.test"; + +// Domain to serve files from. This should be different from `kOriginTrialToken` +// domain. Needs to be from `net::EmbeddedTestServer::CERT_TEST_NAMES`. +constexpr char kNonOriginTrialDomain[] = "b.test"; + +class CryptotokenBrowserTest : public base::test::WithFeatureOverride, + public InProcessBrowserTest { + protected: + CryptotokenBrowserTest() + : base::test::WithFeatureOverride( + extensions_features::kU2FSecurityKeyAPI) { +#if defined(OS_WIN) + // Don't dispatch requests to the native Windows API. + scoped_feature_list_.InitAndDisableFeature(device::kWebAuthUseNativeWinApi); +#endif + } + + void SetUpCommandLine(base::CommandLine* command_line) override { + // The public key for the default privatey key used by the + // tools/origin_trials/generate_token.py tool. + static constexpr char kOriginTrialTestPublicKey[] = + "dRCs+TocuKkocNKa0AtZ4awrt9XKH2SQCI6o4FY6BNA="; + command_line->AppendSwitchASCII(embedder_support::kOriginTrialPublicKey, + kOriginTrialTestPublicKey); + } + + void SetUp() override { + // Make sure the Hangout Services component extension gets loaded. + ComponentLoader::EnableBackgroundExtensionsForTesting(); + InProcessBrowserTest::SetUp(); + } + + void SetUpOnMainThread() override { + InProcessBrowserTest::SetUpOnMainThread(); + + url_loader_interceptor_ = + std::make_unique<content::URLLoaderInterceptor>(base::BindRepeating( + &CryptotokenBrowserTest::InterceptRequest, base::Unretained(this))); + + host_resolver()->AddRule("*", "127.0.0.1"); + + https_server_.SetSSLConfig(net::EmbeddedTestServer::CERT_TEST_NAMES); + https_server_.AddDefaultHandlers(GetChromeTestDataDir()); + ASSERT_TRUE(https_server_.Start()); + + http_server_.AddDefaultHandlers(GetChromeTestDataDir()); + ASSERT_TRUE(http_server_.Start()); + } + + void TearDownOnMainThread() override { url_loader_interceptor_.reset(); } + + // Returns the frame to use when attempting to connect to Cryptotoken in the + // methods below. Uses the main frame by default or + // |frame_to_use_for_connecting_| if a test overrides it. + content::RenderFrameHost* FrameToUseForConnecting() { + return frame_to_use_for_connecting_ ? frame_to_use_for_connecting_ + : browser() + ->tab_strip_model() + ->GetActiveWebContents() + ->GetMainFrame(); + } + + void ExpectChromeRuntimeIsUndefined() { + const std::string script = base::StringPrintf( + R"(let port = chrome.runtime.connect('%s', + {});)", + kCryptoTokenExtensionId); + const content::EvalJsResult result = + content::EvalJs(FrameToUseForConnecting(), script); + EXPECT_THAT( + result.error, + testing::StartsWith("a JavaScript error:\nTypeError: Cannot read " + "properties of undefined (reading 'connect')")); + } + + void ExpectConnectSuccess() { + const std::string script = base::StringPrintf( + R"(new Promise((resolve) => { + chrome.runtime.sendMessage('%s', + {}, () => { + resolve(chrome.runtime.lastError === undefined); + }); + }))", + kCryptoTokenExtensionId); + const content::EvalJsResult result = + content::EvalJs(FrameToUseForConnecting(), script); + EXPECT_EQ(true, result); + } + + void ExpectConnectFailure() { + const std::string script = base::StringPrintf( + R"(new Promise((resolve) => { + chrome.runtime.sendMessage('%s', + {}, () => { + if (!chrome.runtime.lastError) { + resolve('chrome.runtime.lastError is undefined'); + } else { + resolve(chrome.runtime.lastError.message); + } + }); + }))", + kCryptoTokenExtensionId); + const content::EvalJsResult result = + content::EvalJs(FrameToUseForConnecting(), script); + EXPECT_EQ("Could not establish connection. Receiving end does not exist.", + result); + } + + // Indicates whether `ExpectSignSuccess()` should expect a U2F deprecation + // prompt to be shown. + enum class PromptExpectation { + kNoPrompt, + kShowPrompt, + }; + + void ExpectSignSuccess(const std::string& app_id, + PromptExpectation prompt_expectation) { + content::WebContents* web_contents = + content::WebContents::FromRenderFrameHost(FrameToUseForConnecting()); + if (prompt_expectation == PromptExpectation::kShowPrompt) { + // Automatically resolve permission prompts shown by Cryptotoken on the + // target frame. + permissions::PermissionRequestManager* request_manager = + permissions::PermissionRequestManager::FromWebContents(web_contents); + request_manager->set_auto_response_for_test( + permissions::PermissionRequestManager::DENY_ALL); + } + + permissions::PermissionRequestObserver permission_request_observer( + web_contents); + const std::string script = base::StringPrintf( + R"(new Promise((resolve,reject) => { + chrome.runtime.sendMessage('%s', + { + type: 'u2f_sign_request', + appId: '%s', + challenge: 'aGVsbG8gd29ybGQ', + registeredKeys: [ + { + version: 'U2F_V2', + keyHandle: 'aGVsbG8gd29ybGQ', + transports: ['usb'], + appId: '%s', + } + ], + timeoutSeconds: 3, + requestId: 1 + }, + (args) => { + if (chrome.runtime.lastError !== undefined) { + resolve('runtime error: ' + chrome.runtime.lastError); + return; + } + if ('responseData' in args && + 'errorCode' in args.responseData) { + resolve('errorCode:' + + args.responseData.errorCode + + ",errorMessage:" + + args.responseData.errorMessage); + return; + } + reject(); // Requests can never succeed. + }); + }))", + kCryptoTokenExtensionId, app_id.c_str(), app_id.c_str()); + const content::EvalJsResult result = + content::EvalJs(FrameToUseForConnecting(), script); + if (prompt_expectation == PromptExpectation::kShowPrompt) { + // Denied prompt results in a DEVICE_INELIGIBLE error. + EXPECT_EQ("errorCode:4,errorMessage:The operation was not allowed", + result); + EXPECT_EQ(true, permission_request_observer.request_shown()); + } else { + // Without a prompt, the request times out eventually. N.B. the + // `timeoutSeconds` parameter above needs to be high enough to allow time + // for the prompt to show in the kShowPrompt case, but not too high to + // cause test stalls and timeouts + EXPECT_EQ("errorCode:5,errorMessage:undefined", result); + EXPECT_EQ(false, permission_request_observer.request_shown()); + } + } + + net::EmbeddedTestServer http_server_{net::EmbeddedTestServer::TYPE_HTTP}; + net::EmbeddedTestServer https_server_{net::EmbeddedTestServer::TYPE_HTTPS}; + content::RenderFrameHost* frame_to_use_for_connecting_ = nullptr; + + private: + // content::URLLoaderInterceptor callback + bool InterceptRequest(content::URLLoaderInterceptor::RequestParams* params) { + // The response for origin trial requests are injected so that we have a + // stable port to use for generating the token. + if (params->url_request.url.GetOrigin() != GURL(kOriginTrialOrigin)) { + return false; + } + + // Generated with `tools/origin_trials/generate_token.py --expire-days 5000 + // https://a.test U2FSecurityKeyAPI` + constexpr char kOriginTrialToken[] = + "A5xaE9lySzMBejK4rKNqBC86X9m2VhMwB/" + "1FXWcHNhtPhdTK02TzChhjmD7p+" + "kMn2tTO424RwoUWlFCLsd1tRAQAAABWeyJvcmlnaW4iOiAiaHR0cHM6Ly9hLnRlc3Q6NDQ" + "zIiwgImZlYXR1cmUiOiAiVTJGU2VjdXJpdHlLZXlBUEkiLCAiZXhwaXJ5IjogMjA2MjcxM" + "DYzNH0="; + + const std::string headers = base::StringPrintf( + "HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\n" + "Origin-Trial: %s\n\n", + kOriginTrialToken); + content::URLLoaderInterceptor::WriteResponse( + headers, + "<html><head></head><body>OK\n" + "<iframe id=\"otIframe\"></iframe>" + "</body></html>", + params->client.get()); + return true; + } + +#if defined(OS_WIN) + base::test::ScopedFeatureList scoped_feature_list_; +#endif + std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_; +}; + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, Connect) { + // CryptoToken can only be connected to if the feature flag is enabled. + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), https_server_.GetURL(kNonOriginTrialDomain, "/empty.html"))); + if (IsParamFeatureEnabled()) { + ExpectConnectSuccess(); + } else { + ExpectConnectFailure(); + } +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, SignShowsPrompt) { + if (!IsParamFeatureEnabled()) { + // Can't connect with the API disabled. + return; + } + GURL url = https_server_.GetURL(kNonOriginTrialDomain, "/empty.html"); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + std::string app_id = url::Origin::Create(url).Serialize(); + ExpectSignSuccess(app_id, PromptExpectation::kShowPrompt); +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, ConnectWithOriginTrial) { + // Connection succeeds regardless of feature flag state with the origin trial. + ASSERT_TRUE( + ui_test_utils::NavigateToURL(browser(), GURL(kOriginTrialOrigin))); + ExpectConnectSuccess(); +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, + SignWithOriginTrialDoesNotShowPrompt) { + GURL url = GURL(kOriginTrialOrigin); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + std::string app_id = url::Origin::Create(url).Serialize(); + ExpectSignSuccess(app_id, PromptExpectation::kNoPrompt); +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, + ConnectWithOriginTrialInCrossOriginIframe) { + // Cross-origin iframe can connect with a trial token even if the parent frame + // is not enrolled in the trial. + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), https_server_.GetURL(kNonOriginTrialDomain, "/iframe.html"))); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(content::NavigateIframeToURL(web_contents, "test", + GURL(kOriginTrialOrigin))); + frame_to_use_for_connecting_ = content::FrameMatchingPredicate( + web_contents->GetPrimaryPage(), + base::BindRepeating(&content::FrameIsChildOfMainFrame)); + ExpectConnectSuccess(); +} + +IN_PROC_BROWSER_TEST_P( + CryptotokenBrowserTest, + SignWithOriginTrialInCrossOriginIframeDoesNotShowPrompt) { + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), https_server_.GetURL(kNonOriginTrialDomain, "/iframe.html"))); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + GURL url = GURL(kOriginTrialOrigin); + ASSERT_TRUE(content::NavigateIframeToURL(web_contents, "test", url)); + frame_to_use_for_connecting_ = content::FrameMatchingPredicate( + web_contents->GetPrimaryPage(), + base::BindRepeating(&content::FrameIsChildOfMainFrame)); + + // Also make sure no permissions are showing on the main frame either. + permissions::PermissionRequestManager* request_manager = + permissions::PermissionRequestManager::FromWebContents(web_contents); + request_manager->set_auto_response_for_test( + permissions::PermissionRequestManager::DENY_ALL); + permissions::PermissionRequestObserver permission_request_observer( + web_contents); + + std::string app_id = url::Origin::Create(url).Serialize(); + ExpectSignSuccess(app_id, PromptExpectation::kNoPrompt); + EXPECT_FALSE(permission_request_observer.request_shown()); +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, + OriginTrailDoesNotAffectChildIframes) { + GURL parent_url = GURL(kOriginTrialOrigin); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), parent_url)); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + GURL child_url = https_server_.GetURL(kNonOriginTrialDomain, "/empty.html"); + ASSERT_TRUE( + content::NavigateIframeToURL(web_contents, "otIframe", child_url)); + frame_to_use_for_connecting_ = content::FrameMatchingPredicate( + web_contents->GetPrimaryPage(), + base::BindRepeating(&content::FrameIsChildOfMainFrame)); + + if (IsParamFeatureEnabled()) { + // With the feature flag enabled, the U2F API is active; but the OT that + // would suppress the prompt on the main frame, does not suppress the prompt + // on the child frame. + ExpectConnectSuccess(); + std::string app_id = url::Origin::Create(child_url).Serialize(); + ExpectSignSuccess(app_id, PromptExpectation::kShowPrompt); + } else { + // With the feature flag off, the U2F API is inactive on the child frame, + // even though it is enabled via OT on the parent frame. + ExpectConnectFailure(); + } +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, ConnectWithEnterprisePolicy) { + // Connection succeeds regardless of feature flag state with the enterprise + // policy overriding deprecation changes. + browser()->profile()->GetPrefs()->Set( + extensions::pref_names::kU2fSecurityKeyApiEnabled, base::Value(true)); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), https_server_.GetURL(kNonOriginTrialDomain, "/empty.html"))); + ExpectConnectSuccess(); +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, + SignWithEnterprisePolicyDoesNotShowPrompt) { + browser()->profile()->GetPrefs()->Set( + extensions::pref_names::kU2fSecurityKeyApiEnabled, base::Value(true)); + GURL url = GURL(https_server_.GetURL(kNonOriginTrialDomain, "/empty.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + std::string app_id = url::Origin::Create(url).Serialize(); + ExpectSignSuccess(app_id, PromptExpectation::kNoPrompt); +} + +IN_PROC_BROWSER_TEST_P(CryptotokenBrowserTest, InsecureOriginCannotConnect) { + // Connections from insecure origins always fail. + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), http_server_.GetURL(kNonOriginTrialDomain, "/empty.html"))); + ExpectChromeRuntimeIsUndefined(); +} + +INSTANTIATE_FEATURE_OVERRIDE_TEST_SUITE(CryptotokenBrowserTest); + +} // namespace +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc index 9c2c75bd230..dcb4ff0918a 100644 --- a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc +++ b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.cc @@ -57,7 +57,7 @@ DashboardPrivateShowPermissionPromptForDelegatedInstallFunction:: ExtensionFunction::ResponseAction DashboardPrivateShowPermissionPromptForDelegatedInstallFunction::Run() { - params_ = Params::Create(*args_); + params_ = Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_); if (!crx_file::id_util::IdIsValid(params_->details.id)) { diff --git a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h index a41579a179e..9afbd7effa0 100644 --- a/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h +++ b/chromium/chrome/browser/extensions/api/dashboard_private/dashboard_private_api.h @@ -32,6 +32,13 @@ class DashboardPrivateShowPermissionPromptForDelegatedInstallFunction DashboardPrivateShowPermissionPromptForDelegatedInstallFunction(); + DashboardPrivateShowPermissionPromptForDelegatedInstallFunction( + const DashboardPrivateShowPermissionPromptForDelegatedInstallFunction&) = + delete; + DashboardPrivateShowPermissionPromptForDelegatedInstallFunction& operator=( + const DashboardPrivateShowPermissionPromptForDelegatedInstallFunction&) = + delete; + private: using Params = api::dashboard_private::ShowPermissionPromptForDelegatedInstall::Params; @@ -65,9 +72,6 @@ class DashboardPrivateShowPermissionPromptForDelegatedInstallFunction scoped_refptr<Extension> dummy_extension_; std::unique_ptr<ExtensionInstallPrompt> install_prompt_; - - DISALLOW_COPY_AND_ASSIGN( - DashboardPrivateShowPermissionPromptForDelegatedInstallFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc index 9f66c517a72..4e4693f5e16 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc @@ -173,6 +173,10 @@ class ExtensionDevToolsClientHost : public content::DevToolsAgentHostClient, scoped_refptr<const Extension> extension, const Debuggee& debuggee); + ExtensionDevToolsClientHost(const ExtensionDevToolsClientHost&) = delete; + ExtensionDevToolsClientHost& operator=(const ExtensionDevToolsClientHost&) = + delete; + ~ExtensionDevToolsClientHost() override; bool Attach(); @@ -226,8 +230,6 @@ class ExtensionDevToolsClientHost : public content::DevToolsAgentHostClient, // Listen to extension unloaded notification. base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(ExtensionDevToolsClientHost); }; ExtensionDevToolsClientHost::ExtensionDevToolsClientHost( @@ -559,7 +561,7 @@ DebuggerAttachFunction::DebuggerAttachFunction() = default; DebuggerAttachFunction::~DebuggerAttachFunction() = default; ExtensionFunction::ResponseAction DebuggerAttachFunction::Run() { - std::unique_ptr<Attach::Params> params(Attach::Params::Create(*args_)); + std::unique_ptr<Attach::Params> params(Attach::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); @@ -598,7 +600,7 @@ DebuggerDetachFunction::DebuggerDetachFunction() = default; DebuggerDetachFunction::~DebuggerDetachFunction() = default; ExtensionFunction::ResponseAction DebuggerDetachFunction::Run() { - std::unique_ptr<Detach::Params> params(Detach::Params::Create(*args_)); + std::unique_ptr<Detach::Params> params(Detach::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); @@ -619,7 +621,7 @@ DebuggerSendCommandFunction::~DebuggerSendCommandFunction() = default; ExtensionFunction::ResponseAction DebuggerSendCommandFunction::Run() { std::unique_ptr<SendCommand::Params> params( - SendCommand::Params::Create(*args_)); + SendCommand::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); CopyDebuggee(&debuggee_, params->target); diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc index 7aaffd3d9d5..53d1e0c713d 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc @@ -99,7 +99,7 @@ void DebuggerApiTest::SetUpOnMainThread() { testing::AssertionResult DebuggerApiTest::RunAttachFunction( const GURL& url, const std::string& expected_error) { - ui_test_utils::NavigateToURL(browser(), url); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -117,13 +117,13 @@ testing::AssertionResult DebuggerApiTest::RunAttachFunction( std::unique_ptr<base::Value> value( extension_function_test_utils::RunFunctionAndReturnSingleResult( get_targets_function.get(), "[]", browser())); - base::ListValue* targets = nullptr; - EXPECT_TRUE(value->GetAsList(&targets)); + EXPECT_TRUE(value->is_list()); + const base::ListValue& targets = base::Value::AsListValue(*value); std::string debugger_target_id; - for (size_t i = 0; i < targets->GetSize(); ++i) { - base::DictionaryValue* target_dict = nullptr; - EXPECT_TRUE(targets->GetDictionary(i, &target_dict)); + for (size_t i = 0; i < targets.GetList().size(); ++i) { + const base::DictionaryValue* target_dict = nullptr; + EXPECT_TRUE(targets.GetDictionary(i, &target_dict)); int id = -1; if (target_dict->GetInteger("tabId", &id) && id == tab_id) { EXPECT_TRUE(target_dict->GetString("id", &debugger_target_id)); diff --git a/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar_delegate.h b/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar_delegate.h index 4fa19b3dc29..02c0cbd0f5f 100644 --- a/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar_delegate.h +++ b/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar_delegate.h @@ -21,8 +21,7 @@ namespace extensions { // browser (which has security consequences). class ExtensionDevToolsInfoBarDelegate : public ConfirmInfoBarDelegate { public: - static constexpr base::TimeDelta kAutoCloseDelay = - base::TimeDelta::FromSeconds(5); + static constexpr base::TimeDelta kAutoCloseDelay = base::Seconds(5); using CallbackList = base::OnceClosureList; // Ensures a global infobar corresponding to the supplied extension is diff --git a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc index 822cd85a0d4..11dc95b1772 100644 --- a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc @@ -129,7 +129,8 @@ class DeclarativeApiTestWithOriginPolicy : public DeclarativeApiTest { protected: std::u16string NavigateToAndReturnTitle(const char* url) { EXPECT_TRUE(server()); - ui_test_utils::NavigateToURL(browser(), GURL(server()->GetURL(url))); + EXPECT_TRUE( + ui_test_utils::NavigateToURL(browser(), GURL(server()->GetURL(url)))); std::u16string title; ui_test_utils::GetCurrentTabTitle(browser(), &title); return title; @@ -194,7 +195,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, PRE_PersistRules) { IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, PersistRules) { // Wait for declarative rules to be set up from PRE test. profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting(); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_EQ(kTestTitle, GetTitle()); } @@ -218,20 +219,20 @@ IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, ExtensionLifetimeRulesHandling) { profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting(); std::string extension_id(extension->id()); ASSERT_TRUE(ready.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_EQ(kTestTitle, GetTitle()); EXPECT_EQ(1u, NumberOfRegisteredRules(extension_id)); // 2. Disable the extension. Rules are no longer active, but are still // registered. DisableExtension(extension_id); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_NE(kTestTitle, GetTitle()); EXPECT_EQ(1u, NumberOfRegisteredRules(extension_id)); // 3. Enable the extension again. Rules are active again. EnableExtension(extension_id); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_EQ(kTestTitle, GetTitle()); EXPECT_EQ(1u, NumberOfRegisteredRules(extension_id)); @@ -248,19 +249,19 @@ IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, ExtensionLifetimeRulesHandling) { EXPECT_TRUE(UpdateExtension( extension_id, ext_dir.Pack(), 0 /*no new installed extension*/)); ASSERT_TRUE(ready_after_update.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_EQ(kTestTitle, GetTitle()); EXPECT_EQ(1u, NumberOfRegisteredRules(extension_id)); // 5. Reload the extension. Rules remain active. ReloadExtension(extension_id); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_EQ(kTestTitle, GetTitle()); EXPECT_EQ(1u, NumberOfRegisteredRules(extension_id)); // 6. Uninstall the extension. Rules are gone. UninstallExtension(extension_id); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_NE(kTestTitle, GetTitle()); EXPECT_EQ(0u, NumberOfRegisteredRules(extension_id)); } @@ -287,7 +288,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, NoTracesAfterUninstalling) { profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting(); std::string extension_id(extension->id()); ASSERT_TRUE(ready.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_EQ(kTestTitle, GetTitle()); EXPECT_EQ(1u, NumberOfRegisteredRules(extension_id)); ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(browser()->profile()); @@ -297,7 +298,7 @@ IN_PROC_BROWSER_TEST_F(DeclarativeApiTest, NoTracesAfterUninstalling) { UninstallExtension(extension_id); // Wait for declarative rules to be removed. profile()->GetDefaultStoragePartition()->FlushNetworkInterfaceForTesting(); - ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(kArbitraryUrl))); EXPECT_NE(kTestTitle, GetTitle()); EXPECT_EQ(0u, NumberOfRegisteredRules(extension_id)); EXPECT_FALSE(extension_prefs->HasPrefForExtension(extension_id)); diff --git a/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc b/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc index f3cdbb616aa..876c52a27d1 100644 --- a/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative/rules_registry_with_cache_unittest.cc @@ -16,6 +16,7 @@ #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/common/extensions/extension_test_util.h" #include "chrome/test/base/testing_profile.h" +#include "components/value_store/testing_value_store.h" #include "components/version_info/version_info.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" @@ -24,7 +25,6 @@ #include "extensions/browser/api/declarative/test_rules_registry.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" -#include "extensions/browser/value_store/testing_value_store.h" #include "extensions/common/extension.h" #include "extensions/common/features/feature_channel.h" #include "extensions/common/manifest_constants.h" @@ -260,7 +260,8 @@ TEST_F(RulesRegistryWithCacheTest, DeclarativeRulesStored) { } EXPECT_TRUE(cache_delegate->GetDeclarativeRulesStored(extension1_->id())); content::RunAllTasksUntilIdle(); - TestingValueStore* store = env_.GetExtensionSystem()->value_store(); + value_store::TestingValueStore* store = + env_.GetExtensionSystem()->value_store(); ASSERT_TRUE(store); EXPECT_EQ(1, store->write_count()); int write_count = store->write_count(); @@ -305,7 +306,8 @@ TEST_F(RulesRegistryWithCacheTest, EphemeralCacheIsEphemeral) { value.Append(base::Value(true)); cache_delegate->UpdateRules(extension1_->id(), std::move(value)); content::RunAllTasksUntilIdle(); - TestingValueStore* store = env_.GetExtensionSystem()->value_store(); + value_store::TestingValueStore* store = + env_.GetExtensionSystem()->value_store(); ASSERT_TRUE(store); EXPECT_EQ(0, store->write_count()); } diff --git a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc index 82fa40c9217..16922a2aea4 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.cc @@ -39,13 +39,15 @@ class ChromeContentRulesRegistry::EvaluationScope { explicit EvaluationScope(ChromeContentRulesRegistry* registry); EvaluationScope(ChromeContentRulesRegistry* registry, EvaluationDisposition disposition); + + EvaluationScope(const EvaluationScope&) = delete; + EvaluationScope& operator=(const EvaluationScope&) = delete; + ~EvaluationScope(); private: ChromeContentRulesRegistry* const registry_; const EvaluationDisposition previous_disposition_; - - DISALLOW_COPY_AND_ASSIGN(EvaluationScope); }; ChromeContentRulesRegistry::EvaluationScope::EvaluationScope( diff --git a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h index 21dfbfea4ad..a510286e1f3 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h @@ -59,6 +59,10 @@ class ChromeContentRulesRegistry RulesCacheDelegate* cache_delegate, PredicateEvaluatorsFactory evaluators_factory); + ChromeContentRulesRegistry(const ChromeContentRulesRegistry&) = delete; + ChromeContentRulesRegistry& operator=(const ChromeContentRulesRegistry&) = + delete; + // ContentRulesRegistry: void MonitorWebContentsForRuleEvaluation( content::WebContents* contents) override; @@ -98,15 +102,16 @@ class ChromeContentRulesRegistry std::vector<std::unique_ptr<const ContentCondition>> conditions, std::vector<std::unique_ptr<const ContentAction>> actions, int priority); + + ContentRule(const ContentRule&) = delete; + ContentRule& operator=(const ContentRule&) = delete; + ~ContentRule(); const Extension* extension; std::vector<std::unique_ptr<const ContentCondition>> conditions; std::vector<std::unique_ptr<const ContentAction>> actions; int priority; - - private: - DISALLOW_COPY_AND_ASSIGN(ContentRule); }; // Specifies what to do with evaluation requests. @@ -173,8 +178,6 @@ class ChromeContentRulesRegistry // Contains WebContents which require rule evaluation. Only used while // |evaluation_disposition_| is DEFER. std::set<content::WebContents*> evaluation_pending_; - - DISALLOW_COPY_AND_ASSIGN(ChromeContentRulesRegistry); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc index 67ad5d8723f..4c7b848afdf 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry_unittest.cc @@ -29,14 +29,15 @@ class TestPredicate : public ContentPredicate { : evaluator_(evaluator) { } + TestPredicate(const TestPredicate&) = delete; + TestPredicate& operator=(const TestPredicate&) = delete; + ContentPredicateEvaluator* GetEvaluator() const override { return evaluator_; } private: ContentPredicateEvaluator* evaluator_; - - DISALLOW_COPY_AND_ASSIGN(TestPredicate); }; class TestPredicateEvaluator : public ContentPredicateEvaluator { @@ -47,6 +48,9 @@ class TestPredicateEvaluator : public ContentPredicateEvaluator { next_evaluation_result_(false) { } + TestPredicateEvaluator(const TestPredicateEvaluator&) = delete; + TestPredicateEvaluator& operator=(const TestPredicateEvaluator&) = delete; + std::string GetPredicateApiAttributeName() const override { return "test_predicate"; } @@ -115,8 +119,6 @@ class TestPredicateEvaluator : public ContentPredicateEvaluator { ContentPredicateEvaluator::Delegate* delegate_; content::WebContents* contents_for_next_operation_evaluation_; mutable bool next_evaluation_result_; - - DISALLOW_COPY_AND_ASSIGN(TestPredicateEvaluator); }; // Create the test evaluator and set |evaluator| to its pointer. @@ -135,6 +137,11 @@ class DeclarativeChromeContentRulesRegistryTest : public testing::Test { public: DeclarativeChromeContentRulesRegistryTest() {} + DeclarativeChromeContentRulesRegistryTest( + const DeclarativeChromeContentRulesRegistryTest&) = delete; + DeclarativeChromeContentRulesRegistryTest& operator=( + const DeclarativeChromeContentRulesRegistryTest&) = delete; + protected: TestExtensionEnvironment* env() { return &env_; } @@ -143,8 +150,6 @@ class DeclarativeChromeContentRulesRegistryTest : public testing::Test { // Must come after |env_| so only one UI MessageLoop is created. content::RenderViewHostTestEnabler rvh_enabler_; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeChromeContentRulesRegistryTest); }; TEST_F(DeclarativeChromeContentRulesRegistryTest, ActiveRulesDoesntGrow) { diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc b/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc index d3c373509cd..4f8c17769d3 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_action.cc @@ -70,6 +70,10 @@ void RecordContentActionCreated( class ShowExtensionAction : public ContentAction { public: ShowExtensionAction() {} + + ShowExtensionAction(const ShowExtensionAction&) = delete; + ShowExtensionAction& operator=(const ShowExtensionAction&) = delete; + ~ShowExtensionAction() override {} static std::unique_ptr<ContentAction> Create( @@ -115,14 +119,16 @@ class ShowExtensionAction : public ContentAction { return ExtensionActionManager::Get(browser_context) ->GetExtensionAction(*extension); } - - DISALLOW_COPY_AND_ASSIGN(ShowExtensionAction); }; // Action that sets an extension's action icon. class SetIcon : public ContentAction { public: explicit SetIcon(const gfx::Image& icon) : icon_(icon) {} + + SetIcon(const SetIcon&) = delete; + SetIcon& operator=(const SetIcon&) = delete; + ~SetIcon() override {} static std::unique_ptr<ContentAction> Create( @@ -168,8 +174,6 @@ class SetIcon : public ContentAction { } gfx::Image icon_; - - DISALLOW_COPY_AND_ASSIGN(SetIcon); }; // Helper for getting JS collections into C++. diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_action.h b/chromium/chrome/browser/extensions/api/declarative_content/content_action.h index c41375fd7b0..acc68f00fac 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_action.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_action.h @@ -79,6 +79,9 @@ class RequestContentScript : public ContentAction, const Extension* extension, const ScriptData& script_data); + RequestContentScript(const RequestContentScript&) = delete; + RequestContentScript& operator=(const RequestContentScript&) = delete; + ~RequestContentScript() override; static std::unique_ptr<ContentAction> Create( @@ -115,8 +118,6 @@ class RequestContentScript : public ContentAction, ExtensionUserScriptLoader* script_loader_ = nullptr; base::ScopedObservation<UserScriptLoader, UserScriptLoader::Observer> scoped_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(RequestContentScript); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_condition.h b/chromium/chrome/browser/extensions/api/declarative_content/content_condition.h index c9bf5715da3..2b3231990b9 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_condition.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_condition.h @@ -32,12 +32,13 @@ struct ContentCondition { public: explicit ContentCondition( std::vector<std::unique_ptr<const ContentPredicate>> predicates); + + ContentCondition(const ContentCondition&) = delete; + ContentCondition& operator=(const ContentCondition&) = delete; + ~ContentCondition(); std::vector<std::unique_ptr<const ContentPredicate>> predicates; - - private: - DISALLOW_COPY_AND_ASSIGN(ContentCondition); }; // Factory function that instantiates a ContentCondition according to the diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_condition_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/content_condition_unittest.cc index 62aa4c687c0..22f9d87c5ac 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_condition_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_condition_unittest.cc @@ -21,12 +21,12 @@ class TestPredicate : public ContentPredicate { public: TestPredicate() {} + TestPredicate(const TestPredicate&) = delete; + TestPredicate& operator=(const TestPredicate&) = delete; + ContentPredicateEvaluator* GetEvaluator() const override { return nullptr; } - - private: - DISALLOW_COPY_AND_ASSIGN(TestPredicate); }; class TestPredicateFactoryGeneratingError : public ContentPredicateFactory { @@ -35,6 +35,11 @@ class TestPredicateFactoryGeneratingError : public ContentPredicateFactory { : error_(error) { } + TestPredicateFactoryGeneratingError( + const TestPredicateFactoryGeneratingError&) = delete; + TestPredicateFactoryGeneratingError& operator=( + const TestPredicateFactoryGeneratingError&) = delete; + std::unique_ptr<const ContentPredicate> CreatePredicate( const Extension* extension, const base::Value& value, @@ -45,14 +50,17 @@ class TestPredicateFactoryGeneratingError : public ContentPredicateFactory { private: const std::string error_; - - DISALLOW_COPY_AND_ASSIGN(TestPredicateFactoryGeneratingError); }; class TestPredicateFactoryGeneratingPredicate : public ContentPredicateFactory { public: TestPredicateFactoryGeneratingPredicate() {} + TestPredicateFactoryGeneratingPredicate( + const TestPredicateFactoryGeneratingPredicate&) = delete; + TestPredicateFactoryGeneratingPredicate& operator=( + const TestPredicateFactoryGeneratingPredicate&) = delete; + std::unique_ptr<const ContentPredicate> CreatePredicate( const Extension* extension, const base::Value& value, @@ -68,8 +76,6 @@ class TestPredicateFactoryGeneratingPredicate : public ContentPredicateFactory { private: std::vector<const ContentPredicate*> created_predicates_; - - DISALLOW_COPY_AND_ASSIGN(TestPredicateFactoryGeneratingPredicate); }; } // namespace diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_predicate.h b/chromium/chrome/browser/extensions/api/declarative_content/content_predicate.h index 1237ddf65e7..7e14ed3d8a4 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_predicate.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_predicate.h @@ -30,6 +30,9 @@ class Extension; // subclasses. class ContentPredicate { public: + ContentPredicate(const ContentPredicate&) = delete; + ContentPredicate& operator=(const ContentPredicate&) = delete; + virtual ~ContentPredicate(); // Returns true if this predicate should be ignored during evaluation. By @@ -41,9 +44,6 @@ class ContentPredicate { protected: ContentPredicate(); - - private: - DISALLOW_COPY_AND_ASSIGN(ContentPredicate); }; // Defines the interface for objects that create predicates. @@ -55,6 +55,9 @@ class ContentPredicate { // ["input[type='password']"] JSON entities encoded in |value|. class ContentPredicateFactory { public: + ContentPredicateFactory(const ContentPredicateFactory&) = delete; + ContentPredicateFactory& operator=(const ContentPredicateFactory&) = delete; + virtual ~ContentPredicateFactory(); // Creates a new predicate from |value|, as specified in the declarative @@ -66,9 +69,6 @@ class ContentPredicateFactory { protected: ContentPredicateFactory(); - - private: - DISALLOW_COPY_AND_ASSIGN(ContentPredicateFactory); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h b/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h index 1b58e51203e..493cfea7d1e 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/content_predicate_evaluator.h @@ -60,6 +60,10 @@ class ContentPredicateEvaluator : public ContentPredicateFactory { public: class Delegate; + ContentPredicateEvaluator(const ContentPredicateEvaluator&) = delete; + ContentPredicateEvaluator& operator=(const ContentPredicateEvaluator&) = + delete; + ~ContentPredicateEvaluator() override; // Returns the attribute name in the API for this evaluator's predicates. @@ -109,15 +113,15 @@ class ContentPredicateEvaluator : public ContentPredicateFactory { protected: ContentPredicateEvaluator(); - - private: - DISALLOW_COPY_AND_ASSIGN(ContentPredicateEvaluator); }; // Allows an evaluator to notify that predicate evaluation state has been // updated, and determine whether it should manage predicates for a context. class ContentPredicateEvaluator::Delegate { public: + Delegate(const Delegate&) = delete; + Delegate& operator=(const Delegate&) = delete; + // Notifies that predicate evaluation state has been updated for // |contents|. This must be called whenever the URL or page state changes, // even if the value of the predicate evaluation itself doesn't change. @@ -133,9 +137,6 @@ class ContentPredicateEvaluator::Delegate { protected: Delegate(); virtual ~Delegate(); - - private: - DISALLOW_COPY_AND_ASSIGN(Delegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc index 1ad23cd47bd..ff30307242c 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc @@ -121,6 +121,10 @@ class DeclarativeContentApiTest : public ExtensionApiTest { public: DeclarativeContentApiTest() {} + DeclarativeContentApiTest(const DeclarativeContentApiTest&) = delete; + DeclarativeContentApiTest& operator=(const DeclarativeContentApiTest&) = + delete; + protected: enum IncognitoMode { SPANNING, SPLIT }; @@ -134,9 +138,6 @@ class DeclarativeContentApiTest : public ExtensionApiTest { void CheckBookmarkEvents(bool is_bookmarked); TestExtensionDir ext_dir_; - - private: - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentApiTest); }; void DeclarativeContentApiTest::CheckIncognito(IncognitoMode mode, @@ -440,12 +441,15 @@ class ParameterizedShowActionDeclarativeContentApiTest public testing::WithParamInterface<const char*> { public: ParameterizedShowActionDeclarativeContentApiTest() {} + + ParameterizedShowActionDeclarativeContentApiTest( + const ParameterizedShowActionDeclarativeContentApiTest&) = delete; + ParameterizedShowActionDeclarativeContentApiTest& operator=( + const ParameterizedShowActionDeclarativeContentApiTest&) = delete; + ~ParameterizedShowActionDeclarativeContentApiTest() override {} void TestShowAction(absl::optional<ActionInfo::Type> action_type); - - private: - DISALLOW_COPY_AND_ASSIGN(ParameterizedShowActionDeclarativeContentApiTest); }; void ParameterizedShowActionDeclarativeContentApiTest::TestShowAction( @@ -492,8 +496,8 @@ void ParameterizedShowActionDeclarativeContentApiTest::TestShowAction( action->SetIsVisible(ExtensionAction::kDefaultTabId, false); // Open the tab to invoke the APIs, as well as test the action visibility. - ui_test_utils::NavigateToURL(browser(), - extension->GetResourceURL("page.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension->GetResourceURL("page.html"))); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h index 305e041fe88..a7b73d7f76e 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_condition_tracker_test.h @@ -30,6 +30,12 @@ namespace extensions { class DeclarativeContentConditionTrackerTest : public testing::Test { public: DeclarativeContentConditionTrackerTest(); + + DeclarativeContentConditionTrackerTest( + const DeclarativeContentConditionTrackerTest&) = delete; + DeclarativeContentConditionTrackerTest& operator=( + const DeclarativeContentConditionTrackerTest&) = delete; + ~DeclarativeContentConditionTrackerTest() override; protected: @@ -62,8 +68,6 @@ class DeclarativeContentConditionTrackerTest : public testing::Test { std::unique_ptr<TestingProfile> profile_; uintptr_t next_predicate_group_id_; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentConditionTrackerTest); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc index d8dee1189a5..ee96c9747fa 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.cc @@ -43,16 +43,14 @@ DeclarativeContentCssPredicate::Create(ContentPredicateEvaluator* evaluator, const base::Value& value, std::string* error) { std::vector<std::string> css_rules; - const base::ListValue* css_rules_value = nullptr; - if (value.GetAsList(&css_rules_value)) { - for (size_t i = 0; i < css_rules_value->GetSize(); ++i) { - std::string css_rule; - if (!css_rules_value->GetString(i, &css_rule)) { + if (value.is_list()) { + for (const base::Value& css_rule_value : value.GetList()) { + if (!css_rule_value.is_string()) { *error = base::StringPrintf(kCssInvalidTypeOfParameter, declarative_content_constants::kCss); return nullptr; } - css_rules.push_back(css_rule); + css_rules.push_back(css_rule_value.GetString()); } } else { *error = base::StringPrintf(kCssInvalidTypeOfParameter, @@ -177,10 +175,10 @@ void DeclarativeContentCssConditionTracker::StopTrackingPredicates( const std::vector<const void*>& predicate_groups) { bool watched_selectors_updated = false; for (const void* group : predicate_groups) { - auto loc = tracked_predicates_.find(group); - if (loc == tracked_predicates_.end()) + auto it = tracked_predicates_.find(group); + if (it == tracked_predicates_.end()) continue; - for (const DeclarativeContentCssPredicate* predicate : loc->second) { + for (const DeclarativeContentCssPredicate* predicate : it->second) { for (const std::string& selector : predicate->css_selectors()) { auto loc = watched_css_selector_predicate_count_.find(selector); DCHECK(loc != watched_css_selector_predicate_count_.end()); diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.h b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.h index 6a9c23615aa..d704437ad01 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker.h @@ -30,6 +30,11 @@ class Extension; // Tests whether all the specified CSS selectors match on the page. class DeclarativeContentCssPredicate : public ContentPredicate { public: + DeclarativeContentCssPredicate(const DeclarativeContentCssPredicate&) = + delete; + DeclarativeContentCssPredicate& operator=( + const DeclarativeContentCssPredicate&) = delete; + ~DeclarativeContentCssPredicate() override; const std::vector<std::string>& css_selectors() const { @@ -51,8 +56,6 @@ class DeclarativeContentCssPredicate : public ContentPredicate { // Weak. ContentPredicateEvaluator* const evaluator_; std::vector<std::string> css_selectors_; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentCssPredicate); }; // Supports watching of CSS selectors to across tab contents in a browser @@ -62,6 +65,12 @@ class DeclarativeContentCssConditionTracker public content::NotificationObserver { public: explicit DeclarativeContentCssConditionTracker(Delegate* delegate); + + DeclarativeContentCssConditionTracker( + const DeclarativeContentCssConditionTracker&) = delete; + DeclarativeContentCssConditionTracker& operator=( + const DeclarativeContentCssConditionTracker&) = delete; + ~DeclarativeContentCssConditionTracker() override; // ContentPredicateEvaluator: @@ -97,6 +106,10 @@ class DeclarativeContentCssConditionTracker PerWebContentsTracker(content::WebContents* contents, RequestEvaluationCallback request_evaluation, WebContentsDestroyedCallback web_contents_destroyed); + + PerWebContentsTracker(const PerWebContentsTracker&) = delete; + PerWebContentsTracker& operator=(const PerWebContentsTracker&) = delete; + ~PerWebContentsTracker() override; void OnWebContentsNavigation(content::NavigationHandle* navigation_handle); @@ -116,8 +129,6 @@ class DeclarativeContentCssConditionTracker // We use a hash_set for maximally efficient lookup. std::unordered_set<std::string> matching_css_selectors_; - - DISALLOW_COPY_AND_ASSIGN(PerWebContentsTracker); }; // content::NotificationObserver implementation. @@ -158,8 +169,6 @@ class DeclarativeContentCssConditionTracker // Manages our notification registrations. content::NotificationRegistrar registrar_; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentCssConditionTracker); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc index 0158fb6994d..60391d36d66 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_css_condition_tracker_unittest.cc @@ -119,6 +119,12 @@ class InterceptingRendererStartupHelper : public RendererStartupHelper, class DeclarativeContentCssConditionTrackerTest : public DeclarativeContentConditionTrackerTest { + public: + DeclarativeContentCssConditionTrackerTest( + const DeclarativeContentCssConditionTrackerTest&) = delete; + DeclarativeContentCssConditionTrackerTest& operator=( + const DeclarativeContentCssConditionTrackerTest&) = delete; + protected: DeclarativeContentCssConditionTrackerTest() : tracker_(&delegate_) {} @@ -141,6 +147,9 @@ class DeclarativeContentCssConditionTrackerTest public: Delegate() : evaluation_requests_(0) {} + Delegate(const Delegate&) = delete; + Delegate& operator=(const Delegate&) = delete; + int evaluation_requests() { return evaluation_requests_; } // ContentPredicateEvaluator::Delegate: @@ -155,8 +164,6 @@ class DeclarativeContentCssConditionTrackerTest private: int evaluation_requests_; - - DISALLOW_COPY_AND_ASSIGN(Delegate); }; // Creates a predicate with appropriate expectations of success. @@ -221,8 +228,6 @@ class DeclarativeContentCssConditionTrackerTest EXPECT_EQ("", error); ASSERT_TRUE(*predicate); } - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentCssConditionTrackerTest); }; TEST(DeclarativeContentCssPredicateTest, WrongCssDatatype) { diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h index 139c1445ce2..592eb547398 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker.h @@ -27,6 +27,11 @@ namespace extensions { // Tests the bookmarked state of the page. class DeclarativeContentIsBookmarkedPredicate : public ContentPredicate { public: + DeclarativeContentIsBookmarkedPredicate( + const DeclarativeContentIsBookmarkedPredicate&) = delete; + DeclarativeContentIsBookmarkedPredicate& operator=( + const DeclarativeContentIsBookmarkedPredicate&) = delete; + ~DeclarativeContentIsBookmarkedPredicate() override; bool IsIgnored() const override; @@ -53,8 +58,6 @@ class DeclarativeContentIsBookmarkedPredicate : public ContentPredicate { scoped_refptr<const Extension> extension_; bool is_bookmarked_; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentIsBookmarkedPredicate); }; // Supports tracking of URL matches across tab contents in a browser context, @@ -66,6 +69,12 @@ class DeclarativeContentIsBookmarkedConditionTracker DeclarativeContentIsBookmarkedConditionTracker( content::BrowserContext* context, Delegate* delegate); + + DeclarativeContentIsBookmarkedConditionTracker( + const DeclarativeContentIsBookmarkedConditionTracker&) = delete; + DeclarativeContentIsBookmarkedConditionTracker& operator=( + const DeclarativeContentIsBookmarkedConditionTracker&) = delete; + ~DeclarativeContentIsBookmarkedConditionTracker() override; // ContentPredicateEvaluator: @@ -100,6 +109,10 @@ class DeclarativeContentIsBookmarkedConditionTracker PerWebContentsTracker(content::WebContents* contents, RequestEvaluationCallback request_evaluation, WebContentsDestroyedCallback web_contents_destroyed); + + PerWebContentsTracker(const PerWebContentsTracker&) = delete; + PerWebContentsTracker& operator=(const PerWebContentsTracker&) = delete; + ~PerWebContentsTracker() override; void BookmarkAddedForUrl(const GURL& url); @@ -119,8 +132,6 @@ class DeclarativeContentIsBookmarkedConditionTracker bool is_url_bookmarked_; const RequestEvaluationCallback request_evaluation_; WebContentsDestroyedCallback web_contents_destroyed_; - - DISALLOW_COPY_AND_ASSIGN(PerWebContentsTracker); }; // bookmarks::BookmarkModelObserver implementation. @@ -163,8 +174,6 @@ class DeclarativeContentIsBookmarkedConditionTracker base::ScopedObservation<bookmarks::BookmarkModel, bookmarks::BookmarkModelObserver> scoped_bookmarks_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentIsBookmarkedConditionTracker); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc index 8c62bcff1c8..69402861e54 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_is_bookmarked_condition_tracker_unittest.cc @@ -68,11 +68,20 @@ using testing::UnorderedElementsAreArray; class DeclarativeContentIsBookmarkedConditionTrackerTest : public DeclarativeContentConditionTrackerTest { + public: + DeclarativeContentIsBookmarkedConditionTrackerTest( + const DeclarativeContentIsBookmarkedConditionTrackerTest&) = delete; + DeclarativeContentIsBookmarkedConditionTrackerTest& operator=( + const DeclarativeContentIsBookmarkedConditionTrackerTest&) = delete; + protected: class Delegate : public ContentPredicateEvaluator::Delegate { public: Delegate() {} + Delegate(const Delegate&) = delete; + Delegate& operator=(const Delegate&) = delete; + std::set<content::WebContents*>& evaluation_requests() { return evaluation_requests_; } @@ -90,8 +99,6 @@ class DeclarativeContentIsBookmarkedConditionTrackerTest private: std::set<content::WebContents*> evaluation_requests_; - - DISALLOW_COPY_AND_ASSIGN(Delegate); }; DeclarativeContentIsBookmarkedConditionTrackerTest() { @@ -153,9 +160,6 @@ class DeclarativeContentIsBookmarkedConditionTrackerTest is_bookmarked_predicate_; std::unique_ptr<DeclarativeContentIsBookmarkedPredicate> is_not_bookmarked_predicate_; - - private: - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentIsBookmarkedConditionTrackerTest); }; diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.h b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.h index deb52e818fe..38d6fa43b38 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.h +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker.h @@ -27,6 +27,11 @@ class Extension; // URLMatcherConditionSet. class DeclarativeContentPageUrlPredicate : public ContentPredicate { public: + DeclarativeContentPageUrlPredicate( + const DeclarativeContentPageUrlPredicate&) = delete; + DeclarativeContentPageUrlPredicate& operator=( + const DeclarativeContentPageUrlPredicate&) = delete; + ~DeclarativeContentPageUrlPredicate() override; url_matcher::URLMatcherConditionSet* url_matcher_condition_set() const { @@ -52,8 +57,6 @@ class DeclarativeContentPageUrlPredicate : public ContentPredicate { ContentPredicateEvaluator* const evaluator_; scoped_refptr<url_matcher::URLMatcherConditionSet> url_matcher_condition_set_; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentPageUrlPredicate); }; // Supports tracking of URL matches across tab contents in a browser context, @@ -62,6 +65,12 @@ class DeclarativeContentPageUrlConditionTracker : public ContentPredicateEvaluator { public: explicit DeclarativeContentPageUrlConditionTracker(Delegate* delegate); + + DeclarativeContentPageUrlConditionTracker( + const DeclarativeContentPageUrlConditionTracker&) = delete; + DeclarativeContentPageUrlConditionTracker& operator=( + const DeclarativeContentPageUrlConditionTracker&) = delete; + ~DeclarativeContentPageUrlConditionTracker() override; // ContentPredicateEvaluator: @@ -100,6 +109,10 @@ class DeclarativeContentPageUrlConditionTracker url_matcher::URLMatcher* url_matcher, RequestEvaluationCallback request_evaluation, WebContentsDestroyedCallback web_contents_destroyed); + + PerWebContentsTracker(const PerWebContentsTracker&) = delete; + PerWebContentsTracker& operator=(const PerWebContentsTracker&) = delete; + ~PerWebContentsTracker() override; void UpdateMatchesForCurrentUrl(bool request_evaluation_if_unchanged); @@ -117,8 +130,6 @@ class DeclarativeContentPageUrlConditionTracker WebContentsDestroyedCallback web_contents_destroyed_; std::set<url_matcher::URLMatcherConditionSet::ID> matches_; - - DISALLOW_COPY_AND_ASSIGN(PerWebContentsTracker); }; // Called by PerWebContentsTracker on web contents destruction. @@ -139,8 +150,6 @@ class DeclarativeContentPageUrlConditionTracker // Maps WebContents to the tracker for that WebContents state. std::map<content::WebContents*, std::unique_ptr<PerWebContentsTracker>> per_web_contents_tracker_; - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentPageUrlConditionTracker); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc index 84fab1a24bc..9d44a874d4d 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_page_url_condition_tracker_unittest.cc @@ -27,11 +27,20 @@ using testing::UnorderedElementsAreArray; class DeclarativeContentPageUrlConditionTrackerTest : public DeclarativeContentConditionTrackerTest { + public: + DeclarativeContentPageUrlConditionTrackerTest( + const DeclarativeContentPageUrlConditionTrackerTest&) = delete; + DeclarativeContentPageUrlConditionTrackerTest& operator=( + const DeclarativeContentPageUrlConditionTrackerTest&) = delete; + protected: class Delegate : public ContentPredicateEvaluator::Delegate { public: Delegate() {} + Delegate(const Delegate&) = delete; + Delegate& operator=(const Delegate&) = delete; + std::set<content::WebContents*>& evaluation_requests() { return evaluation_requests_; } @@ -49,8 +58,6 @@ class DeclarativeContentPageUrlConditionTrackerTest private: std::set<content::WebContents*> evaluation_requests_; - - DISALLOW_COPY_AND_ASSIGN(Delegate); }; DeclarativeContentPageUrlConditionTrackerTest() @@ -84,8 +91,6 @@ class DeclarativeContentPageUrlConditionTrackerTest EXPECT_EQ("", error); ASSERT_TRUE(*predicate); } - - DISALLOW_COPY_AND_ASSIGN(DeclarativeContentPageUrlConditionTrackerTest); }; TEST(DeclarativeContentPageUrlPredicateTest, WrongPageUrlDatatype) { diff --git a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc index 4a99b452a50..7f54a9e9bd5 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc @@ -132,9 +132,8 @@ testing::AssertionResult RequestContentScriptAPITest::RunTest( false /* won't reply */); injection_succeeded_listener.set_extension_id(extension_->id()); - ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("/extensions/test_file.html")); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/extensions/test_file.html"))); content::WebContents* web_contents = browser() ? browser()->tab_strip_model()->GetActiveWebContents() : NULL; diff --git a/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc index 23de89b6802..b4c72cafc86 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc @@ -8,6 +8,8 @@ #include "components/version_info/version_info.h" #include "content/public/browser/storage_partition.h" #include "content/public/test/browser_test.h" +#include "extensions/browser/api/declarative/rules_registry.h" +#include "extensions/browser/api/declarative/rules_registry_service.h" #include "extensions/browser/extension_action_manager.h" #include "extensions/common/features/feature_channel.h" #include "extensions/test/extension_test_message_listener.h" @@ -33,6 +35,10 @@ const char kDeclarativeContentManifest[] = " ]\n" "}\n"; +constexpr char kOneByOneImageData[] = + "GAAAAAAAAAAQAAAAAAAAADAAAAAAAAAAKAAAAAAAAAACAAAAAQAAAAEAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAwAAAAEAAAAAAAAAAAAAAA="; + class SetIconAPITest : public ExtensionApiTest { public: SetIconAPITest() @@ -57,7 +63,7 @@ IN_PROC_BROWSER_TEST_F(SetIconAPITest, Overview) { "\n" "var canvas = document.createElement(\'canvas\');\n" "var ctx = canvas.getContext(\"2d\");" - "var imageData = ctx.createImageData(19,19);\n" + "var imageData = ctx.createImageData(1, 1);\n" "\n" "var rule0 = {\n" " conditions: [new PageStateMatcher({\n" @@ -84,6 +90,30 @@ IN_PROC_BROWSER_TEST_F(SetIconAPITest, Overview) { ASSERT_TRUE(action); ASSERT_TRUE(ready.WaitUntilSatisfied()); + + // Regression test for crbug.com/1231027. + { + scoped_refptr<RulesRegistry> rules_registry = + extensions::RulesRegistryService::Get(browser()->profile()) + ->GetRulesRegistry(RulesRegistryService::kDefaultRulesRegistryID, + "declarativeContent.onPageChanged"); + ASSERT_TRUE(rules_registry); + + std::vector<const api::events::Rule*> rules; + rules_registry->GetAllRules(extension->id(), &rules); + ASSERT_EQ(1u, rules.size()); + ASSERT_EQ(rules[0]->actions.size(), 1u); + + base::Value& action_value = *rules[0]->actions[0]; + base::Value* action_instance_type = action_value.FindPath("instanceType"); + ASSERT_TRUE(action_instance_type); + EXPECT_EQ("declarativeContent.SetIcon", action_instance_type->GetString()); + + base::Value* image_data_value = action_value.FindPath({"imageData", "1"}); + ASSERT_TRUE(image_data_value); + EXPECT_EQ(kOneByOneImageData, image_data_value->GetString()); + } + content::WebContents* const tab = browser()->tab_strip_model()->GetWebContentsAt(0); const int tab_id = ExtensionTabUtil::GetTabId(tab); diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/action_tracker_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/action_tracker_unittest.cc index 8b7e21cdcd7..7e3dd1da03d 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/action_tracker_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/action_tracker_unittest.cc @@ -197,8 +197,8 @@ TEST_P(ActionTrackerTest, GetMatchedRulesLifespan) { // Half life of a matched rule associated with a non-active tab, with 50ms // added. - base::TimeDelta half_life = (ActionTracker::kNonActiveTabRuleLifespan / 2) + - base::TimeDelta::FromMilliseconds(50); + base::TimeDelta half_life = + (ActionTracker::kNonActiveTabRuleLifespan / 2) + base::Milliseconds(50); // Advance the clock by half of the lifespan of a matched rule for the unknown // tab ID. @@ -287,8 +287,7 @@ TEST_P(ActionTrackerTest, RulesClearedOnTimer) { // Advance the clock by more than the lifespan of a rule through // |mock_time_task_runner|. mock_time_task_runner->FastForwardBy( - ActionTracker::kNonActiveTabRuleLifespan + - base::TimeDelta::FromSeconds(1)); + ActionTracker::kNonActiveTabRuleLifespan + base::Seconds(1)); // Verify that the rule has been cleared by the recurring task. EXPECT_EQ(0, action_tracker()->GetMatchedRuleCountForTest( diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc index ec2b6906aba..d4d0507fb2c 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_apitest.cc @@ -23,7 +23,7 @@ class DeclarativeNetRequestAPItest : public extensions::ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - DeclarativeNetRequestAPItest() = default; + DeclarativeNetRequestAPItest() : ExtensionApiTest(GetParam()) {} ~DeclarativeNetRequestAPItest() override = default; DeclarativeNetRequestAPItest(const DeclarativeNetRequestAPItest&) = delete; DeclarativeNetRequestAPItest& operator=(const DeclarativeNetRequestAPItest&) = @@ -53,12 +53,6 @@ class DeclarativeNetRequestAPItest test_data_dir_ = temp_dir_.GetPath().AppendASCII("declarative_net_request"); } - bool RunTest(const std::string& extension_path) { - return RunExtensionTest( - extension_path.c_str(), {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } - private: base::ScopedTempDir temp_dir_; }; @@ -76,7 +70,7 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, ::testing::Values(ContextType::kServiceWorker)); IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, DynamicRules) { - ASSERT_TRUE(RunTest("dynamic_rules")) << message_; + ASSERT_TRUE(RunExtensionTest("dynamic_rules")) << message_; } // Flaky on ASAN/MSAN: https://crbug.com/1167168 @@ -87,25 +81,25 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, DynamicRules) { #endif IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, MAYBE_DynamicRulesLimits) { - ASSERT_TRUE(RunTest("dynamic_rules_limits")) << message_; + ASSERT_TRUE(RunExtensionTest("dynamic_rules_limits")) << message_; } IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, OnRulesMatchedDebug) { - ASSERT_TRUE(RunTest("on_rules_matched_debug")) << message_; + ASSERT_TRUE(RunExtensionTest("on_rules_matched_debug")) << message_; } // This test uses webRequest/webRequestBlocking, so it's not currently // supported for service workers. IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestAPItest, ModifyHeaders) { - ASSERT_TRUE(RunTest("modify_headers")) << message_; + ASSERT_TRUE(RunExtensionTest("modify_headers")) << message_; } IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, GetMatchedRules) { - ASSERT_TRUE(RunTest("get_matched_rules")) << message_; + ASSERT_TRUE(RunExtensionTest("get_matched_rules")) << message_; } IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestLazyAPItest, IsRegexSupported) { - ASSERT_TRUE(RunTest("is_regex_supported")) << message_; + ASSERT_TRUE(RunExtensionTest("is_regex_supported")) << message_; } } // namespace diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc index 92f3c009ce5..271c7d59d5a 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_browsertest.cc @@ -75,6 +75,7 @@ #include "content/public/test/simple_url_loader_test_helper.h" #include "content/public/test/test_navigation_observer.h" #include "content/public/test/test_utils.h" +#include "content/public/test/web_transport_simple_test_server.h" #include "extensions/browser/api/declarative_net_request/action_tracker.h" #include "extensions/browser/api/declarative_net_request/composite_matcher.h" #include "extensions/browser/api/declarative_net_request/constants.h" @@ -180,12 +181,20 @@ class DeclarativeNetRequestBrowserTest public ::testing::WithParamInterface<ExtensionLoadType> { public: DeclarativeNetRequestBrowserTest() { - feature_list_.InitWithFeatures({blink::features::kFledgeInterestGroups, - blink::features::kFledgeInterestGroupAPI}, - {}); + feature_list_.InitWithFeatures( + /*enabled_features=*/ + {blink::features::kInterestGroupStorage, + blink::features::kAdInterestGroupAPI, blink::features::kFledge}, + /*disabled_features=*/ + {}); net::test_server::RegisterDefaultHandlers(embedded_test_server()); } + DeclarativeNetRequestBrowserTest(const DeclarativeNetRequestBrowserTest&) = + delete; + DeclarativeNetRequestBrowserTest& operator=( + const DeclarativeNetRequestBrowserTest&) = delete; + // Returns the path of the files served by the EmbeddedTestServer. static base::FilePath GetHttpServerPath() { base::FilePath test_root_path; @@ -359,7 +368,7 @@ class DeclarativeNetRequestBrowserTest // Returns true if the navigation to given |url| is blocked. bool IsNavigationBlocked(const GURL& url) { - ui_test_utils::NavigateToURL(browser(), url); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); return !WasFrameWithScriptLoaded(GetMainFrame()); } @@ -601,6 +610,13 @@ class DeclarativeNetRequestBrowserTest std::make_unique<RulesetManagerObserver>(ruleset_manager()); } + net::EmbeddedTestServer* https_server() { + if (!https_server_) + InitializeHttpsServer(); + + return https_server_.get(); + } + private: enum class RulesetScope { kDynamic, kSession }; void UpdateRules(const ExtensionId& extension_id, @@ -732,9 +748,6 @@ class DeclarativeNetRequestBrowserTest tester.ExpectTotalCount(kIndexAndPersistRulesTimeHistogram, expected_histogram_counts); - tester.ExpectBucketCount(kManifestRulesCountHistogram, - expected_manifest_rules_count /*sample*/, - expected_histogram_counts); tester.ExpectBucketCount(kManifestEnabledRulesCountHistogram, expected_manifest_enabled_rules_count /*sample*/, expected_histogram_counts); @@ -746,7 +759,13 @@ class DeclarativeNetRequestBrowserTest LoadRulesetResult::kSuccess /*sample*/, expected_enabled_rulesets_count); - EXPECT_TRUE(AreAllIndexedStaticRulesetsValid(*extension, profile())); + auto ruleset_filter = FileBackedRulesetSource::RulesetFilter::kIncludeAll; + if (GetParam() == ExtensionLoadType::PACKED) { + ruleset_filter = + FileBackedRulesetSource::RulesetFilter::kIncludeManifestEnabled; + } + EXPECT_TRUE(AreAllIndexedStaticRulesetsValid(*extension, profile(), + ruleset_filter)); // Wait for the background page to load if needed. if (flags_ & kConfig_HasBackgroundScript) { @@ -789,6 +808,18 @@ class DeclarativeNetRequestBrowserTest return ExecuteScriptInBackgroundPage(extension_id, script); } + void InitializeHttpsServer() { + https_server_ = std::make_unique<net::EmbeddedTestServer>( + net::test_server::EmbeddedTestServer::TYPE_HTTPS); + + https_server_->SetSSLConfig(net::EmbeddedTestServer::CERT_OK); + https_server_->AddDefaultHandlers(); + https_server_->ServeFilesFromDirectory(GetHttpServerPath()); + https_server_->RegisterRequestMonitor( + base::BindRepeating(&DeclarativeNetRequestBrowserTest::MonitorRequest, + base::Unretained(this))); + } + base::test::ScopedFeatureList feature_list_; base::ScopedTempDir temp_dir_; @@ -811,7 +842,8 @@ class DeclarativeNetRequestBrowserTest // Path to the PEM file for the last installed packed extension. base::FilePath last_pem_path_; - DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestBrowserTest); + // Most tests don't use this, so it is initialized lazily. + std::unique_ptr<net::EmbeddedTestServer> https_server_; }; using DeclarativeNetRequestBrowserTest_Packed = @@ -906,7 +938,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, embedded_test_server()->GetURL(test_case.hostname, test_case.path); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(test_case.expect_main_frame_loaded, WasFrameWithScriptLoaded(GetMainFrame())); @@ -947,7 +979,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, GURL url = embedded_test_server()->GetURL("google.com", test_case.url_path); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(test_case.expect_main_frame_loaded, WasFrameWithScriptLoaded(GetMainFrame())); @@ -968,7 +1000,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, GURL url = embedded_test_server()->GetURL("google.com", "/pages_with_script/page2.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_FALSE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType()); } @@ -1014,7 +1046,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, embedded_test_server()->GetURL(test_case.hostname, test_case.path); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(test_case.expect_main_frame_loaded, WasFrameWithScriptLoaded(GetMainFrame())); @@ -1078,7 +1110,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, "/page_with_two_frames.html"); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); content::RenderFrameHost* main_frame = GetMainFrame(); EXPECT_TRUE(WasFrameWithScriptLoaded(main_frame)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); @@ -1119,7 +1151,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, GURL url = embedded_test_server()->GetURL("example.com", "/domain_type_test.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); ASSERT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); @@ -1192,7 +1224,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowBlock) { base::StringPrintf("/pages_with_script/page.html?num=%d", i)); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // All requests ending with odd numbers should be blocked. const bool page_should_load = (i % 2 == 0); @@ -1270,7 +1302,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowRedirect) { GURL url = test_case.initial_url; SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); GURL final_url = web_contents()->GetLastCommittedURL(); @@ -1295,7 +1327,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowRedirect) { GURL url = test_case.initial_url; SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); GURL final_url = web_contents()->GetLastCommittedURL(); @@ -1303,10 +1335,17 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowRedirect) { } } +// Test is flaky on win. http://crbug.com/1241762. +#if defined(OS_WIN) +#define MAYBE_Enable_Disable_Reload_Uninstall \ + DISABLED_Enable_Disable_Reload_Uninstall +#else +#define MAYBE_Enable_Disable_Reload_Uninstall Enable_Disable_Reload_Uninstall +#endif // Tests that the extension ruleset is active only when the extension is // enabled. IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, - Enable_Disable_Reload_Uninstall) { + MAYBE_Enable_Disable_Reload_Uninstall) { set_config_flags(ConfigFlag::kConfig_HasBackgroundScript); // Block all main frame requests to "static.example". @@ -1430,7 +1469,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, "/pages_with_script/page.html"); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(test_case.expect_main_frame_loaded, WasFrameWithScriptLoaded(GetMainFrame())); content::PageType expected_page_type = test_case.expect_main_frame_loaded @@ -1482,7 +1521,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // corresponding to the most recently installed extension. GURL url = embedded_test_server()->GetURL("example.com", "/pages_with_script/page.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); GURL final_url = web_contents()->GetLastCommittedURL(); @@ -1554,7 +1593,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) { std::string url = get_url_for_host(test_case.hostname); SCOPED_TRACE(base::StringPrintf("Testing %s", url.c_str())); - ui_test_utils::NavigateToURL(browser(), GURL(url)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(url))); EXPECT_EQ(test_case.expected_main_frame_loaded, WasFrameWithScriptLoaded(GetMainFrame())); @@ -1624,7 +1663,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RedirectPriority) { "/pages_with_script/page.html"); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); GURL final_url = web_contents()->GetLastCommittedURL(); @@ -1642,17 +1681,12 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RedirectPriority) { // Test that upgradeScheme rules will change the scheme of matching requests to // https. IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, UpgradeRules) { - auto get_url_for_host = [this](std::string hostname, const char* scheme) { - GURL url = embedded_test_server()->GetURL(hostname, - "/pages_with_script/index.html"); - - url::Replacements<char> replacements; - replacements.SetScheme(scheme, url::Component(0, strlen(scheme))); - - return url.ReplaceComponents(replacements); + auto get_url_for_host = [this](std::string hostname) { + return embedded_test_server()->GetURL(hostname, + "/pages_with_script/index.html"); }; - GURL google_url = get_url_for_host("google.com", url::kHttpScheme); + GURL google_url = get_url_for_host("google.com"); struct { std::string url_filter; int id; @@ -1702,26 +1736,25 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, UpgradeRules) { struct { std::string hostname; - const char* scheme; // |expected_final_url| is null if the request is expected to be blocked. absl::optional<GURL> expected_final_url; } test_cases[] = { - {"exact.com", url::kHttpScheme, absl::nullopt}, + {"exact.com", absl::nullopt}, // http://example.com -> https://example.com/ -> http://google.com - {"example.com", url::kHttpScheme, google_url}, + {"example.com", google_url}, // test_extension_2 should upgrade the scheme for http://yahoo.com // despite having no host permissions. Note that this request is not // matched with test_extension_1's ruleset as test_extension_2 is // installed more recently. // http://yahoo.com -> https://yahoo.com/ -> http://google.com - {"yahoo.com", url::kHttpScheme, google_url}, + {"yahoo.com", google_url}, }; for (const auto& test_case : test_cases) { - GURL url = get_url_for_host(test_case.hostname, test_case.scheme); + GURL url = get_url_for_host(test_case.hostname); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); if (!test_case.expected_final_url) { EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType()); @@ -1754,13 +1787,13 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, util::IsIncognitoEnabled(extension_id, profile())); // The url should be blocked in normal context. - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_FALSE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType()); // In incognito context, the url should be blocked if the extension is // enabled in incognito mode. - ui_test_utils::NavigateToURL(incognito_browser, url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, url)); EXPECT_EQ(!expected_enabled_in_incognito, WasFrameWithScriptLoaded(GetMainFrame(incognito_browser))); content::PageType expected_page_type = expected_enabled_in_incognito @@ -1796,6 +1829,94 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, } } +// Tests the declarativeNetRequestWithHostAccess permission. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, HostAccessPermission) { + std::vector<TestRule> rules; + int rule_id = kMinValidID; + + auto get_url = [this](const std::string& host, const std::string& query) { + std::string path = "/pages_with_script/index.html?q=" + query; + + return embedded_test_server()->GetURL(host, path); + }; + + { + TestRule rule = CreateMainFrameBlockRule("block"); + rule.id = rule_id++; + rules.push_back(rule); + } + + { + TestRule rule = CreateGenericRule(rule_id++); + rule.condition->url_filter = "redirect"; + rule.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule.action->type = "redirect"; + rule.action->redirect.emplace(); + rule.action->redirect->url = get_url("final.com", "final").spec(); + rules.push_back(rule); + } + + { + TestRule rule = CreateGenericRule(rule_id++); + rule.condition->url_filter = "|http://*upgrade"; + rule.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule.action->type = "upgradeScheme"; + rules.push_back(rule); + } + + { + // Have a rule which redirects upgraded https requests to a special url. It + // might seem that this can be avoided by using a HTTPS test server but it + // doesn't seem trivial to listen to the same port on both http and https. + TestRule rule = CreateGenericRule(rule_id++); + rule.condition->url_filter = "|https://*upgrade"; + rule.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule.action->type = "redirect"; + rule.action->redirect.emplace(); + rule.action->redirect->url = get_url("https.com", "https").spec(); + rules.push_back(rule); + } + + set_config_flags( + ConfigFlag::kConfig_HasDelarativeNetRequestWithHostAccessPermission | + ConfigFlag::kConfig_OmitDeclarativeNetRequestPermission); + ASSERT_NO_FATAL_FAILURE( + LoadExtensionWithRules(rules, "directory", {"*://allowed.com:*/*"})); + + struct { + GURL url; + // nullopt if expected to be blocked. + absl::optional<GURL> expected_final_url; + } cases[] = { + {get_url("allowed.com", "block"), absl::nullopt}, + {get_url("notallowed.com", "block"), get_url("notallowed.com", "block")}, + {get_url("allowed.com", "redirect"), get_url("final.com", "final")}, + {get_url("notallowed.com", "redirect"), + get_url("notallowed.com", "redirect")}, + + // This should be upgraded first and then match the https->http rule. + {get_url("allowed.com", "upgrade"), get_url("https.com", "https")}, + + {get_url("notallowed.com", "upgrade"), + get_url("notallowed.com", "upgrade")}, + }; + + for (const auto& test_case : cases) { + SCOPED_TRACE( + base::StringPrintf("Testing %s", test_case.url.spec().c_str())); + + if (!test_case.expected_final_url) { + EXPECT_TRUE(IsNavigationBlocked(test_case.url)); + continue; + } + + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_case.url)); + EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); + EXPECT_EQ(*test_case.expected_final_url, + web_contents()->GetLastCommittedURL()); + } +} + #if defined(OS_MAC) && !defined(NDEBUG) // Times out on mac-debug: https://crbug.com/1159418 #define MAYBE_ChromeURLS DISABLED_ChromeURLS @@ -1816,7 +1937,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, MAYBE_ChromeURLS) { chrome::kChromeUIExtensionsURL, chrome::kChromeUIVersionURL}; for (const char* url : test_urls) { - ui_test_utils::NavigateToURL(browser(), GURL(url)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(url))); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); } } @@ -1942,7 +2063,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ASSERT_NO_FATAL_FAILURE( LoadExtensionWithRules({CreateMainFrameBlockRule("example.com")})); - ui_test_utils::NavigateToURL(browser(), GetURLForFilter("example.com")); + ASSERT_TRUE( + ui_test_utils::NavigateToURL(browser(), GetURLForFilter("example.com"))); EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType()); std::string body; @@ -2004,7 +2126,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) { "example.com", "/cached/page_with_cacheable_script.html"); // With no extension loaded, the request to the script should succeed. - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); @@ -2020,7 +2142,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) { // Another request to |url| should not cause a network request for // script.js since it will be served by the renderer's in-memory // cache. - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_FALSE(base::Contains( @@ -2034,7 +2156,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) { // Adding an extension ruleset should have cleared the renderer's in-memory // cache. Hence the browser process will observe the request to // script.js and block it. - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_FALSE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_TRUE(base::Contains( @@ -2047,7 +2169,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) { // Disabling the extension should cause the request to succeed again. The // request for the script will again be observed by the browser since it's not // in the renderer's in-memory cache. - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_EQ(expect_request_seen, @@ -2079,9 +2201,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ->FlushProxyConfigMonitorForTesting(); // Verify that the extension can't intercept the network request. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), - GURL("http://does.not.resolve.test/pages_with_script/page.html")); + GURL("http://does.not.resolve.test/pages_with_script/page.html"))); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); } @@ -2119,10 +2241,12 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // Extension 1 should not be able to block the request to its own // manifest.json or that of the Extension 2, even with "<all_urls>" host // permissions. - ui_test_utils::NavigateToURL(browser(), get_manifest_url(extension_id_1)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), + get_manifest_url(extension_id_1))); GURL final_url = web_contents()->GetLastCommittedURL(); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); - ui_test_utils::NavigateToURL(browser(), get_manifest_url(extension_id_2)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), + get_manifest_url(extension_id_2))); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); } @@ -2130,8 +2254,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ImageCollapsed) { // Loads a page with an image and returns whether the image was collapsed. auto is_image_collapsed = [this]() { - ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("google.com", "/image.html")); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), + embedded_test_server()->GetURL("google.com", "/image.html"))); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); bool is_image_collapsed = false; const std::string script = @@ -2188,7 +2313,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, IFrameCollapsed) { // Load a page with two iframes (|kFrameName1| and |kFrameName2|). Initially // both the frames should be loaded successfully. - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); { SCOPED_TRACE("No extension loaded"); @@ -2202,7 +2327,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, IFrameCollapsed) { ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule})); // Reloading the page should cause |kFrameName1| to be collapsed. - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); { SCOPED_TRACE("Extension loaded initial"); @@ -2251,7 +2376,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, const Extension* extension = last_loaded_extension(); std::vector<FileBackedRulesetSource> static_sources = - FileBackedRulesetSource::CreateStatic(*extension); + FileBackedRulesetSource::CreateStatic( + *extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(1u, static_sources.size()); FileBackedRulesetSource dynamic_source = FileBackedRulesetSource::CreateDynamic(profile(), extension->id()); @@ -2372,7 +2498,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ASSERT_TRUE(extension); std::vector<FileBackedRulesetSource> sources = - FileBackedRulesetSource::CreateStatic(*extension); + FileBackedRulesetSource::CreateStatic( + *extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(kNumStaticRulesets, sources.size()); // Mimic extension prefs corruption by overwriting the indexed ruleset @@ -2494,7 +2621,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, const ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); const Extension* extension = last_loaded_extension(); std::vector<FileBackedRulesetSource> static_sources = - FileBackedRulesetSource::CreateStatic(*extension); + FileBackedRulesetSource::CreateStatic( + *extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(static_cast<size_t>(kNumStaticRulesets), static_sources.size()); int checksum = kTestChecksum + 1; @@ -2522,7 +2650,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, const Extension* extension = last_loaded_extension(); std::vector<FileBackedRulesetSource> static_sources = - FileBackedRulesetSource::CreateStatic(*extension); + FileBackedRulesetSource::CreateStatic( + *extension, FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(1u, static_sources.size()); DisableExtension(extension_id); @@ -2595,7 +2724,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, const GURL& page_url, bool expect_script_redirected, int expected_blocked_actions) { - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); // The page should have loaded correctly. EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); @@ -2731,16 +2860,16 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // Request made by index.html to script.js should be blocked despite the // extension having no active host permissions to the request. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( - "example.com", "/pages_with_script/index.html")); + "example.com", "/pages_with_script/index.html"))); EXPECT_FALSE(WasFrameWithScriptLoaded(GetMainFrame())); // Sanity check that the script.js request is not blocked if does not match a // rule. - ui_test_utils::NavigateToURL(browser(), - embedded_test_server()->GetURL( - "foo.com", "/pages_with_script/index.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL( + "foo.com", "/pages_with_script/index.html"))); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); } @@ -2789,7 +2918,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, DynamicRules) { // Navigate to a page on "example.com". It should be redirected to // |dynamic_redirect_url|. GURL example_url = embedded_test_server()->GetURL("example.com", kUrlPath); - ui_test_utils::NavigateToURL(browser(), example_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), example_url)); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_EQ(dynamic_redirect_url, web_contents()->GetLastCommittedURL()); @@ -2895,7 +3024,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, Redirect) { for (const auto& test_case : cases) { SCOPED_TRACE("Testing " + test_case.url.spec()); - ui_test_utils::NavigateToURL(browser(), test_case.url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), test_case.url)); EXPECT_EQ(test_case.expected_url, web_contents()->GetLastCommittedURL()); } } @@ -2997,7 +3126,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, {"abcd.com", "3", false}, }; - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); // Verify that the badge text is empty when navigation finishes because no @@ -3115,7 +3244,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, WebRequestEvents) { // Wait for the web request listeners to be installed before navigating. ASSERT_TRUE(installed_listener.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_FALSE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_TRUE(pass_listener.WaitUntilSatisfied()); @@ -3164,7 +3293,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, WebRequestPriority) { // Wait for the web request listeners to be installed before navigating. ASSERT_TRUE(installed_listener.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Ensure the response from the web request listener was ignored and the // request was redirected. @@ -3182,7 +3311,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, TabIdFiltering) { constexpr char kUrlPath[] = "/pages_with_script/index.html"; GURL url = embedded_test_server()->GetURL("example.com", kUrlPath); // Open three tabs to `url`. - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); ui_test_utils::NavigateToURLWithDisposition( @@ -3268,7 +3397,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, TabIdFiltering) { ExtensionTabUtil::GetTabId(web_contents())); // Verify tab ID filtering works on a main-frame request. - ui_test_utils::NavigateToURL(browser(), new_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), new_url)); EXPECT_EQ(embedded_test_server()->GetURL(cases[i].expected_host, kUrlPath), web_contents()->GetLastCommittedURL()); @@ -3280,9 +3409,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, TabIdFiltering) { // Test matching against requests which don't originate from a tab (tab ID of // -1) by performing a fetch from a shared worker. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), - embedded_test_server()->GetURL(kHost, "/fetch_from_shared_worker.html")); + embedded_test_server()->GetURL(kHost, "/fetch_from_shared_worker.html"))); // This navigation should have matched the third rule. ASSERT_EQ(embedded_test_server()->GetURL("rule3.com", @@ -3354,7 +3483,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // initially. const GURL page_url = embedded_test_server()->GetURL("abc.com", "/page_with_two_frames.html"); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); TabHelper* tab_helper = TabHelper::FromWebContents(web_contents()); ActiveTabPermissionGranter* active_tab_granter = @@ -3486,7 +3615,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, const GURL page_url = embedded_test_server()->GetURL( "abc.com", "/pages_with_script/index.html"); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); int first_browser_tab_id = ExtensionTabUtil::GetTabId(web_contents()); EXPECT_EQ("", extension_action->GetDisplayBadgeText(first_browser_tab_id)); @@ -3494,7 +3623,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // Now create a new browser with the same profile as |browser()| and navigate // to |page_url|. Browser* second_browser = CreateBrowser(profile()); - ui_test_utils::NavigateToURL(second_browser, page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(second_browser, page_url)); content::WebContents* second_browser_contents = second_browser->tab_strip_model()->GetActiveWebContents(); @@ -3545,7 +3674,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, true); Browser* incognito_browser = CreateIncognitoBrowser(); - ui_test_utils::NavigateToURL(incognito_browser, GURL("http://abc.com")); + ASSERT_TRUE( + ui_test_utils::NavigateToURL(incognito_browser, GURL("http://abc.com"))); content::WebContents* incognito_contents = incognito_browser->tab_strip_model()->GetActiveWebContents(); @@ -3657,7 +3787,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, GURL url = get_url_for_host(test_case.frame_hostname); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(test_case.expected_badge_text, action->GetDisplayBadgeText(first_tab_id)); } @@ -3796,7 +3926,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, {get_no_headers_url("ghi.com"), false, "6", "4"}, }; - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); @@ -3847,7 +3977,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // Navigate to a page with two frames, the same-origin one should be blocked. const GURL page_url = embedded_test_server()->GetURL("abc.com", "/page_with_two_frames.html"); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); int tab_id = ExtensionTabUtil::GetTabId(web_contents()); @@ -3999,7 +4129,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Unpacked, LoadExtensionWithRules({abc_set_cookie_rule, abc_referer_rule}, "extension_1", {URLPattern::kAllUrlsPattern})); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); // Start the onRuleMatchedDebug observer. @@ -4084,7 +4214,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, LoadExtensionWithRules({def_rule}, "extension_2", {})); auto extension_2_id = last_loaded_extension_id(); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); const int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); @@ -4103,7 +4233,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ASSERT_EQ(2, browser()->tab_strip_model()->count()); ASSERT_TRUE(browser()->tab_strip_model()->IsTabSelected(1)); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); const int second_tab_id = ExtensionTabUtil::GetTabId(web_contents()); @@ -4207,7 +4337,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}, "extension_1", {})); // Navigate to abc.com. - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); std::string actual_rule_and_tab_ids = GetRuleAndTabIdsMatched(last_loaded_extension_id(), absl::nullopt); @@ -4220,7 +4350,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, EXPECT_EQ(expected_rule_and_tab_ids, actual_rule_and_tab_ids); // Navigate to abc.com again. - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); actual_rule_and_tab_ids = GetRuleAndTabIdsMatched(last_loaded_extension_id(), absl::nullopt); @@ -4235,9 +4365,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, EXPECT_EQ(expected_rule_and_tab_ids, actual_rule_and_tab_ids); // Navigate to nomatch,com. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( - "nomatch.com", "/pages_with_script/index.html")); + "nomatch.com", "/pages_with_script/index.html"))); // No rules should be matched for the navigation request to nomatch.com and // all rules previously attributed to |first_tab_id| should now be attributed @@ -4283,7 +4413,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}, "extension_1", {})); const ExtensionId& extension_id = last_loaded_extension_id(); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); // Using subframes here to make requests without triggering main-frame // navigations. This request will match with the block rule for example.com at @@ -4312,16 +4442,16 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // Advance the clock to capture a timestamp after when the first request was // made. - clock_.Advance(base::TimeDelta::FromMilliseconds(100)); + clock_.Advance(base::Milliseconds(100)); base::Time timestamp_1 = clock_.Now(); - clock_.Advance(base::TimeDelta::FromMilliseconds(100)); + clock_.Advance(base::Milliseconds(100)); // Navigate to example.com again. This should cause |rule| to be matched. NavigateFrame(kFrameName1, sub_frame_url); // Advance the clock to capture a timestamp after when the second request was // made. - clock_.Advance(base::TimeDelta::FromMilliseconds(100)); + clock_.Advance(base::Milliseconds(100)); base::Time timestamp_2 = clock_.Now(); int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); @@ -4368,7 +4498,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, const ExtensionId& extension_id = last_loaded_extension_id(); // Navigate to |page_url| which will cause |rule| to be matched. - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); @@ -4486,6 +4616,22 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, const ExtensionId extension_id = last_loaded_extension_id(); const Extension* extension = last_loaded_extension(); + ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); + ASSERT_TRUE(prefs); + + // Since this is a packed extension, rulesets are only indexed when they are + // first enabled. The second ruleset has not been enabled yet, so it shouldn't + // have been indexed yet either. + int checksum = -1; + EXPECT_TRUE(prefs->GetDNRStaticRulesetChecksum( + extension_id, kMinValidStaticRulesetID, &checksum)); + EXPECT_FALSE(prefs->GetDNRStaticRulesetChecksum( + extension_id, RulesetID(kMinValidStaticRulesetID.value() + 1), + &checksum)); + EXPECT_TRUE(prefs->GetDNRStaticRulesetChecksum( + extension_id, RulesetID(kMinValidStaticRulesetID.value() + 2), + &checksum)); + // Also add a dynamic rule. ASSERT_NO_FATAL_FAILURE( AddDynamicRules(extension_id, {CreateMainFrameBlockRule("dynamic")})); @@ -4500,10 +4646,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, EXPECT_THAT(GetPublicRulesetIDs(*extension, *composite_matcher), UnorderedElementsAre("id2", "id3", dnr_api::DYNAMIC_RULESET_ID)); - // Also sanity check the extension prefs entry for the rulesets. - ExtensionPrefs* prefs = ExtensionPrefs::Get(profile()); - ASSERT_TRUE(prefs); - int checksum = -1; + // Also sanity check the extension prefs entry for the rulesets. Note that + // the second static ruleset now should have been indexed since it has now + // been enabled. int dynamic_checksum_1 = -1; EXPECT_TRUE(prefs->GetDNRStaticRulesetChecksum( extension_id, kMinValidStaticRulesetID, &checksum)); @@ -4547,7 +4692,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, int dynamic_checksum_2; EXPECT_TRUE(prefs->GetDNRStaticRulesetChecksum( extension_id, kMinValidStaticRulesetID, &checksum)); - EXPECT_TRUE(prefs->GetDNRStaticRulesetChecksum( + EXPECT_FALSE(prefs->GetDNRStaticRulesetChecksum( extension_id, RulesetID(kMinValidStaticRulesetID.value() + 1), &checksum)); EXPECT_FALSE(prefs->GetDNRStaticRulesetChecksum( @@ -4662,7 +4807,7 @@ class DeclarativeNetRequestAllowAllRequestsBrowserTest GURL page_url = embedded_test_server()->GetURL( "example.com", post_navigation ? "/post_to_page_with_two_frames.html" : "/page_with_two_frames.html"); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); std::map<GURL, net::test_server::HttpRequest> requests_seen = GetAndResetRequestsToServer(); @@ -4893,7 +5038,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestIdentifiabilityTest, GURL url = embedded_test_server()->GetURL("google.com", "/pages_with_script/page2.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_FALSE(WasFrameWithScriptLoaded(GetMainFrame())); EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType()); @@ -4926,6 +5071,11 @@ class DeclarativeNetRequestHostPermissionsBrowserTest public: DeclarativeNetRequestHostPermissionsBrowserTest() {} + DeclarativeNetRequestHostPermissionsBrowserTest( + const DeclarativeNetRequestHostPermissionsBrowserTest&) = delete; + DeclarativeNetRequestHostPermissionsBrowserTest& operator=( + const DeclarativeNetRequestHostPermissionsBrowserTest&) = delete; + protected: struct FrameRedirectResult { std::string child_frame_name; @@ -4951,7 +5101,7 @@ class DeclarativeNetRequestHostPermissionsBrowserTest GURL url = embedded_test_server()->GetURL("example.com", "/page_with_four_frames.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); for (const auto& frame_result : expected_results) { @@ -4969,9 +5119,6 @@ class DeclarativeNetRequestHostPermissionsBrowserTest std::string GetMatchPatternForDomain(const std::string& domain) const { return "*://*." + domain + ".com/*"; } - - private: - DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestHostPermissionsBrowserTest); }; IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest, @@ -5016,6 +5163,11 @@ class DeclarativeNetRequestResourceTypeBrowserTest public: DeclarativeNetRequestResourceTypeBrowserTest() {} + DeclarativeNetRequestResourceTypeBrowserTest( + const DeclarativeNetRequestResourceTypeBrowserTest&) = delete; + DeclarativeNetRequestResourceTypeBrowserTest& operator=( + const DeclarativeNetRequestResourceTypeBrowserTest&) = delete; + protected: // TODO(crbug.com/696822): Add tests for "object", "ping", "other", "font", // "csp_report". @@ -5058,7 +5210,7 @@ class DeclarativeNetRequestResourceTypeBrowserTest "/subresources.html"); SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); content::RenderFrameHost* frame = GetMainFrame(); @@ -5143,9 +5295,6 @@ class DeclarativeNetRequestResourceTypeBrowserTest } LoadExtensionWithRules(rules); } - - private: - DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestResourceTypeBrowserTest); }; // These are split into two tests to prevent a timeout. See crbug.com/787957. @@ -5207,6 +5356,31 @@ class DeclarativeNetRequestSubresourceWebBundlesBrowserTest return success; } + bool TryLoadBundle(const std::string& href, const std::string& resources) { + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + bool success = false; + std::string script = base::StringPrintf(R"( + (() => { + const link = document.createElement('link'); + link.rel = 'webbundle'; + link.addEventListener('load', () => { + window.domAutomationController.send(true); + }); + link.addEventListener('error', () => { + window.domAutomationController.send(false); + }); + link.href = '%s'; + link.resources = '%s'; + document.body.appendChild(link); + })(); + )", + href.c_str(), resources.c_str()); + EXPECT_TRUE(ExecuteScriptAndExtractBool(web_contents->GetMainFrame(), + script, &success)); + return success; + } + // Registers a request handler for static content. void RegisterRequestHandler(const std::string& relative_url, const std::string& content_type, @@ -5317,7 +5491,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest, GURL page_url = embedded_test_server()->GetURL("/test.html"); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); std::u16string expected_title = u"script loaded"; @@ -5390,7 +5564,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest, GURL page_url = embedded_test_server()->GetURL("/test.html"); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); std::u16string expected_title = u"script loaded"; @@ -5512,7 +5686,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest, GURL page_url = embedded_test_server()->GetURL("/test.html"); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); { std::u16string expected_title = u"redirected"; @@ -5534,6 +5708,51 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest, EXPECT_FALSE(TryLoadScript("redirect_to_server.js")); } +// Ensure that request to Subresource WebBundle fails if it is redirected by +// DeclarativeNetRequest API. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestSubresourceWebBundlesBrowserTest, + WebBundleRequestRedirected) { + std::string web_bundle; + RegisterWebBundleRequestHandler("/redirect.wbn", &web_bundle); + RegisterWebBundleRequestHandler("/redirected.wbn", &web_bundle); + ASSERT_TRUE(embedded_test_server()->Start()); + + // Create a web bundle. + std::string js_url_str = embedded_test_server()->GetURL("/script.js").spec(); + web_package::test::WebBundleBuilder builder(js_url_str, ""); + builder.AddExchange( + js_url_str, + {{":status", "200"}, {"content-type", "application/javascript"}}, + "document.title = 'script loaded';"); + std::vector<uint8_t> bundle = builder.CreateBundle(); + web_bundle = std::string(bundle.begin(), bundle.end()); + + std::vector<TestRule> rules; + TestRule rule = CreateGenericRule(); + rule.id = kMinValidID; + rule.priority = 1; + rule.condition->url_filter = "redirect.wbn|"; + // TODO(crbug.com/1246214): Introduce a new resource type for web bundles. + rule.condition->resource_types = std::vector<std::string>({"other"}); + rule.action->type = "redirect"; + rule.action->redirect.emplace(); + rule.action->redirect->url = + embedded_test_server()->GetURL("/redirected.wbn").spec(); + rules.push_back(rule); + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules, "test_extension", {URLPattern::kAllUrlsPattern})); + + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/empty.html"))); + + // In the current implementation, extensions can't redirect requests to + // Subresource WebBundles. + EXPECT_FALSE(TryLoadBundle("redirect.wbn", js_url_str)); + + // Without redirection, bundle load should succeed. + EXPECT_TRUE(TryLoadBundle("redirected.wbn", js_url_str)); +} + class DeclarativeNetRequestGlobalRulesBrowserTest : public DeclarativeNetRequestBrowserTest { public: @@ -5909,7 +6128,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, )"; GURL url = embedded_test_server()->GetURL("abc.com", "/empty.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); content::RenderFrameHost* main_frame = GetMainFrame(); for (const auto& test_case : test_cases) { @@ -5926,9 +6145,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, } // Tests that the "requestMethods" and "excludedRequestMethods" properties of a -// rule condition are considered properly for non-HTTP(s) requests. +// rule condition are considered properly for WebSocket requests. IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, - BlockRequests_NonHTTPMethods) { + BlockRequests_WebSocket) { // Load an extension with some DNR rules that have different request method // conditions. std::vector<TestRule> rules; @@ -6011,6 +6230,83 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, actual_blocked); } +class DeclarativeNetRequestWebTransportTest + : public DeclarativeNetRequestBrowserTest { + public: + DeclarativeNetRequestWebTransportTest() { webtransport_server_.Start(); } + + void SetUpCommandLine(base::CommandLine* command_line) override { + DeclarativeNetRequestBrowserTest::SetUpCommandLine(command_line); + webtransport_server_.SetUpCommandLine(command_line); + } + + protected: + content::WebTransportSimpleTestServer webtransport_server_; +}; + +// Tests that the "requestMethods" and "excludedRequestMethods" properties of a +// rule condition are considered properly for WebTransport requests. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestWebTransportTest, BlockRequests) { + ASSERT_TRUE(https_server()->Start()); + + // Load an extension with some rules that have different request method + // conditions. + std::vector<TestRule> rules; + + // We need to prefix "echo" so that the server accepts it. + TestRule rule1 = CreateGenericRule(1); + rule1.condition->url_filter = "echo1_default"; + rules.push_back(rule1); + + TestRule rule2 = CreateGenericRule(2); + rule2.condition->url_filter = "echo2_include"; + rule2.condition->request_methods = {"connect"}; + rules.push_back(rule2); + + TestRule rule4 = CreateGenericRule(3); + rule4.condition->url_filter = "echo3_exclude"; + rule4.condition->excluded_request_methods = {"connect"}; + rules.push_back(rule4); + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules)); + + ASSERT_TRUE( + ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/echo"))); + + const char kOpenWebTransportScript[] = R"(( + async () => + { + const testCases = ["echo1_default", "echo2_include", "echo3_exclude" ]; + + let blockedTestCases = []; + + await Promise.allSettled( + testCases.map(testCase => + new Promise(async (resolve) => + { + try { + const transport = new WebTransport( + `https://localhost:%d/${testCase}`); + await transport.ready; + } catch (e) { + blockedTestCases.push(testCase); + } + resolve(); + }) + ) + ); + return blockedTestCases.sort().join(); + } + )())"; + + content::RenderFrameHost* main_frame = GetMainFrame(); + EXPECT_EQ("echo1_default,echo2_include", + content::EvalJs(main_frame, + base::StringPrintf( + kOpenWebTransportScript, + webtransport_server_.server_address().port()))); +} + // Tests that FLEDGE requests can be blocked by the declarativeNetRequest API, // and that if they try to redirect requests, the request is blocked, instead of // being redirected. @@ -6018,25 +6314,17 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, FledgeAuctionScripts) { const char kAddedHeaderName[] = "Header-Name"; const char kAddedHeaderValue[] = "Header-Value"; - net::EmbeddedTestServer https_server( - net::test_server::EmbeddedTestServer::TYPE_HTTPS); - https_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK); - https_server.AddDefaultHandlers(); - https_server.ServeFilesFromDirectory(GetHttpServerPath()); - https_server.RegisterRequestMonitor( - base::BindRepeating(&DeclarativeNetRequestBrowserTest::MonitorRequest, - base::Unretained(this))); - ASSERT_TRUE(https_server.Start()); + ASSERT_TRUE(https_server()->Start()); ASSERT_TRUE( - ui_test_utils::NavigateToURL(browser(), https_server.GetURL("/echo"))); + ui_test_utils::NavigateToURL(browser(), https_server()->GetURL("/echo"))); GURL bidding_logic_url = - https_server.GetURL("/interest_group/bidding_logic.js"); + https_server()->GetURL("/interest_group/bidding_logic.js"); GURL decision_logic_url = - https_server.GetURL("/interest_group/decision_logic.js"); - GURL bidder_report_url = https_server.GetURL("/echo?bidder_report"); - GURL decision_report_url = https_server.GetURL("/echo?decision_report"); + https_server()->GetURL("/interest_group/decision_logic.js"); + GURL bidder_report_url = https_server()->GetURL("/echo?bidder_report"); + GURL decision_report_url = https_server()->GetURL("/echo?decision_report"); // Add an interest group. EXPECT_EQ("done", content::EvalJs( @@ -6088,13 +6376,10 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, FledgeAuctionScripts) { url::Origin::Create(decision_logic_url).Serialize(), decision_logic_url.spec()); - // Unfortunately, there's a race between adding an interest group and running - // an auction, with no API in Javascript currently available to wait until an - // interest group has been added, so can only run the auction until there's a - // result, which means the interest group has been added. - while ("https://example.com/render" != - content::EvalJs(web_contents(), run_auction_command)) { - } + // The auction should return a unique URN URL. + GURL ad_url( + content::EvalJs(web_contents(), run_auction_command).ExtractString()); + EXPECT_TRUE(ad_url.SchemeIs(url::kUrnScheme)); // Wait to see both the report request of both worklets. WaitForRequest(bidder_report_url); @@ -6122,9 +6407,11 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, FledgeAuctionScripts) { ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( {block_report_rule}, "test_extension2", {URLPattern::kAllUrlsPattern})); - // Running the auction again should result in the same URL winning. - EXPECT_EQ("https://example.com/render", - content::EvalJs(web_contents(), run_auction_command)); + // Run the auction again. + ad_url = GURL( + content::EvalJs(web_contents(), run_auction_command).ExtractString()); + EXPECT_TRUE(ad_url.SchemeIs(url::kUrnScheme)); + // Wait for the decision script's report URL to be requested. WaitForRequest(decision_report_url); // The bidder script should be blocked. Unfortunately, there's no way to wait @@ -6145,7 +6432,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, FledgeAuctionScripts) { redirect_bidding_logic_rule.action->type = "redirect"; redirect_bidding_logic_rule.action->redirect.emplace(); redirect_bidding_logic_rule.action->redirect->url = - https_server.GetURL("/interest_group/bidding_logic2.js").spec(); + https_server()->GetURL("/interest_group/bidding_logic2.js").spec(); ASSERT_NO_FATAL_FAILURE( LoadExtensionWithRules({redirect_bidding_logic_rule}, "test_extension3", @@ -6325,6 +6612,11 @@ INSTANTIATE_TEST_SUITE_P(All, ExtensionLoadType::UNPACKED)); INSTANTIATE_TEST_SUITE_P(All, + DeclarativeNetRequestWebTransportTest, + ::testing::Values(ExtensionLoadType::PACKED, + ExtensionLoadType::UNPACKED)); + +INSTANTIATE_TEST_SUITE_P(All, DeclarativeNetRequestBackForwardCacheBrowserTest, ::testing::Values(ExtensionLoadType::PACKED, ExtensionLoadType::UNPACKED)); diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc index 92287fc0955..42392bc40b6 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/declarative_net_request_unittest.cc @@ -33,6 +33,7 @@ #include "extensions/browser/api/declarative_net_request/composite_matcher.h" #include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/browser/api/declarative_net_request/declarative_net_request_api.h" +#include "extensions/browser/api/declarative_net_request/file_backed_ruleset_source.h" #include "extensions/browser/api/declarative_net_request/parse_info.h" #include "extensions/browser/api/declarative_net_request/rules_count_pair.h" #include "extensions/browser/api/declarative_net_request/rules_monitor_service.h" @@ -79,10 +80,6 @@ using ::testing::Property; using ::testing::UnorderedElementsAre; using ::testing::UnorderedElementsAreArray; -std::string GetParseError(ParseResult result, int rule_id) { - return ParseInfo(result, rule_id).error(); -} - std::string GetErrorWithFilename( const std::string& error, const std::string& filename = kJSONRulesFilename) { @@ -150,8 +147,13 @@ class DeclarativeNetRequestUnittest : public DNRTestBase { extension_ = loader_->LoadExtension(extension_dir_); ASSERT_TRUE(extension_.get()); - EXPECT_TRUE( - AreAllIndexedStaticRulesetsValid(*extension_, browser_context())); + auto ruleset_filter = FileBackedRulesetSource::RulesetFilter::kIncludeAll; + if (GetParam() == ExtensionLoadType::PACKED) { + ruleset_filter = + FileBackedRulesetSource::RulesetFilter::kIncludeManifestEnabled; + } + EXPECT_TRUE(AreAllIndexedStaticRulesetsValid(*extension_, browser_context(), + ruleset_filter)); // Ensure no load errors were reported. EXPECT_TRUE(error_reporter()->GetErrors()->empty()); @@ -162,8 +164,6 @@ class DeclarativeNetRequestUnittest : public DNRTestBase { tester.ExpectTotalCount(kIndexAndPersistRulesTimeHistogram, expected_samples); - tester.ExpectUniqueSample(kManifestRulesCountHistogram, - expected_rules_count, expected_samples); tester.ExpectUniqueSample(kManifestEnabledRulesCountHistogram, expected_enabled_rules_count, expected_samples); } @@ -196,7 +196,41 @@ class DeclarativeNetRequestUnittest : public DNRTestBase { << "expected: " << error_with_filename << " actual: " << errors->at(0); tester.ExpectTotalCount(kIndexAndPersistRulesTimeHistogram, 0u); - tester.ExpectTotalCount(kManifestRulesCountHistogram, 0u); + tester.ExpectTotalCount(kManifestEnabledRulesCountHistogram, 0u); + } + + void LoadAndExpectParseFailure(ParseResult parse_result, + int rule_id, + const std::string& filename) { + std::string expected_error = GetParseError(parse_result, rule_id); + + if (GetParam() == ExtensionLoadType::UNPACKED) { + // All static rulesets are indexed (and therefore all static rules are + // parsed) at installation time for unpacked extensions, with invalid + // rules resulting in a hard installation error where possible. + LoadAndExpectError(expected_error, filename); + return; + } + + // Static ruleset indexing for packed extensions is deferred until the + // ruleset is enabled. Invalid static rules are ignored with a warning + // raised. + + base::HistogramTester tester; + WriteExtensionData(); + + loader_->set_should_fail(false); + + // Clear all load errors before loading the extension. + error_reporter()->ClearErrors(); + + extension_ = loader_->LoadExtension(extension_dir_); + + // Neither warnings nor errors are raised for problematic static rules for + // packed extensions. + EXPECT_TRUE(extension_.get()); + const std::vector<std::u16string>* errors = error_reporter()->GetErrors(); + ASSERT_TRUE(errors->empty()); } enum class RulesetScope { kDynamic, kSession }; @@ -441,6 +475,11 @@ class SingleRulesetTest : public DeclarativeNetRequestUnittest { kJSONRulesFilename); } + void LoadAndExpectParseFailure(ParseResult parse_result, int rule_id) { + DeclarativeNetRequestUnittest::LoadAndExpectParseFailure( + parse_result, rule_id, kJSONRulesFilename); + } + // |expected_rules_count| refers to the count of indexed rules. When // |expected_rules_count| is not set, it is inferred from the added rules. void LoadAndExpectSuccess( @@ -500,8 +539,8 @@ TEST_P(SingleRulesetTest, DuplicateResourceTypes) { std::vector<std::string>({"image", "stylesheet"}); rule.condition->excluded_resource_types = std::vector<std::string>({"image"}); AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_RESOURCE_TYPE_DUPLICATED, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_RESOURCE_TYPE_DUPLICATED, + *rule.id); } TEST_P(SingleRulesetTest, EmptyRedirectRuleUrl) { @@ -514,16 +553,14 @@ TEST_P(SingleRulesetTest, EmptyRedirectRuleUrl) { rule.priority = kMinValidPriority; AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_INVALID_REDIRECT, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_INVALID_REDIRECT, *rule.id); } TEST_P(SingleRulesetTest, InvalidRuleID) { TestRule rule = CreateGenericRule(); rule.id = kMinValidID - 1; AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_INVALID_RULE_ID, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_INVALID_RULE_ID, *rule.id); } TEST_P(SingleRulesetTest, InvalidRedirectRulePriority) { @@ -533,8 +570,7 @@ TEST_P(SingleRulesetTest, InvalidRedirectRulePriority) { rule.action->redirect->url = std::string("https://google.com"); rule.priority = kMinValidPriority - 1; AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_INVALID_RULE_PRIORITY, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_INVALID_RULE_PRIORITY, *rule.id); } TEST_P(SingleRulesetTest, NoApplicableResourceTypes) { @@ -542,34 +578,32 @@ TEST_P(SingleRulesetTest, NoApplicableResourceTypes) { rule.condition->excluded_resource_types = std::vector<std::string>( {"main_frame", "sub_frame", "stylesheet", "script", "image", "font", "object", "xmlhttprequest", "ping", "csp_report", "media", "websocket", - "other"}); + "webtransport", "other"}); AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_NO_APPLICABLE_RESOURCE_TYPES, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_NO_APPLICABLE_RESOURCE_TYPES, + *rule.id); } TEST_P(SingleRulesetTest, EmptyDomainsList) { TestRule rule = CreateGenericRule(); rule.condition->domains = std::vector<std::string>(); AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_EMPTY_DOMAINS_LIST, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_EMPTY_DOMAINS_LIST, *rule.id); } TEST_P(SingleRulesetTest, EmptyResourceTypeList) { TestRule rule = CreateGenericRule(); rule.condition->resource_types = std::vector<std::string>(); AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_EMPTY_RESOURCE_TYPES_LIST, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_EMPTY_RESOURCE_TYPES_LIST, + *rule.id); } TEST_P(SingleRulesetTest, EmptyURLFilter) { TestRule rule = CreateGenericRule(); rule.condition->url_filter = std::string(); AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_EMPTY_URL_FILTER, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_EMPTY_URL_FILTER, *rule.id); } TEST_P(SingleRulesetTest, InvalidRedirectURL) { @@ -579,8 +613,7 @@ TEST_P(SingleRulesetTest, InvalidRedirectURL) { rule.action->redirect->url = std::string("google"); rule.priority = kMinValidPriority; AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_INVALID_REDIRECT_URL, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_INVALID_REDIRECT_URL, *rule.id); } TEST_P(SingleRulesetTest, ListNotPassed) { @@ -592,7 +625,7 @@ TEST_P(SingleRulesetTest, DuplicateIDS) { TestRule rule = CreateGenericRule(); AddRule(rule); AddRule(rule); - LoadAndExpectError(GetParseError(ParseResult::ERROR_DUPLICATE_IDS, *rule.id)); + LoadAndExpectParseFailure(ParseResult::ERROR_DUPLICATE_IDS, *rule.id); } // Ensure that we limit the number of parse failure warnings shown. @@ -811,8 +844,8 @@ TEST_P(SingleRulesetTest, WarningAndError) { rule.id = kMinValidID + 1; AddRule(rule); - LoadAndExpectError( - GetParseError(ParseResult::ERROR_INVALID_REGEX_FILTER, kMinValidID + 1)); + LoadAndExpectParseFailure(ParseResult::ERROR_INVALID_REGEX_FILTER, + kMinValidID + 1); } // Ensure that we get an install warning on exceeding the regex rule count @@ -1054,7 +1087,8 @@ TEST_P(SingleRulesetTest, RuleCountLimitMatched) { ruleset_waiter.WaitForExtensionsWithRulesetsCount(1); std::vector<FileBackedRulesetSource> static_sources = - FileBackedRulesetSource::CreateStatic(*extension()); + FileBackedRulesetSource::CreateStatic( + *extension(), FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(1u, static_sources.size()); EXPECT_TRUE(base::PathExists(static_sources[0].indexed_path())); @@ -1121,7 +1155,8 @@ TEST_P(SingleRulesetTest, RuleCountLimitExceeded) { 0, 0, false /* expect_rulesets_indexed */); std::vector<FileBackedRulesetSource> static_sources = - FileBackedRulesetSource::CreateStatic(*extension()); + FileBackedRulesetSource::CreateStatic( + *extension(), FileBackedRulesetSource::RulesetFilter::kIncludeAll); // Since the ruleset was ignored and not indexed, it should not be persisted // to a file. @@ -1632,21 +1667,27 @@ TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_RegexRuleCountExceeded) { TEST_P(MultipleRulesetsTest, UpdateEnabledRulesets_InternalError) { AddRuleset(CreateRuleset(kId1, 10, 10, true)); - AddRuleset(CreateRuleset(kId2, 10, 10, false)); + AddRuleset(CreateRuleset(kId2, 10, 10, true)); RulesetManagerObserver ruleset_waiter(manager()); LoadAndExpectSuccess(); ruleset_waiter.WaitForExtensionsWithRulesetsCount(1); std::vector<FileBackedRulesetSource> static_sources = - FileBackedRulesetSource::CreateStatic(*extension()); + FileBackedRulesetSource::CreateStatic( + *extension(), FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(2u, static_sources.size()); constexpr char kReindexHistogram[] = "Extensions.DeclarativeNetRequest.RulesetReindexSuccessful"; { - // First delete the indexed ruleset file for the second ruleset. Enabling it - // should cause re-indexing and succeed in enabling the ruleset. + // First disable the second ruleset and then delete its indexed ruleset + // file. + RunUpdateEnabledRulesetsFunction(*extension(), {kId2}, {}, absl::nullopt); + ASSERT_TRUE(base::DeleteFile(static_sources[1].indexed_path())); + + // Enabling it again should cause re-indexing and succeed in enabling the + // ruleset. base::HistogramTester tester; ASSERT_TRUE(base::DeleteFile(static_sources[1].indexed_path())); @@ -1767,7 +1808,8 @@ TEST_P(MultipleRulesetsTest, StaticRuleCountExceeded) { Pointee(Property(&RulesetMatcher::GetRulesCount, 250)))); std::vector<FileBackedRulesetSource> static_sources = - FileBackedRulesetSource::CreateStatic(*extension()); + FileBackedRulesetSource::CreateStatic( + *extension(), FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(2u, static_sources.size()); if (GetParam() != ExtensionLoadType::PACKED) { diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/dnr_test_base.h b/chromium/chrome/browser/extensions/api/declarative_net_request/dnr_test_base.h index 78e4a891a96..39af0b7c2b0 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/dnr_test_base.h +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/dnr_test_base.h @@ -23,15 +23,15 @@ class DNRTestBase : public ExtensionServiceTestBase, public: DNRTestBase(); + DNRTestBase(const DNRTestBase&) = delete; + DNRTestBase& operator=(const DNRTestBase&) = delete; + // ExtensionServiceTestBase override. void SetUp() override; protected: // Returns an extension loader for the current ExtensionLoadType. std::unique_ptr<ChromeTestExtensionLoader> CreateExtensionLoader(); - - private: - DISALLOW_COPY_AND_ASSIGN(DNRTestBase); }; } // namespace declarative_net_request diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc index 8579417bfd2..440b6a48920 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_manager_unittest.cc @@ -47,6 +47,9 @@ class RulesetManagerTest : public DNRTestBase { public: RulesetManagerTest() {} + RulesetManagerTest(const RulesetManagerTest&) = delete; + RulesetManagerTest& operator=(const RulesetManagerTest&) = delete; + void SetUp() override { DNRTestBase::SetUp(); manager_ = std::make_unique<RulesetManager>(browser_context()); @@ -84,7 +87,9 @@ class RulesetManagerTest : public DNRTestBase { ->AddEnabled(last_loaded_extension_); std::vector<FileBackedRulesetSource> sources = - FileBackedRulesetSource::CreateStatic(*last_loaded_extension_); + FileBackedRulesetSource::CreateStatic( + *last_loaded_extension_, + FileBackedRulesetSource::RulesetFilter::kIncludeAll); ASSERT_EQ(1u, sources.size()); int expected_checksum; @@ -98,7 +103,8 @@ class RulesetManagerTest : public DNRTestBase { LoadRulesetResult::kSuccess, sources[0].CreateVerifiedMatcher(expected_checksum, &matchers[0])); - *matcher = std::make_unique<CompositeMatcher>(std::move(matchers)); + *matcher = std::make_unique<CompositeMatcher>( + std::move(matchers), HostPermissionsAlwaysRequired::kFalse); } void SetIncognitoEnabled(const Extension* extension, bool incognito_enabled) { @@ -148,8 +154,6 @@ class RulesetManagerTest : public DNRTestBase { private: scoped_refptr<const Extension> last_loaded_extension_; std::unique_ptr<RulesetManager> manager_; - - DISALLOW_COPY_AND_ASSIGN(RulesetManagerTest); }; // Tests that the RulesetManager handles multiple rulesets correctly. @@ -528,6 +532,68 @@ TEST_P(RulesetManagerTest, ModifyHeaders) { ::testing::Eq(::testing::ByRef(expected_action_2)))); } +// Ensures that an allow rule doesn't win over a higher priority modifyHeaders +// rule. Regression test for crbug.com/1244249. +TEST_P(RulesetManagerTest, ModifyHeadersWithAllowRules) { + int rule_id = kMinValidID; + + TestRule rule1 = CreateGenericRule(); + rule1.condition->url_filter = std::string("example.com"); + rule1.action->type = std::string("modifyHeaders"); + rule1.action->request_headers = + std::vector<TestHeaderInfo>({TestHeaderInfo("header", "set", "value")}); + rule1.priority = 5; + rule1.id = rule_id++; + + TestRule rule2 = CreateGenericRule(); + rule2.condition->url_filter = std::string("example.com"); + rule2.action->type = std::string("allow"); + rule2.priority = 3; + rule2.id = rule_id++; + + TestRule rule3 = CreateGenericRule(); + rule3.condition->url_filter = std::string("abc.example.com"); + rule3.action->type = std::string("allow"); + rule3.priority = 8; + rule3.id = rule_id++; + + std::unique_ptr<CompositeMatcher> matcher; + ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules({rule1, rule2, rule3}, + "test extension", &matcher, + {URLPattern::kAllUrlsPattern})); + const Extension* extension = last_loaded_extension(); + manager()->AddRuleset(extension->id(), std::move(matcher)); + + { + WebRequestInfo request(GetRequestParamsForURL("http://example.com")); + const std::vector<RequestAction>& actions = + manager()->EvaluateRequest(request, false /*is_incognito_context*/); + + // `rule1` and `rule2` match. `rule1` gets precedence because of priority. + RequestAction expected_action = CreateRequestActionForTesting( + RequestActionType::MODIFY_HEADERS, *rule1.id, *rule1.priority, + kMinValidStaticRulesetID, extension->id()); + expected_action.request_headers_to_modify = {RequestAction::HeaderInfo( + "header", dnr_api::HEADER_OPERATION_SET, "value")}; + EXPECT_THAT(actions, ::testing::ElementsAre( + ::testing::Eq(::testing::ByRef(expected_action)))); + } + + { + WebRequestInfo request(GetRequestParamsForURL("http://abc.example.com")); + const std::vector<RequestAction>& actions = + manager()->EvaluateRequest(request, false /*is_incognito_context*/); + + // `rule1`, `rule2` and `rule3` match. `rule3` gets precedence because of + // priority. + RequestAction expected_action = CreateRequestActionForTesting( + RequestActionType::ALLOW, *rule3.id, *rule3.priority, + kMinValidStaticRulesetID, extension->id()); + EXPECT_THAT(actions, ::testing::ElementsAre( + ::testing::Eq(::testing::ByRef(expected_action)))); + } +} + // Test that an extension's modify header rules are applied on a request only if // it has host permissions for the request. TEST_P(RulesetManagerTest, ModifyHeaders_HostPermissions) { diff --git a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc index 979e270ce2f..461c9815c64 100644 --- a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_rules_registry_unittest.cc @@ -110,14 +110,14 @@ class WebRequestRulesRegistryTest : public testing::Test { // https://www.example.com and cancels it api::events::Rule CreateRule1() { auto scheme_http = std::make_unique<base::ListValue>(); - scheme_http->AppendString("http"); + scheme_http->Append("http"); auto http_condition_dict = std::make_unique<base::DictionaryValue>(); http_condition_dict->SetString(keys2::kHostSuffixKey, "example.com"); base::DictionaryValue http_condition_url_filter; http_condition_url_filter.SetString(keys::kInstanceTypeKey, keys::kRequestMatcherType); - scheme_http->AppendString("https"); + scheme_http->Append("https"); auto https_condition_dict = std::make_unique<base::DictionaryValue>(); https_condition_dict->Set(keys2::kSchemesKey, std::make_unique<base::ListValue>()); diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc index b7517fae26a..ed6443dd2ef 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_api.cc @@ -39,18 +39,17 @@ DesktopCaptureChooseDesktopMediaFunction:: ExtensionFunction::ResponseAction DesktopCaptureChooseDesktopMediaFunction::Run() { - const auto& list = args_->GetList(); - EXTENSION_FUNCTION_VALIDATE(list.size() > 0); - const auto& request_id_value = list[0]; + EXTENSION_FUNCTION_VALIDATE(args().size() > 0); + const auto& request_id_value = args()[0]; EXTENSION_FUNCTION_VALIDATE(request_id_value.is_int()); request_id_ = request_id_value.GetInt(); DesktopCaptureRequestsRegistry::GetInstance()->AddRequest(source_process_id(), request_id_, this); - args_->EraseListIter(list.begin()); + mutable_args().erase(args().begin()); std::unique_ptr<api::desktop_capture::ChooseDesktopMedia::Params> params = - api::desktop_capture::ChooseDesktopMedia::Params::Create(*args_); + api::desktop_capture::ChooseDesktopMedia::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); // |web_contents| is the WebContents for which the stream is created, and will diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc index 5e817db1540..fcae3b1a3a5 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc @@ -154,8 +154,8 @@ IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, DISABLED_Delegation) { const Extension* extension = LoadExtension(extension_path); ASSERT_TRUE(extension); - ui_test_utils::NavigateToURL( - browser(), GetURLForPath("example.com", "/example.com.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GetURLForPath("example.com", "/example.com.html"))); FakeDesktopMediaPickerFactory::TestFlags test_flags[] = { {true, true, false, false, false, diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc index 42aaad21901..2a391251562 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc @@ -222,12 +222,12 @@ DesktopCaptureCancelChooseDesktopMediaFunctionBase:: ExtensionFunction::ResponseAction DesktopCaptureCancelChooseDesktopMediaFunctionBase::Run() { - EXTENSION_FUNCTION_VALIDATE(args_->GetList().size() >= 1); - absl::optional<int> request_id = args_->GetList()[0].GetIfInt(); - EXTENSION_FUNCTION_VALIDATE(request_id.has_value()); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 1); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_int()); + int request_id = args()[0].GetInt(); DesktopCaptureRequestsRegistry::GetInstance()->CancelRequest( - source_process_id(), *request_id); + source_process_id(), request_id); return RespondNow(NoArguments()); } diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h index 93f450ad84c..2e7a394dfa3 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.h @@ -76,6 +76,12 @@ class DesktopCaptureCancelChooseDesktopMediaFunctionBase class DesktopCaptureRequestsRegistry { public: DesktopCaptureRequestsRegistry(); + + DesktopCaptureRequestsRegistry(const DesktopCaptureRequestsRegistry&) = + delete; + DesktopCaptureRequestsRegistry& operator=( + const DesktopCaptureRequestsRegistry&) = delete; + ~DesktopCaptureRequestsRegistry(); static DesktopCaptureRequestsRegistry* GetInstance(); @@ -103,8 +109,6 @@ class DesktopCaptureRequestsRegistry { std::map<RequestId, DesktopCaptureChooseDesktopMediaFunctionBase*>; RequestsMap requests_; - - DISALLOW_COPY_AND_ASSIGN(DesktopCaptureRequestsRegistry); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc index f16fba9f33d..f35f7e9d224 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.cc @@ -277,6 +277,9 @@ class DeveloperPrivateAPI::WebContentsTracker content::WebContents* web_contents) : content::WebContentsObserver(web_contents), api_(api) {} + WebContentsTracker(const WebContentsTracker&) = delete; + WebContentsTracker& operator=(const WebContentsTracker&) = delete; + private: ~WebContentsTracker() override = default; @@ -287,8 +290,6 @@ class DeveloperPrivateAPI::WebContentsTracker } base::WeakPtr<DeveloperPrivateAPI> api_; - - DISALLOW_COPY_AND_ASSIGN(WebContentsTracker); }; DeveloperPrivateAPI::WebContentsData::WebContentsData() = default; @@ -311,7 +312,7 @@ std::unique_ptr<developer::ProfileInfo> DeveloperPrivateAPI::CreateProfileInfo( const PrefService::Preference* pref = prefs->FindPreference(prefs::kExtensionsUIDeveloperMode); info->is_incognito_available = IncognitoModePrefs::GetAvailability(prefs) != - IncognitoModePrefs::DISABLED; + IncognitoModePrefs::Availability::kDisabled; info->is_developer_mode_controlled_by_policy = pref->IsManaged(); info->in_developer_mode = !info->is_supervised && @@ -743,7 +744,7 @@ DeveloperPrivateGetExtensionsInfoFunction:: ExtensionFunction::ResponseAction DeveloperPrivateGetExtensionsInfoFunction::Run() { std::unique_ptr<developer::GetExtensionsInfo::Params> params( - developer::GetExtensionsInfo::Params::Create(*args_)); + developer::GetExtensionsInfo::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); bool include_disabled = true; @@ -781,7 +782,7 @@ DeveloperPrivateGetExtensionInfoFunction:: ExtensionFunction::ResponseAction DeveloperPrivateGetExtensionInfoFunction::Run() { std::unique_ptr<developer::GetExtensionInfo::Params> params( - developer::GetExtensionInfo::Params::Create(*args_)); + developer::GetExtensionInfo::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); info_generator_ = std::make_unique<ExtensionInfoGenerator>(browser_context()); @@ -811,7 +812,7 @@ DeveloperPrivateGetExtensionSizeFunction:: ExtensionFunction::ResponseAction DeveloperPrivateGetExtensionSizeFunction::Run() { std::unique_ptr<developer::GetExtensionSize::Params> params( - developer::GetExtensionSize::Params::Create(*args_)); + developer::GetExtensionSize::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const Extension* extension = GetExtensionById(params->id); @@ -837,7 +838,7 @@ DeveloperPrivateGetItemsInfoFunction::~DeveloperPrivateGetItemsInfoFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateGetItemsInfoFunction::Run() { std::unique_ptr<developer::GetItemsInfo::Params> params( - developer::GetItemsInfo::Params::Create(*args_)); + developer::GetItemsInfo::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); info_generator_ = std::make_unique<ExtensionInfoGenerator>(browser_context()); @@ -886,7 +887,7 @@ DeveloperPrivateUpdateProfileConfigurationFunction:: ExtensionFunction::ResponseAction DeveloperPrivateUpdateProfileConfigurationFunction::Run() { std::unique_ptr<developer::UpdateProfileConfiguration::Params> params( - developer::UpdateProfileConfiguration::Params::Create(*args_)); + developer::UpdateProfileConfiguration::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const developer::ProfileConfigurationUpdate& update = params->update; @@ -908,7 +909,7 @@ DeveloperPrivateUpdateExtensionConfigurationFunction:: ExtensionFunction::ResponseAction DeveloperPrivateUpdateExtensionConfigurationFunction::Run() { std::unique_ptr<developer::UpdateExtensionConfiguration::Params> params( - developer::UpdateExtensionConfiguration::Params::Create(*args_)); + developer::UpdateExtensionConfiguration::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const developer::ExtensionConfigurationUpdate& update = params->update; @@ -968,7 +969,7 @@ DeveloperPrivateReloadFunction::DeveloperPrivateReloadFunction() = default; DeveloperPrivateReloadFunction::~DeveloperPrivateReloadFunction() = default; ExtensionFunction::ResponseAction DeveloperPrivateReloadFunction::Run() { - std::unique_ptr<Reload::Params> params(Reload::Params::Create(*args_)); + std::unique_ptr<Reload::Params> params(Reload::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); const Extension* extension = GetExtensionById(params->extension_id); @@ -1072,7 +1073,7 @@ DeveloperPrivateShowPermissionsDialogFunction:: ExtensionFunction::ResponseAction DeveloperPrivateShowPermissionsDialogFunction::Run() { std::unique_ptr<developer::ShowPermissionsDialog::Params> params( - developer::ShowPermissionsDialog::Params::Create(*args_)); + developer::ShowPermissionsDialog::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const Extension* target_extension = GetExtensionById(params->extension_id); @@ -1098,7 +1099,7 @@ DeveloperPrivateLoadUnpackedFunction::DeveloperPrivateLoadUnpackedFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateLoadUnpackedFunction::Run() { std::unique_ptr<developer::LoadUnpacked::Params> params( - developer::LoadUnpacked::Params::Create(*args_)); + developer::LoadUnpacked::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); content::WebContents* web_contents = GetSenderWebContents(); @@ -1348,7 +1349,7 @@ void DeveloperPrivatePackDirectoryFunction::OnPackFailure( ExtensionFunction::ResponseAction DeveloperPrivatePackDirectoryFunction::Run() { std::unique_ptr<PackDirectory::Params> params( - PackDirectory::Params::Create(*args_)); + PackDirectory::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int flags = params->flags ? *params->flags : 0; @@ -1400,13 +1401,14 @@ DeveloperPrivateLoadUnpackedFunction::~DeveloperPrivateLoadUnpackedFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateLoadDirectoryFunction::Run() { // TODO(grv) : add unittests. - std::string directory_url_str; - std::string filesystem_name; - std::string filesystem_path; + EXTENSION_FUNCTION_VALIDATE(args().size() >= 3); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); + EXTENSION_FUNCTION_VALIDATE(args()[1].is_string()); + EXTENSION_FUNCTION_VALIDATE(args()[2].is_string()); - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &filesystem_name)); - EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_path)); - EXTENSION_FUNCTION_VALIDATE(args_->GetString(2, &directory_url_str)); + const std::string& filesystem_name = args()[0].GetString(); + const std::string& filesystem_path = args()[1].GetString(); + const std::string& directory_url_str = args()[2].GetString(); context_ = browser_context() ->GetStoragePartition(render_frame_host()->GetSiteInstance()) @@ -1632,7 +1634,7 @@ DeveloperPrivateLoadDirectoryFunction::~DeveloperPrivateLoadDirectoryFunction() ExtensionFunction::ResponseAction DeveloperPrivateChoosePathFunction::Run() { std::unique_ptr<developer::ChoosePath::Params> params( - developer::ChoosePath::Params::Create(*args_)); + developer::ChoosePath::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); ui::SelectFileDialog::Type type = ui::SelectFileDialog::SELECT_FOLDER; @@ -1704,7 +1706,7 @@ DeveloperPrivateRequestFileSourceFunction:: ExtensionFunction::ResponseAction DeveloperPrivateRequestFileSourceFunction::Run() { - params_ = developer::RequestFileSource::Params::Create(*args_); + params_ = developer::RequestFileSource::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_); const developer::RequestFileSourceProperties& properties = @@ -1774,7 +1776,7 @@ DeveloperPrivateOpenDevToolsFunction::~DeveloperPrivateOpenDevToolsFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateOpenDevToolsFunction::Run() { std::unique_ptr<developer::OpenDevTools::Params> params( - developer::OpenDevTools::Params::Create(*args_)); + developer::OpenDevTools::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const developer::OpenDevToolsProperties& properties = params->properties; @@ -1863,7 +1865,7 @@ DeveloperPrivateDeleteExtensionErrorsFunction:: ExtensionFunction::ResponseAction DeveloperPrivateDeleteExtensionErrorsFunction::Run() { std::unique_ptr<developer::DeleteExtensionErrors::Params> params( - developer::DeleteExtensionErrors::Params::Create(*args_)); + developer::DeleteExtensionErrors::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const developer::DeleteExtensionErrorsProperties& properties = params->properties; @@ -1891,7 +1893,7 @@ DeveloperPrivateRepairExtensionFunction:: ExtensionFunction::ResponseAction DeveloperPrivateRepairExtensionFunction::Run() { std::unique_ptr<developer::RepairExtension::Params> params( - developer::RepairExtension::Params::Create(*args_)); + developer::RepairExtension::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) @@ -1937,7 +1939,7 @@ DeveloperPrivateShowOptionsFunction::~DeveloperPrivateShowOptionsFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateShowOptionsFunction::Run() { std::unique_ptr<developer::ShowOptions::Params> params( - developer::ShowOptions::Params::Create(*args_)); + developer::ShowOptions::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const Extension* extension = GetEnabledExtensionById(params->extension_id); if (!extension) @@ -1960,7 +1962,7 @@ DeveloperPrivateShowPathFunction::~DeveloperPrivateShowPathFunction() {} ExtensionFunction::ResponseAction DeveloperPrivateShowPathFunction::Run() { std::unique_ptr<developer::ShowPath::Params> params( - developer::ShowPath::Params::Create(*args_)); + developer::ShowPath::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const Extension* extension = GetExtensionById(params->extension_id); if (!extension) @@ -1980,7 +1982,7 @@ DeveloperPrivateSetShortcutHandlingSuspendedFunction:: ExtensionFunction::ResponseAction DeveloperPrivateSetShortcutHandlingSuspendedFunction::Run() { std::unique_ptr<developer::SetShortcutHandlingSuspended::Params> params( - developer::SetShortcutHandlingSuspended::Params::Create(*args_)); + developer::SetShortcutHandlingSuspended::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); ExtensionCommandsGlobalRegistry::Get(browser_context()) ->SetShortcutHandlingSuspended(params->is_suspended); @@ -1993,7 +1995,7 @@ DeveloperPrivateUpdateExtensionCommandFunction:: ExtensionFunction::ResponseAction DeveloperPrivateUpdateExtensionCommandFunction::Run() { std::unique_ptr<developer::UpdateExtensionCommand::Params> params( - developer::UpdateExtensionCommand::Params::Create(*args_)); + developer::UpdateExtensionCommand::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const developer::ExtensionCommandUpdate& update = params->update; @@ -2020,7 +2022,7 @@ DeveloperPrivateAddHostPermissionFunction:: ExtensionFunction::ResponseAction DeveloperPrivateAddHostPermissionFunction::Run() { std::unique_ptr<developer::AddHostPermission::Params> params( - developer::AddHostPermission::Params::Create(*args_)); + developer::AddHostPermission::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); absl::optional<URLPattern> pattern = @@ -2063,7 +2065,7 @@ DeveloperPrivateRemoveHostPermissionFunction:: ExtensionFunction::ResponseAction DeveloperPrivateRemoveHostPermissionFunction::Run() { std::unique_ptr<developer::RemoveHostPermission::Params> params( - developer::RemoveHostPermission::Params::Create(*args_)); + developer::RemoveHostPermission::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); absl::optional<URLPattern> pattern = diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h index b8b7fcf661d..9b6ca4d7e59 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api.h @@ -74,6 +74,11 @@ class DeveloperPrivateEventRouter : public ExtensionRegistryObserver, public content::NotificationObserver { public: explicit DeveloperPrivateEventRouter(Profile* profile); + + DeveloperPrivateEventRouter(const DeveloperPrivateEventRouter&) = delete; + DeveloperPrivateEventRouter& operator=(const DeveloperPrivateEventRouter&) = + delete; + ~DeveloperPrivateEventRouter() override; // Add or remove an ID to the list of extensions subscribed to events. @@ -188,8 +193,6 @@ class DeveloperPrivateEventRouter : public ExtensionRegistryObserver, content::NotificationRegistrar notification_registrar_; base::WeakPtrFactory<DeveloperPrivateEventRouter> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateEventRouter); }; // The profile-keyed service that manages the DeveloperPrivate API. @@ -208,6 +211,10 @@ class DeveloperPrivateAPI : public BrowserContextKeyedAPI, static DeveloperPrivateAPI* Get(content::BrowserContext* context); explicit DeveloperPrivateAPI(content::BrowserContext* context); + + DeveloperPrivateAPI(const DeveloperPrivateAPI&) = delete; + DeveloperPrivateAPI& operator=(const DeveloperPrivateAPI&) = delete; + ~DeveloperPrivateAPI() override; // Adds a path to the list of allowed unpacked paths for the given @@ -250,6 +257,10 @@ class DeveloperPrivateAPI : public BrowserContextKeyedAPI, // Data specific to a given WebContents. struct WebContentsData { WebContentsData(); + + WebContentsData(const WebContentsData&) = delete; + WebContentsData& operator=(const WebContentsData&) = delete; + ~WebContentsData(); WebContentsData(WebContentsData&& other); @@ -266,8 +277,6 @@ class DeveloperPrivateAPI : public BrowserContextKeyedAPI, // The last dragged path for the WebContents. base::FilePath dragged_path; - - DISALLOW_COPY_AND_ASSIGN(WebContentsData); }; friend class BrowserContextKeyedAPIFactory<DeveloperPrivateAPI>; @@ -296,8 +305,6 @@ class DeveloperPrivateAPI : public BrowserContextKeyedAPI, std::unique_ptr<DeveloperPrivateEventRouter> developer_private_event_router_; base::WeakPtrFactory<DeveloperPrivateAPI> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateAPI); }; template <> @@ -339,6 +346,11 @@ class DeveloperPrivateGetItemsInfoFunction DEVELOPERPRIVATE_GETITEMSINFO) DeveloperPrivateGetItemsInfoFunction(); + DeveloperPrivateGetItemsInfoFunction( + const DeveloperPrivateGetItemsInfoFunction&) = delete; + DeveloperPrivateGetItemsInfoFunction& operator=( + const DeveloperPrivateGetItemsInfoFunction&) = delete; + private: ~DeveloperPrivateGetItemsInfoFunction() override; ResponseAction Run() override; @@ -347,14 +359,18 @@ class DeveloperPrivateGetItemsInfoFunction std::vector<api::developer_private::ExtensionInfo> infos); std::unique_ptr<ExtensionInfoGenerator> info_generator_; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateGetItemsInfoFunction); }; class DeveloperPrivateGetExtensionsInfoFunction : public DeveloperPrivateAPIFunction { public: DeveloperPrivateGetExtensionsInfoFunction(); + + DeveloperPrivateGetExtensionsInfoFunction( + const DeveloperPrivateGetExtensionsInfoFunction&) = delete; + DeveloperPrivateGetExtensionsInfoFunction& operator=( + const DeveloperPrivateGetExtensionsInfoFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("developerPrivate.getExtensionsInfo", DEVELOPERPRIVATE_GETEXTENSIONSINFO) @@ -366,14 +382,18 @@ class DeveloperPrivateGetExtensionsInfoFunction std::vector<api::developer_private::ExtensionInfo> infos); std::unique_ptr<ExtensionInfoGenerator> info_generator_; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateGetExtensionsInfoFunction); }; class DeveloperPrivateGetExtensionInfoFunction : public DeveloperPrivateAPIFunction { public: DeveloperPrivateGetExtensionInfoFunction(); + + DeveloperPrivateGetExtensionInfoFunction( + const DeveloperPrivateGetExtensionInfoFunction&) = delete; + DeveloperPrivateGetExtensionInfoFunction& operator=( + const DeveloperPrivateGetExtensionInfoFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("developerPrivate.getExtensionInfo", DEVELOPERPRIVATE_GETEXTENSIONINFO) @@ -385,14 +405,18 @@ class DeveloperPrivateGetExtensionInfoFunction std::vector<api::developer_private::ExtensionInfo> infos); std::unique_ptr<ExtensionInfoGenerator> info_generator_; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateGetExtensionInfoFunction); }; class DeveloperPrivateGetExtensionSizeFunction : public DeveloperPrivateAPIFunction { public: DeveloperPrivateGetExtensionSizeFunction(); + + DeveloperPrivateGetExtensionSizeFunction( + const DeveloperPrivateGetExtensionSizeFunction&) = delete; + DeveloperPrivateGetExtensionSizeFunction& operator=( + const DeveloperPrivateGetExtensionSizeFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("developerPrivate.getExtensionSize", DEVELOPERPRIVATE_GETEXTENSIONSIZE) @@ -401,8 +425,6 @@ class DeveloperPrivateGetExtensionSizeFunction ResponseAction Run() override; void OnSizeCalculated(const std::u16string& size); - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateGetExtensionSizeFunction); }; class DeveloperPrivateGetProfileConfigurationFunction @@ -446,6 +468,11 @@ class DeveloperPrivateReloadFunction : public DeveloperPrivateAPIFunction, DeveloperPrivateReloadFunction(); + DeveloperPrivateReloadFunction(const DeveloperPrivateReloadFunction&) = + delete; + DeveloperPrivateReloadFunction& operator=( + const DeveloperPrivateReloadFunction&) = delete; + // ExtensionRegistryObserver: void OnExtensionLoaded(content::BrowserContext* browser_context, const Extension* extension) override; @@ -479,8 +506,6 @@ class DeveloperPrivateReloadFunction : public DeveloperPrivateAPIFunction, registry_observation_{this}; base::ScopedObservation<LoadErrorReporter, LoadErrorReporter::Observer> error_reporter_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateReloadFunction); }; class DeveloperPrivateShowPermissionsDialogFunction @@ -490,14 +515,17 @@ class DeveloperPrivateShowPermissionsDialogFunction DEVELOPERPRIVATE_PERMISSIONS) DeveloperPrivateShowPermissionsDialogFunction(); + DeveloperPrivateShowPermissionsDialogFunction( + const DeveloperPrivateShowPermissionsDialogFunction&) = delete; + DeveloperPrivateShowPermissionsDialogFunction& operator=( + const DeveloperPrivateShowPermissionsDialogFunction&) = delete; + protected: // DeveloperPrivateAPIFunction: ~DeveloperPrivateShowPermissionsDialogFunction() override; ResponseAction Run() override; void Finish(); - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateShowPermissionsDialogFunction); }; class DeveloperPrivateChooseEntryFunction : public ExtensionFunction, @@ -554,13 +582,16 @@ class DeveloperPrivateInstallDroppedFileFunction DEVELOPERPRIVATE_INSTALLDROPPEDFILE) DeveloperPrivateInstallDroppedFileFunction(); + DeveloperPrivateInstallDroppedFileFunction( + const DeveloperPrivateInstallDroppedFileFunction&) = delete; + DeveloperPrivateInstallDroppedFileFunction& operator=( + const DeveloperPrivateInstallDroppedFileFunction&) = delete; + private: ~DeveloperPrivateInstallDroppedFileFunction() override; // ExtensionFunction: ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateInstallDroppedFileFunction); }; class DeveloperPrivateNotifyDragInstallInProgressFunction @@ -571,14 +602,17 @@ class DeveloperPrivateNotifyDragInstallInProgressFunction DeveloperPrivateNotifyDragInstallInProgressFunction(); + DeveloperPrivateNotifyDragInstallInProgressFunction( + const DeveloperPrivateNotifyDragInstallInProgressFunction&) = delete; + DeveloperPrivateNotifyDragInstallInProgressFunction& operator=( + const DeveloperPrivateNotifyDragInstallInProgressFunction&) = delete; + ResponseAction Run() override; static void SetDropPathForTesting(base::FilePath* file_path); private: ~DeveloperPrivateNotifyDragInstallInProgressFunction() override; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateNotifyDragInstallInProgressFunction); }; class DeveloperPrivateChoosePathFunction @@ -797,14 +831,17 @@ class DeveloperPrivateAddHostPermissionFunction DEVELOPERPRIVATE_ADDHOSTPERMISSION) DeveloperPrivateAddHostPermissionFunction(); + DeveloperPrivateAddHostPermissionFunction( + const DeveloperPrivateAddHostPermissionFunction&) = delete; + DeveloperPrivateAddHostPermissionFunction& operator=( + const DeveloperPrivateAddHostPermissionFunction&) = delete; + private: ~DeveloperPrivateAddHostPermissionFunction() override; ResponseAction Run() override; void OnRuntimePermissionsGranted(); - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateAddHostPermissionFunction); }; class DeveloperPrivateRemoveHostPermissionFunction @@ -814,14 +851,17 @@ class DeveloperPrivateRemoveHostPermissionFunction DEVELOPERPRIVATE_REMOVEHOSTPERMISSION) DeveloperPrivateRemoveHostPermissionFunction(); + DeveloperPrivateRemoveHostPermissionFunction( + const DeveloperPrivateRemoveHostPermissionFunction&) = delete; + DeveloperPrivateRemoveHostPermissionFunction& operator=( + const DeveloperPrivateRemoveHostPermissionFunction&) = delete; + private: ~DeveloperPrivateRemoveHostPermissionFunction() override; ResponseAction Run() override; void OnRuntimePermissionsRevoked(); - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateRemoveHostPermissionFunction); }; } // namespace api diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc index 57224acbfdc..482f466f506 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_api_unittest.cc @@ -116,6 +116,11 @@ bool WasItemChangedEventDispatched( } // namespace class DeveloperPrivateApiUnitTest : public ExtensionServiceTestWithInstall { + public: + DeveloperPrivateApiUnitTest(const DeveloperPrivateApiUnitTest&) = delete; + DeveloperPrivateApiUnitTest& operator=(const DeveloperPrivateApiUnitTest&) = + delete; + protected: DeveloperPrivateApiUnitTest() {} ~DeveloperPrivateApiUnitTest() override {} @@ -179,8 +184,6 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestWithInstall { std::unique_ptr<Browser> browser_; std::vector<std::unique_ptr<TestExtensionDir>> test_extension_dirs_; - - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateApiUnitTest); }; bool DeveloperPrivateApiUnitTest::RunFunction( @@ -325,7 +328,7 @@ void DeveloperPrivateApiUnitTest::GetProfileConfiguration( EXPECT_TRUE(RunFunction(function, args)) << function->GetError(); ASSERT_TRUE(function->GetResultList()); - ASSERT_EQ(1u, function->GetResultList()->GetSize()); + ASSERT_EQ(1u, function->GetResultList()->GetList().size()); const base::Value* response_value = nullptr; function->GetResultList()->Get(0u, &response_value); *profile_info = @@ -410,7 +413,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateReload) { scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateReloadFunction()); base::ListValue reload_args; - reload_args.AppendString(extension_id); + reload_args.Append(extension_id); TestExtensionRegistryObserver registry_observer(registry()); EXPECT_TRUE(RunFunction(function, reload_args)); @@ -444,7 +447,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivatePackFunction) { // First, test a directory that should pack properly. base::ListValue pack_args; - pack_args.AppendString(temp_root_path.AsUTF8Unsafe()); + pack_args.Append(temp_root_path.AsUTF8Unsafe()); EXPECT_TRUE(TestPackExtensionFunction( pack_args, api::developer_private::PACK_STATUS_SUCCESS, 0)); @@ -453,7 +456,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivatePackFunction) { EXPECT_TRUE(base::PathExists(pem_path)); // Deliberately don't cleanup the files, and append the pem path. - pack_args.AppendString(pem_path.AsUTF8Unsafe()); + pack_args.Append(pem_path.AsUTF8Unsafe()); // Try to pack again - we should get a warning abot overwriting the crx. EXPECT_TRUE(TestPackExtensionFunction( @@ -462,7 +465,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivatePackFunction) { ExtensionCreator::kOverwriteCRX)); // Try to pack again, with the overwrite flag; this should succeed. - pack_args.AppendInteger(ExtensionCreator::kOverwriteCRX); + pack_args.Append(ExtensionCreator::kOverwriteCRX); EXPECT_TRUE(TestPackExtensionFunction( pack_args, api::developer_private::PACK_STATUS_SUCCESS, 0)); @@ -488,8 +491,8 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateChoosePath) { // Try selecting a directory. base::ListValue choose_args; - choose_args.AppendString("FOLDER"); - choose_args.AppendString("LOAD"); + choose_args.Append("FOLDER"); + choose_args.Append("LOAD"); scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateChoosePathFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -504,8 +507,8 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateChoosePath) { data_dir().AppendASCII("simple_with_popup.pem"); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&expected_file_path); choose_args.ClearList(); - choose_args.AppendString("FILE"); - choose_args.AppendString("PEM"); + choose_args.Append("FILE"); + choose_args.Append("PEM"); function = new api::DeveloperPrivateChoosePathFunction(); function->SetRenderFrameHost(web_contents->GetMainFrame()); EXPECT_TRUE(RunFunction(function, choose_args)) << function->GetError(); @@ -838,6 +841,10 @@ TEST_F(DeveloperPrivateApiUnitTest, ReloadBadExtensionToLoadUnpackedRetry) { observation_.Observe(registry); } + UnloadedRegistryObserver(const UnloadedRegistryObserver&) = delete; + UnloadedRegistryObserver& operator=(const UnloadedRegistryObserver&) = + delete; + void OnExtensionUnloaded(content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionReason reason) override { @@ -852,8 +859,6 @@ TEST_F(DeveloperPrivateApiUnitTest, ReloadBadExtensionToLoadUnpackedRetry) { base::FilePath expected_path_; base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(UnloadedRegistryObserver); }; UnloadedRegistryObserver unload_observer(path, registry()); @@ -900,10 +905,10 @@ TEST_F(DeveloperPrivateApiUnitTest, ReloadBadExtensionToLoadUnpackedRetry) { "retryGuid": "%s"}])", retry_guid.c_str()); api_test_utils::RunFunction(function.get(), args, profile()); - scoped_refptr<const Extension> extension = + scoped_refptr<const Extension> reloaded_extension = observer.WaitForExtensionLoaded(); - ASSERT_TRUE(extension); - EXPECT_EQ(extension->path(), path); + ASSERT_TRUE(reloaded_extension); + EXPECT_EQ(reloaded_extension->path(), path); EXPECT_TRUE(registry()->enabled_extensions().Contains(id)); } } @@ -1046,8 +1051,8 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateGetExtensionsInfo) { // sane value. function = new api::DeveloperPrivateGetItemsInfoFunction(); base::ListValue args; - args.AppendBoolean(false); - args.AppendBoolean(false); + args.Append(false); + args.Append(false); EXPECT_TRUE(RunFunction(function, args)) << function->GetError(); results = function->GetResultList(); results_list = results->GetList(); @@ -1821,8 +1826,9 @@ TEST_F(DeveloperPrivateApiAllowlistUnitTest, test_observer, dummy_extension->id(), api::developer_private::EVENT_TYPE_PREFS_CHANGED)); - safe_browsing::SetSafeBrowsingState(profile()->GetPrefs(), - safe_browsing::ENHANCED_PROTECTION); + safe_browsing::SetSafeBrowsingState( + profile()->GetPrefs(), + safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION); base::RunLoop().RunUntilIdle(); // The warning state should not have changed since the allowlist state is not @@ -1841,8 +1847,9 @@ TEST_F(DeveloperPrivateApiAllowlistUnitTest, test_observer.ClearEvents(); - safe_browsing::SetSafeBrowsingState(profile()->GetPrefs(), - safe_browsing::STANDARD_PROTECTION); + safe_browsing::SetSafeBrowsingState( + profile()->GetPrefs(), + safe_browsing::SafeBrowsingState::STANDARD_PROTECTION); base::RunLoop().RunUntilIdle(); // The warning is now hidden because the profile is no longer Enhanced @@ -1856,12 +1863,15 @@ class DeveloperPrivateApiSupervisedUserUnitTest : public DeveloperPrivateApiUnitTest { public: DeveloperPrivateApiSupervisedUserUnitTest() = default; + + DeveloperPrivateApiSupervisedUserUnitTest( + const DeveloperPrivateApiSupervisedUserUnitTest&) = delete; + DeveloperPrivateApiSupervisedUserUnitTest& operator=( + const DeveloperPrivateApiSupervisedUserUnitTest&) = delete; + ~DeveloperPrivateApiSupervisedUserUnitTest() override = default; bool ProfileIsSupervised() const override { return true; } - - private: - DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateApiSupervisedUserUnitTest); }; // Tests trying to call loadUnpacked when the profile shouldn't be allowed to. diff --git a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.h b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.h index d9eaa552969..f2faecb0e9f 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.h +++ b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.h @@ -34,6 +34,9 @@ class EntryPicker : public ui::SelectFileDialog::Listener { const ui::SelectFileDialog::FileTypeInfo& info, int file_type_index); + EntryPicker(const EntryPicker&) = delete; + EntryPicker& operator=(const EntryPicker&) = delete; + // Allow picker UI to be skipped in testing. static void SkipPickerAndAlwaysSelectPathForTest(base::FilePath* path); static void SkipPickerAndAlwaysCancelForTest(); @@ -53,8 +56,6 @@ class EntryPicker : public ui::SelectFileDialog::Listener { scoped_refptr<ui::SelectFileDialog> select_file_dialog_; EntryPickerClient* client_; - - DISALLOW_COPY_AND_ASSIGN(EntryPicker); }; } // namespace api diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc index eae89544afe..4d9b13d1cb1 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc @@ -552,10 +552,10 @@ void ExtensionInfoGenerator::CreateExtensionInfoHelper( ->GetDependentExtensions(&extension); for (const scoped_refptr<const Extension>& dependent : *dependent_extensions) { - developer::DependentExtension extension; - extension.id = dependent->id(); - extension.name = dependent->name(); - info->dependent_extensions.push_back(std::move(extension)); + developer::DependentExtension dependent_extension; + dependent_extension.id = dependent->id(); + dependent_extension.name = dependent->name(); + info->dependent_extensions.push_back(std::move(dependent_extension)); } } diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h index 812128fe5a4..5db74095e24 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h +++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.h @@ -46,6 +46,10 @@ class ExtensionInfoGenerator { using ExtensionInfosCallback = base::OnceCallback<void(ExtensionInfoList)>; explicit ExtensionInfoGenerator(content::BrowserContext* context); + + ExtensionInfoGenerator(const ExtensionInfoGenerator&) = delete; + ExtensionInfoGenerator& operator=(const ExtensionInfoGenerator&) = delete; + ~ExtensionInfoGenerator(); // Creates and asynchronously returns an ExtensionInfo for the given @@ -100,8 +104,6 @@ class ExtensionInfoGenerator { ExtensionInfosCallback callback_; base::WeakPtrFactory<ExtensionInfoGenerator> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(ExtensionInfoGenerator); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc index 0365ae62e7c..41c706e658e 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc @@ -103,6 +103,12 @@ std::string SiteControlsToString( class ExtensionInfoGeneratorUnitTest : public ExtensionServiceTestWithInstall { public: ExtensionInfoGeneratorUnitTest() {} + + ExtensionInfoGeneratorUnitTest(const ExtensionInfoGeneratorUnitTest&) = + delete; + ExtensionInfoGeneratorUnitTest& operator=( + const ExtensionInfoGeneratorUnitTest&) = delete; + ~ExtensionInfoGeneratorUnitTest() override {} protected: @@ -243,8 +249,6 @@ class ExtensionInfoGeneratorUnitTest : public ExtensionServiceTestWithInstall { private: base::OnceClosure quit_closure_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionInfoGeneratorUnitTest); }; // Test some of the basic fields. @@ -608,7 +612,7 @@ TEST_F(ExtensionInfoGeneratorUnitTest, RuntimeHostPermissionsAllURLs) { PermissionSet all_url_set(APIPermissionSet(), ManifestPermissionSet(), URLPatternSet({all_url}), URLPatternSet({all_url})); PermissionsUpdater(profile()).GrantRuntimePermissions( - *all_urls_extension, all_url_set, base::DoNothing::Once()); + *all_urls_extension, all_url_set, base::DoNothing()); // Now the extension should look like it has access to all hosts, while still // also counting as having permission withholding enabled. @@ -679,7 +683,7 @@ TEST_F(ExtensionInfoGeneratorUnitTest, WithheldUrlsOverlapping) { URLPatternSet({example_com}), URLPatternSet({example_com})); PermissionsUpdater(profile()).GrantRuntimePermissions( - *extension, example_com_set, base::DoNothing::Once()); + *extension, example_com_set, base::DoNothing()); } { @@ -707,7 +711,7 @@ TEST_F(ExtensionInfoGeneratorUnitTest, WithheldUrlsOverlapping) { URLPatternSet({example_com}), URLPatternSet({example_com})); PermissionsUpdater(profile()).GrantRuntimePermissions( - *extension, example_com_set, base::DoNothing::Once()); + *extension, example_com_set, base::DoNothing()); } { diff --git a/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h b/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h index c09f31c2cca..eb3657d1276 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h +++ b/chromium/chrome/browser/extensions/api/developer_private/inspectable_views_finder.h @@ -31,6 +31,10 @@ class InspectableViewsFinder { using ViewList = std::vector<View>; explicit InspectableViewsFinder(Profile* profile); + + InspectableViewsFinder(const InspectableViewsFinder&) = delete; + InspectableViewsFinder& operator=(const InspectableViewsFinder&) = delete; + ~InspectableViewsFinder(); // Construct a view from the given parameters. @@ -64,8 +68,6 @@ class InspectableViewsFinder { ViewList* result); Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(InspectableViewsFinder); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.h b/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.h index 3fea6b66fa3..2349404fc1c 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.h +++ b/chromium/chrome/browser/extensions/api/developer_private/show_permissions_dialog_helper.h @@ -26,6 +26,10 @@ class Extension; // install-prompt style dialog. class ShowPermissionsDialogHelper { public: + ShowPermissionsDialogHelper(const ShowPermissionsDialogHelper&) = delete; + ShowPermissionsDialogHelper& operator=(const ShowPermissionsDialogHelper&) = + delete; + static void Show(content::BrowserContext* browser_context, content::WebContents* web_contents, const Extension* extension, @@ -48,8 +52,6 @@ class ShowPermissionsDialogHelper { base::OnceClosure on_complete_; std::string extension_id_; - - DISALLOW_COPY_AND_ASSIGN(ShowPermissionsDialogHelper); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc index 0f5a5f61672..f1b68a479e9 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc @@ -659,6 +659,11 @@ class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data { download_item->SetUserData(kKey, base::WrapUnique(this)); } + ExtensionDownloadsEventRouterData(const ExtensionDownloadsEventRouterData&) = + delete; + ExtensionDownloadsEventRouterData& operator=( + const ExtensionDownloadsEventRouterData&) = delete; + ~ExtensionDownloadsEventRouterData() override = default; void set_is_download_completed(bool is_download_completed) { @@ -701,7 +706,7 @@ class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data { base::BindOnce( &ExtensionDownloadsEventRouterData::DetermineFilenameTimeout, weak_ptr_factory_->GetWeakPtr()), - base::TimeDelta::FromSeconds(determine_filename_timeout_s_)); + base::Seconds(determine_filename_timeout_s_)); } void DetermineFilenameTimeout() { CallFilenameCallback(); } @@ -861,7 +866,7 @@ class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data { base::BindOnce( &ExtensionDownloadsEventRouterData::ClearPendingDeterminers, weak_ptr_factory_->GetWeakPtr()), - base::TimeDelta::FromSeconds(15)); + base::Seconds(15)); } int updated_; @@ -887,8 +892,6 @@ class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data { std::unique_ptr<base::WeakPtrFactory<ExtensionDownloadsEventRouterData>> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionDownloadsEventRouterData); }; int ExtensionDownloadsEventRouterData::determine_filename_timeout_s_ = 15; @@ -965,7 +968,7 @@ DownloadsDownloadFunction::~DownloadsDownloadFunction() {} ExtensionFunction::ResponseAction DownloadsDownloadFunction::Run() { std::unique_ptr<downloads::Download::Params> params( - downloads::Download::Params::Create(*args_)); + downloads::Download::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); const downloads::DownloadOptions& options = params->options; GURL download_url(options.url); @@ -1100,7 +1103,7 @@ DownloadsSearchFunction::~DownloadsSearchFunction() {} ExtensionFunction::ResponseAction DownloadsSearchFunction::Run() { std::unique_ptr<downloads::Search::Params> params( - downloads::Search::Params::Create(*args_)); + downloads::Search::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadManager* manager = NULL; DownloadManager* incognito_manager = NULL; @@ -1149,7 +1152,7 @@ DownloadsPauseFunction::~DownloadsPauseFunction() {} ExtensionFunction::ResponseAction DownloadsPauseFunction::Run() { std::unique_ptr<downloads::Pause::Params> params( - downloads::Pause::Params::Create(*args_)); + downloads::Pause::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = GetDownload( browser_context(), include_incognito_information(), params->download_id); @@ -1172,7 +1175,7 @@ DownloadsResumeFunction::~DownloadsResumeFunction() {} ExtensionFunction::ResponseAction DownloadsResumeFunction::Run() { std::unique_ptr<downloads::Resume::Params> params( - downloads::Resume::Params::Create(*args_)); + downloads::Resume::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = GetDownload( browser_context(), include_incognito_information(), params->download_id); @@ -1195,7 +1198,7 @@ DownloadsCancelFunction::~DownloadsCancelFunction() {} ExtensionFunction::ResponseAction DownloadsCancelFunction::Run() { std::unique_ptr<downloads::Resume::Params> params( - downloads::Resume::Params::Create(*args_)); + downloads::Resume::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = GetDownload( browser_context(), include_incognito_information(), params->download_id); @@ -1213,7 +1216,7 @@ DownloadsEraseFunction::~DownloadsEraseFunction() {} ExtensionFunction::ResponseAction DownloadsEraseFunction::Run() { std::unique_ptr<downloads::Erase::Params> params( - downloads::Erase::Params::Create(*args_)); + downloads::Erase::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadManager* manager = NULL; DownloadManager* incognito_manager = NULL; @@ -1227,7 +1230,7 @@ ExtensionFunction::ResponseAction DownloadsEraseFunction::Run() { std::unique_ptr<base::ListValue> json_results(new base::ListValue()); for (DownloadManager::DownloadVector::const_iterator it = results.begin(); it != results.end(); ++it) { - json_results->AppendInteger(static_cast<int>((*it)->GetId())); + json_results->Append(static_cast<int>((*it)->GetId())); (*it)->Remove(); } RecordApiFunctions(DOWNLOADS_FUNCTION_ERASE); @@ -1241,7 +1244,7 @@ DownloadsRemoveFileFunction::~DownloadsRemoveFileFunction() {} ExtensionFunction::ResponseAction DownloadsRemoveFileFunction::Run() { std::unique_ptr<downloads::RemoveFile::Params> params( - downloads::RemoveFile::Params::Create(*args_)); + downloads::RemoveFile::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = GetDownload( browser_context(), include_incognito_information(), params->download_id); @@ -1276,7 +1279,7 @@ DownloadsAcceptDangerFunction::OnPromptCreatedCallback* ExtensionFunction::ResponseAction DownloadsAcceptDangerFunction::Run() { std::unique_ptr<downloads::AcceptDanger::Params> params( - downloads::AcceptDanger::Params::Create(*args_)); + downloads::AcceptDanger::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); PromptOrWait(params->download_id, 10); return RespondLater(); @@ -1304,7 +1307,7 @@ void DownloadsAcceptDangerFunction::PromptOrWait(int download_id, int retries) { FROM_HERE, base::BindOnce(&DownloadsAcceptDangerFunction::PromptOrWait, this, download_id, retries - 1), - base::TimeDelta::FromMilliseconds(100)); + base::Milliseconds(100)); return; } Respond(Error(download_extension_errors::kInvisibleContext)); @@ -1355,7 +1358,7 @@ DownloadsShowFunction::~DownloadsShowFunction() {} ExtensionFunction::ResponseAction DownloadsShowFunction::Run() { std::unique_ptr<downloads::Show::Params> params( - downloads::Show::Params::Create(*args_)); + downloads::Show::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = GetDownload( browser_context(), include_incognito_information(), params->download_id); @@ -1393,7 +1396,7 @@ DownloadsOpenFunction::~DownloadsOpenFunction() {} ExtensionFunction::ResponseAction DownloadsOpenFunction::Run() { std::unique_ptr<downloads::Open::Params> params( - downloads::Open::Params::Create(*args_)); + downloads::Open::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); DownloadItem* download_item = GetDownload( browser_context(), include_incognito_information(), params->download_id); @@ -1463,7 +1466,7 @@ DownloadsSetShelfEnabledFunction::~DownloadsSetShelfEnabledFunction() {} ExtensionFunction::ResponseAction DownloadsSetShelfEnabledFunction::Run() { std::unique_ptr<downloads::SetShelfEnabled::Params> params( - downloads::SetShelfEnabled::Params::Create(*args_)); + downloads::SetShelfEnabled::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); // TODO(devlin): Solve this with the feature system. if (!extension()->permissions_data()->HasAPIPermission( @@ -1527,7 +1530,7 @@ void DownloadsGetFileIconFunction::SetIconExtractorForTesting( ExtensionFunction::ResponseAction DownloadsGetFileIconFunction::Run() { std::unique_ptr<downloads::GetFileIcon::Params> params( - downloads::GetFileIcon::Params::Create(*args_)); + downloads::GetFileIcon::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); const downloads::GetFileIconOptions* options = params->options.get(); int icon_size = kDefaultIconSize; diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h index 38fdac1f080..1fb7d5eaf01 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h @@ -74,6 +74,9 @@ class DownloadedByExtension : public base::SupportsUserData::Data { const std::string& id, const std::string& name); + DownloadedByExtension(const DownloadedByExtension&) = delete; + DownloadedByExtension& operator=(const DownloadedByExtension&) = delete; + const std::string& id() const { return id_; } const std::string& name() const { return name_; } @@ -82,14 +85,17 @@ class DownloadedByExtension : public base::SupportsUserData::Data { std::string id_; std::string name_; - - DISALLOW_COPY_AND_ASSIGN(DownloadedByExtension); }; class DownloadsDownloadFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.download", DOWNLOADS_DOWNLOAD) DownloadsDownloadFunction(); + + DownloadsDownloadFunction(const DownloadsDownloadFunction&) = delete; + DownloadsDownloadFunction& operator=(const DownloadsDownloadFunction&) = + delete; + ResponseAction Run() override; protected: @@ -101,79 +107,87 @@ class DownloadsDownloadFunction : public ExtensionFunction { creator_conflict_action, download::DownloadItem* item, download::DownloadInterruptReason interrupt_reason); - - DISALLOW_COPY_AND_ASSIGN(DownloadsDownloadFunction); }; class DownloadsSearchFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.search", DOWNLOADS_SEARCH) DownloadsSearchFunction(); + + DownloadsSearchFunction(const DownloadsSearchFunction&) = delete; + DownloadsSearchFunction& operator=(const DownloadsSearchFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsSearchFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsSearchFunction); }; class DownloadsPauseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.pause", DOWNLOADS_PAUSE) DownloadsPauseFunction(); + + DownloadsPauseFunction(const DownloadsPauseFunction&) = delete; + DownloadsPauseFunction& operator=(const DownloadsPauseFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsPauseFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsPauseFunction); }; class DownloadsResumeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.resume", DOWNLOADS_RESUME) DownloadsResumeFunction(); + + DownloadsResumeFunction(const DownloadsResumeFunction&) = delete; + DownloadsResumeFunction& operator=(const DownloadsResumeFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsResumeFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsResumeFunction); }; class DownloadsCancelFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.cancel", DOWNLOADS_CANCEL) DownloadsCancelFunction(); + + DownloadsCancelFunction(const DownloadsCancelFunction&) = delete; + DownloadsCancelFunction& operator=(const DownloadsCancelFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsCancelFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsCancelFunction); }; class DownloadsEraseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.erase", DOWNLOADS_ERASE) DownloadsEraseFunction(); + + DownloadsEraseFunction(const DownloadsEraseFunction&) = delete; + DownloadsEraseFunction& operator=(const DownloadsEraseFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsEraseFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsEraseFunction); }; class DownloadsRemoveFileFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.removeFile", DOWNLOADS_REMOVEFILE) DownloadsRemoveFileFunction(); + + DownloadsRemoveFileFunction(const DownloadsRemoveFileFunction&) = delete; + DownloadsRemoveFileFunction& operator=(const DownloadsRemoveFileFunction&) = + delete; + ResponseAction Run() override; protected: @@ -181,8 +195,6 @@ class DownloadsRemoveFileFunction : public ExtensionFunction { private: void Done(bool success); - - DISALLOW_COPY_AND_ASSIGN(DownloadsRemoveFileFunction); }; class DownloadsAcceptDangerFunction : public ExtensionFunction { @@ -196,6 +208,11 @@ class DownloadsAcceptDangerFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("downloads.acceptDanger", DOWNLOADS_ACCEPTDANGER) DownloadsAcceptDangerFunction(); + + DownloadsAcceptDangerFunction(const DownloadsAcceptDangerFunction&) = delete; + DownloadsAcceptDangerFunction& operator=( + const DownloadsAcceptDangerFunction&) = delete; + ResponseAction Run() override; protected: @@ -207,20 +224,20 @@ class DownloadsAcceptDangerFunction : public ExtensionFunction { void PromptOrWait(int download_id, int retries); static OnPromptCreatedCallback* on_prompt_created_; - DISALLOW_COPY_AND_ASSIGN(DownloadsAcceptDangerFunction); }; class DownloadsShowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.show", DOWNLOADS_SHOW) DownloadsShowFunction(); + + DownloadsShowFunction(const DownloadsShowFunction&) = delete; + DownloadsShowFunction& operator=(const DownloadsShowFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsShowFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsShowFunction); }; class DownloadsShowDefaultFolderFunction : public ExtensionFunction { @@ -228,19 +245,26 @@ class DownloadsShowDefaultFolderFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION( "downloads.showDefaultFolder", DOWNLOADS_SHOWDEFAULTFOLDER) DownloadsShowDefaultFolderFunction(); + + DownloadsShowDefaultFolderFunction( + const DownloadsShowDefaultFolderFunction&) = delete; + DownloadsShowDefaultFolderFunction& operator=( + const DownloadsShowDefaultFolderFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsShowDefaultFolderFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsShowDefaultFolderFunction); }; class DownloadsOpenFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.open", DOWNLOADS_OPEN) DownloadsOpenFunction(); + + DownloadsOpenFunction(const DownloadsOpenFunction&) = delete; + DownloadsOpenFunction& operator=(const DownloadsOpenFunction&) = delete; + ResponseAction Run() override; typedef base::OnceCallback<void(DownloadOpenPrompt*)> OnPromptCreatedCallback; @@ -256,8 +280,6 @@ class DownloadsOpenFunction : public ExtensionFunction { void OpenPromptDone(int download_id, bool accept); static OnPromptCreatedCallback* on_prompt_created_cb_; - - DISALLOW_COPY_AND_ASSIGN(DownloadsOpenFunction); }; class DownloadsSetShelfEnabledFunction : public ExtensionFunction { @@ -265,19 +287,27 @@ class DownloadsSetShelfEnabledFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("downloads.setShelfEnabled", DOWNLOADS_SETSHELFENABLED) DownloadsSetShelfEnabledFunction(); + + DownloadsSetShelfEnabledFunction(const DownloadsSetShelfEnabledFunction&) = + delete; + DownloadsSetShelfEnabledFunction& operator=( + const DownloadsSetShelfEnabledFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsSetShelfEnabledFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsSetShelfEnabledFunction); }; class DownloadsGetFileIconFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.getFileIcon", DOWNLOADS_GETFILEICON) DownloadsGetFileIconFunction(); + + DownloadsGetFileIconFunction(const DownloadsGetFileIconFunction&) = delete; + DownloadsGetFileIconFunction& operator=(const DownloadsGetFileIconFunction&) = + delete; + ResponseAction Run() override; void SetIconExtractorForTesting(DownloadFileIconExtractor* extractor); @@ -288,7 +318,6 @@ class DownloadsGetFileIconFunction : public ExtensionFunction { void OnIconURLExtracted(const std::string& url); base::FilePath path_; std::unique_ptr<DownloadFileIconExtractor> icon_extractor_; - DISALLOW_COPY_AND_ASSIGN(DownloadsGetFileIconFunction); }; // Observes a single DownloadManager and many DownloadItems and dispatches @@ -337,6 +366,11 @@ class ExtensionDownloadsEventRouter explicit ExtensionDownloadsEventRouter( Profile* profile, content::DownloadManager* manager); + + ExtensionDownloadsEventRouter(const ExtensionDownloadsEventRouter&) = delete; + ExtensionDownloadsEventRouter& operator=( + const ExtensionDownloadsEventRouter&) = delete; + ~ExtensionDownloadsEventRouter() override; void SetShelfEnabled(const extensions::Extension* extension, bool enabled); @@ -389,8 +423,6 @@ class ExtensionDownloadsEventRouter base::ScopedObservation<extensions::ExtensionRegistry, extensions::ExtensionRegistryObserver> extension_registry_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(ExtensionDownloadsEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc index ca243f0254f..fcaf58e68cd 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc @@ -67,10 +67,12 @@ #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "net/test/embedded_test_server/http_response.h" #include "services/network/public/cpp/features.h" #include "storage/browser/file_system/file_system_context.h" #include "storage/browser/file_system/file_system_operation_runner.h" #include "storage/browser/file_system/file_system_url.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/page_transition_types.h" #include "url/origin.h" @@ -119,6 +121,9 @@ class DownloadsEventsListener : public EventRouter::TestObserver { explicit DownloadsEventsListener(Profile* profile) : waiting_(false), profile_(profile) {} + DownloadsEventsListener(const DownloadsEventsListener&) = delete; + DownloadsEventsListener& operator=(const DownloadsEventsListener&) = delete; + ~DownloadsEventsListener() override = default; void ClearEvents() { events_.clear(); } @@ -134,6 +139,9 @@ class DownloadsEventsListener : public EventRouter::TestObserver { args_(args.Clone()), caught_(caught) {} + Event(const Event&) = delete; + Event& operator=(const Event&) = delete; + const base::Time& caught() { return caught_; } bool Satisfies(const Event& other) const { @@ -185,8 +193,6 @@ class DownloadsEventsListener : public EventRouter::TestObserver { std::string json_args_; base::Value args_; base::Time caught_; - - DISALLOW_COPY_AND_ASSIGN(Event); }; // extensions::EventRouter::TestObserver: @@ -251,8 +257,6 @@ class DownloadsEventsListener : public EventRouter::TestObserver { std::unique_ptr<Event> waiting_for_; base::circular_deque<std::unique_ptr<Event>> events_; Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(DownloadsEventsListener); }; // Object waiting for a download open event. @@ -262,6 +266,9 @@ class DownloadOpenObserver : public download::DownloadItem::Observer { open_observation_.Observe(item); } + DownloadOpenObserver(const DownloadOpenObserver&) = delete; + DownloadOpenObserver& operator=(const DownloadOpenObserver&) = delete; + ~DownloadOpenObserver() override = default; void WaitForEvent() { @@ -290,8 +297,6 @@ class DownloadOpenObserver : public download::DownloadItem::Observer { open_observation_{this}; download::DownloadItem* item_; base::OnceClosure completion_closure_; - - DISALLOW_COPY_AND_ASSIGN(DownloadOpenObserver); }; } // namespace @@ -303,6 +308,9 @@ class DownloadExtensionTest : public ExtensionApiTest { incognito_browser_(nullptr), current_browser_(nullptr) {} + DownloadExtensionTest(const DownloadExtensionTest&) = delete; + DownloadExtensionTest& operator=(const DownloadExtensionTest&) = delete; + protected: // Used with CreateHistoryDownloads struct HistoryDownloadInfo { @@ -688,8 +696,6 @@ class DownloadExtensionTest : public ExtensionApiTest { std::unique_ptr<net::test_server::ControllableHttpResponse> first_download_; std::unique_ptr<net::test_server::ControllableHttpResponse> second_download_; - - DISALLOW_COPY_AND_ASSIGN(DownloadExtensionTest); }; namespace { @@ -746,6 +752,10 @@ bool ItemNotInProgress(DownloadItem* item) { class ScopedCancellingItem { public: explicit ScopedCancellingItem(DownloadItem* item) : item_(item) {} + + ScopedCancellingItem(const ScopedCancellingItem&) = delete; + ScopedCancellingItem& operator=(const ScopedCancellingItem&) = delete; + ~ScopedCancellingItem() { item_->Cancel(true); content::DownloadUpdatedObserver observer( @@ -755,7 +765,6 @@ class ScopedCancellingItem { DownloadItem* get() { return item_; } private: DownloadItem* item_; - DISALLOW_COPY_AND_ASSIGN(ScopedCancellingItem); }; // Cancels all the underlying DownloadItems when the ScopedItemVectorCanceller @@ -766,6 +775,11 @@ class ScopedItemVectorCanceller { explicit ScopedItemVectorCanceller(DownloadManager::DownloadVector* items) : items_(items) { } + + ScopedItemVectorCanceller(const ScopedItemVectorCanceller&) = delete; + ScopedItemVectorCanceller& operator=(const ScopedItemVectorCanceller&) = + delete; + ~ScopedItemVectorCanceller() { for (DownloadManager::DownloadVector::const_iterator item = items_->begin(); item != items_->end(); ++item) { @@ -779,7 +793,6 @@ class ScopedItemVectorCanceller { private: DownloadManager::DownloadVector* items_; - DISALLOW_COPY_AND_ASSIGN(ScopedItemVectorCanceller); }; // Writes an HTML5 file so that it can be downloaded. @@ -843,14 +856,17 @@ class JustInProgressDownloadObserver : content::DownloadTestObserverInProgress(download_manager, wait_count) { } + JustInProgressDownloadObserver(const JustInProgressDownloadObserver&) = + delete; + JustInProgressDownloadObserver& operator=( + const JustInProgressDownloadObserver&) = delete; + ~JustInProgressDownloadObserver() override {} private: bool IsDownloadInFinalState(DownloadItem* item) override { return item->GetState() == DownloadItem::IN_PROGRESS; } - - DISALLOW_COPY_AND_ASSIGN(JustInProgressDownloadObserver); }; bool ItemIsInterrupted(DownloadItem* item) { @@ -1181,9 +1197,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, std::unique_ptr<base::Value> result( RunFunctionAndReturnResult(new DownloadsSearchFunction(), "[{}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); } // Test that file existence check should be performed after search. @@ -1201,9 +1216,9 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, FileExistenceCheckAfterSearch) { std::unique_ptr<base::Value> result( RunFunctionAndReturnResult(new DownloadsSearchFunction(), "[{}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = nullptr; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); + // Check file removal update will eventually come. WaitForEvent() will // immediately return if the file is already removed. content::DownloadUpdatedObserver( @@ -1248,14 +1263,13 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{\"filenameRegex\": \"foobar\"}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); - base::DictionaryValue* item_value = NULL; - ASSERT_TRUE(result_list->GetDictionary(0, &item_value)); - int item_id = -1; - ASSERT_TRUE(item_value->GetInteger("id", &item_id)); - ASSERT_EQ(all_downloads[0]->GetId(), static_cast<uint32_t>(item_id)); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); + const base::Value& item_value = result->GetList()[0]; + ASSERT_TRUE(item_value.is_dict()); + absl::optional<int> item_id = item_value.FindIntKey("id"); + ASSERT_TRUE(item_id); + ASSERT_EQ(all_downloads[0]->GetId(), static_cast<uint32_t>(*item_id)); } // Test the |id| parameter for search(). @@ -1269,14 +1283,13 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchId) { new DownloadsSearchFunction(), base::StringPrintf("[{\"id\": %u}]", items[0]->GetId()))); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); - base::DictionaryValue* item_value = NULL; - ASSERT_TRUE(result_list->GetDictionary(0, &item_value)); - int item_id = -1; - ASSERT_TRUE(item_value->GetInteger("id", &item_id)); - ASSERT_EQ(items[0]->GetId(), static_cast<uint32_t>(item_id)); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); + const base::Value& item_value = result->GetList()[0]; + ASSERT_TRUE(item_value.is_dict()); + absl::optional<int> item_id = item_value.FindIntKey("id"); + ASSERT_TRUE(item_id); + ASSERT_EQ(items[0]->GetId(), static_cast<uint32_t>(*item_id)); } // Test specifying both the |id| and |filename| parameters for search(). @@ -1291,9 +1304,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, RunFunctionAndReturnResult(new DownloadsSearchFunction(), "[{\"id\": 0, \"filename\": \"foobar\"}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(0UL, result_list->GetSize()); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(0UL, result->GetList().size()); } // Test a single |orderBy| parameter for search(). @@ -1311,19 +1323,19 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{\"orderBy\": [\"filename\"]}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(2UL, result_list->GetSize()); - base::DictionaryValue* item0_value = NULL; - base::DictionaryValue* item1_value = NULL; - ASSERT_TRUE(result_list->GetDictionary(0, &item0_value)); - ASSERT_TRUE(result_list->GetDictionary(1, &item1_value)); - std::string item0_name, item1_name; - ASSERT_TRUE(item0_value->GetString("filename", &item0_name)); - ASSERT_TRUE(item1_value->GetString("filename", &item1_name)); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(2UL, result->GetList().size()); + const base::Value& item0_value = result->GetList()[0]; + const base::Value& item1_value = result->GetList()[1]; + ASSERT_TRUE(item0_value.is_dict()); + ASSERT_TRUE(item1_value.is_dict()); + const std::string* item0_name = item0_value.FindStringKey("filename"); + const std::string* item1_name = item1_value.FindStringKey("filename"); + ASSERT_TRUE(item0_name); + ASSERT_TRUE(item1_name); ASSERT_GT(items[0]->GetTargetFilePath().value(), items[1]->GetTargetFilePath().value()); - ASSERT_LT(item0_name, item1_name); + ASSERT_LT(*item0_name, *item1_name); } // Test specifying an empty |orderBy| parameter for search(). @@ -1341,16 +1353,16 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{\"orderBy\": []}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(2UL, result_list->GetSize()); - base::DictionaryValue* item0_value = NULL; - base::DictionaryValue* item1_value = NULL; - ASSERT_TRUE(result_list->GetDictionary(0, &item0_value)); - ASSERT_TRUE(result_list->GetDictionary(1, &item1_value)); - std::string item0_name, item1_name; - ASSERT_TRUE(item0_value->GetString("filename", &item0_name)); - ASSERT_TRUE(item1_value->GetString("filename", &item1_name)); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(2UL, result->GetList().size()); + const base::Value& item0_value = result->GetList()[0]; + const base::Value& item1_value = result->GetList()[1]; + ASSERT_TRUE(item0_value.is_dict()); + ASSERT_TRUE(item1_value.is_dict()); + const std::string* item0_name = item0_value.FindStringKey("filename"); + const std::string* item1_name = item1_value.FindStringKey("filename"); + ASSERT_TRUE(item0_name); + ASSERT_TRUE(item1_name); ASSERT_GT(items[0]->GetTargetFilePath().value(), items[1]->GetTargetFilePath().value()); // The order of results when orderBy is empty is unspecified. When there are @@ -1375,9 +1387,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{\"danger\": \"content\"}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); } // Test the |state| option for search(). @@ -1392,9 +1403,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{\"state\": \"in_progress\"}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); } // Test the |limit| option for search(). @@ -1407,9 +1417,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{\"limit\": 1}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); } // Test invalid search parameters. @@ -1452,14 +1461,13 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, "\"orderBy\": [\"filename\"], " "\"limit\": 1}]")); ASSERT_TRUE(result.get()); - base::ListValue* result_list = NULL; - ASSERT_TRUE(result->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); - base::DictionaryValue* item_value = NULL; - ASSERT_TRUE(result_list->GetDictionary(0, &item_value)); - std::string item_name; - ASSERT_TRUE(item_value->GetString("filename", &item_name)); - ASSERT_EQ(items[2]->GetTargetFilePath().AsUTF8Unsafe(), item_name); + ASSERT_TRUE(result->is_list()); + ASSERT_EQ(1UL, result->GetList().size()); + const base::Value& item_value = result->GetList()[0]; + ASSERT_TRUE(item_value.is_dict()); + const std::string* item_name = item_value.FindStringKey("filename"); + ASSERT_TRUE(item_name); + ASSERT_EQ(items[2]->GetTargetFilePath().AsUTF8Unsafe(), *item_name); } // Test that incognito downloads are only visible in incognito contexts, and @@ -1470,13 +1478,7 @@ IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito) { std::unique_ptr<base::Value> result_value; - base::ListValue* result_list = NULL; - base::DictionaryValue* result_dict = NULL; - std::string filename; - bool is_incognito = false; std::string error; - std::string on_item_arg; - std::string off_item_arg; std::string result_string; // Set up one on-record item and one off-record item. @@ -1486,12 +1488,12 @@ IN_PROC_BROWSER_TEST_F( GoOffTheRecord(); DownloadItem* off_item = CreateFirstSlowTestDownload(); ASSERT_TRUE(off_item); - off_item_arg = DownloadItemIdAsArgList(off_item); + const std::string off_item_arg = DownloadItemIdAsArgList(off_item); GoOnTheRecord(); DownloadItem* on_item = CreateSecondSlowTestDownload(); ASSERT_TRUE(on_item); - on_item_arg = DownloadItemIdAsArgList(on_item); + const std::string on_item_arg = DownloadItemIdAsArgList(on_item); ASSERT_TRUE(on_item->GetTargetFilePath() != off_item->GetTargetFilePath()); // Extensions running in the incognito window should have access to both @@ -1500,20 +1502,30 @@ IN_PROC_BROWSER_TEST_F( result_value.reset(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{}]")); ASSERT_TRUE(result_value.get()); - ASSERT_TRUE(result_value->GetAsList(&result_list)); - ASSERT_EQ(2UL, result_list->GetSize()); - ASSERT_TRUE(result_list->GetDictionary(0, &result_dict)); - ASSERT_TRUE(result_dict->GetString("filename", &filename)); - ASSERT_TRUE(result_dict->GetBoolean("incognito", &is_incognito)); - EXPECT_TRUE(on_item->GetTargetFilePath() == - base::FilePath::FromUTF8Unsafe(filename)); - EXPECT_FALSE(is_incognito); - ASSERT_TRUE(result_list->GetDictionary(1, &result_dict)); - ASSERT_TRUE(result_dict->GetString("filename", &filename)); - ASSERT_TRUE(result_dict->GetBoolean("incognito", &is_incognito)); - EXPECT_TRUE(off_item->GetTargetFilePath() == - base::FilePath::FromUTF8Unsafe(filename)); - EXPECT_TRUE(is_incognito); + ASSERT_TRUE(result_value->is_list()); + ASSERT_EQ(2UL, result_value->GetList().size()); + { + const base::Value& result_dict = result_value->GetList()[0]; + ASSERT_TRUE(result_dict.is_dict()); + const std::string* filename = result_dict.FindStringKey("filename"); + ASSERT_TRUE(filename); + absl::optional<bool> is_incognito = result_dict.FindBoolKey("incognito"); + ASSERT_TRUE(is_incognito.has_value()); + EXPECT_TRUE(on_item->GetTargetFilePath() == + base::FilePath::FromUTF8Unsafe(*filename)); + EXPECT_FALSE(is_incognito.value()); + } + { + const base::Value& result_dict = result_value->GetList()[1]; + ASSERT_TRUE(result_dict.is_dict()); + const std::string* filename = result_dict.FindStringKey("filename"); + ASSERT_TRUE(filename); + absl::optional<bool> is_incognito = result_dict.FindBoolKey("incognito"); + ASSERT_TRUE(is_incognito.has_value()); + EXPECT_TRUE(off_item->GetTargetFilePath() == + base::FilePath::FromUTF8Unsafe(*filename)); + EXPECT_TRUE(is_incognito.value()); + } // Extensions running in the on-record window should have access only to the // on-record item. @@ -1521,14 +1533,19 @@ IN_PROC_BROWSER_TEST_F( result_value.reset(RunFunctionAndReturnResult( new DownloadsSearchFunction(), "[{}]")); ASSERT_TRUE(result_value.get()); - ASSERT_TRUE(result_value->GetAsList(&result_list)); - ASSERT_EQ(1UL, result_list->GetSize()); - ASSERT_TRUE(result_list->GetDictionary(0, &result_dict)); - ASSERT_TRUE(result_dict->GetString("filename", &filename)); - EXPECT_TRUE(on_item->GetTargetFilePath() == - base::FilePath::FromUTF8Unsafe(filename)); - ASSERT_TRUE(result_dict->GetBoolean("incognito", &is_incognito)); - EXPECT_FALSE(is_incognito); + ASSERT_TRUE(result_value->is_list()); + ASSERT_EQ(1UL, result_value->GetList().size()); + { + const base::Value& result_dict = result_value->GetList()[0]; + ASSERT_TRUE(result_dict.is_dict()); + const std::string* filename = result_dict.FindStringKey("filename"); + ASSERT_TRUE(filename); + EXPECT_TRUE(on_item->GetTargetFilePath() == + base::FilePath::FromUTF8Unsafe(*filename)); + absl::optional<bool> is_incognito = result_dict.FindBoolKey("incognito"); + ASSERT_TRUE(is_incognito.has_value()); + EXPECT_FALSE(is_incognito.value()); + } // Pausing/Resuming the off-record item while on the record should return an // error. Cancelling "non-existent" downloads is not an error. @@ -1598,10 +1615,18 @@ IN_PROC_BROWSER_TEST_F( EXPECT_STREQ(errors::kNotResumable, error.c_str()); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_Basic \ + DISABLED_DownloadExtensionTest_Download_Basic +#else +#define MAYBE_DownloadExtensionTest_Download_Basic \ + DownloadExtensionTest_Download_Basic +#endif // Test that we can start a download and that the correct sequence of events is // fired for it. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Basic) { + MAYBE_DownloadExtensionTest_Download_Basic) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = embedded_test_server()->GetURL("/slow?0").spec(); @@ -1646,10 +1671,18 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_Redirect \ + DISABLED_DownloadExtensionTest_Download_Redirect +#else +#define MAYBE_DownloadExtensionTest_Download_Redirect \ + DownloadExtensionTest_Download_Redirect +#endif // Test that we can start a download that gets redirected and that the correct // sequence of events is fired for it. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Redirect) { + MAYBE_DownloadExtensionTest_Download_Redirect) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); GURL download_final_url(embedded_test_server()->GetURL("/slow?0")); @@ -1699,8 +1732,16 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, // Test that we can start a download from an incognito context, and that the // download knows that it's incognito. +#if defined(OS_WIN) +// TODO(https://crbug.com/1245173) Flaky on Win7 +#define MAYBE_DownloadExtensionTest_Download_Incognito \ + DISABLED_DownloadExtensionTest_Download_Incognito +#else +#define MAYBE_DownloadExtensionTest_Download_Incognito \ + DownloadExtensionTest_Download_Incognito +#endif IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Incognito) { + MAYBE_DownloadExtensionTest_Download_Incognito) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); GoOffTheRecord(); @@ -1747,38 +1788,43 @@ namespace { class CustomResponse : public net::test_server::HttpResponse { public: - CustomResponse(net::test_server::SendCompleteCallback* callback, + CustomResponse(base::OnceClosure* callback, base::TaskRunner** task_runner, bool first_request) : callback_(callback), task_runner_(task_runner), first_request_(first_request) {} + + CustomResponse(const CustomResponse&) = delete; + CustomResponse& operator=(const CustomResponse&) = delete; + ~CustomResponse() override {} - void SendResponse(const net::test_server::SendBytesCallback& send, - net::test_server::SendCompleteCallback done) override { - std::string response( - "HTTP/1.1 200 OK\r\n" - "Content-type: application/octet-stream\r\n" - "Cache-Control: max-age=0\r\n" - "\r\n"); - response += std::string(kDownloadSize, '*'); + void SendResponse( + base::WeakPtr<net::test_server::HttpResponseDelegate> delegate) override { + base::StringPairs headers = { + //"HTTP/1.1 200 OK\r\n" + {"Content-type", "application/octet-stream"}, + {"Cache-Control", "max-age=0"}, + }; + std::string contents = std::string(kDownloadSize, '*'); if (first_request_) { - *callback_ = std::move(done); + *callback_ = base::BindOnce( + &net::test_server::HttpResponseDelegate::FinishResponse, delegate); *task_runner_ = base::ThreadTaskRunnerHandle::Get().get(); - send.Run(response, base::DoNothing()); + delegate->SendResponseHeaders(net::HTTP_OK, "OK", headers); + delegate->SendContents(contents); } else { - send.Run(response, std::move(done)); + delegate->SendHeadersContentAndFinish(net::HTTP_OK, "OK", headers, + contents); } } private: - net::test_server::SendCompleteCallback* callback_; + base::OnceClosure* callback_; base::TaskRunner** task_runner_; bool first_request_; - - DISALLOW_COPY_AND_ASSIGN(CustomResponse); }; } // namespace @@ -1789,7 +1835,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadItem* item = nullptr; - net::test_server::SendCompleteCallback complete_callback; + base::OnceClosure complete_callback; base::TaskRunner* embedded_test_server_io_runner = nullptr; const char kThirdDownloadUrl[] = "/download3"; bool first_request = true; @@ -2049,9 +2095,17 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, " \"url\": \"javascript:return false;\"}]")); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_URLFragment \ + DISABLED_DownloadExtensionTest_Download_URLFragment +#else +#define MAYBE_DownloadExtensionTest_Download_URLFragment \ + DownloadExtensionTest_Download_URLFragment +#endif // Valid URLs plus fragments are still valid URLs. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_URLFragment) { + MAYBE_DownloadExtensionTest_Download_URLFragment) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = @@ -2094,8 +2148,17 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, } // conflictAction may be specified without filename. +#if defined(OS_WIN) +// TODO(https://crbug.com/1245173) Flaky on Win7 +#define MAYBE_DownloadExtensionTest_Download_ConflictAction \ + DISABLED_DownloadExtensionTest_Download_ConflictAction +#else +#define MAYBE_DownloadExtensionTest_Download_ConflictAction \ + DownloadExtensionTest_Download_ConflictAction +#endif + IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_ConflictAction) { + MAYBE_DownloadExtensionTest_Download_ConflictAction) { static char kFilename[] = "download.txt"; LoadExtension("downloads_split"); std::string download_url = "data:text/plain,hello"; @@ -2173,9 +2236,17 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_DataURL \ + DISABLED_DownloadExtensionTest_Download_DataURL +#else +#define MAYBE_DownloadExtensionTest_Download_DataURL \ + DownloadExtensionTest_Download_DataURL +#endif // Valid data URLs are valid URLs. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_DataURL) { + MAYBE_DownloadExtensionTest_Download_DataURL) { LoadExtension("downloads_split"); std::string download_url = "data:text/plain,hello"; GoOnTheRecord(); @@ -2308,9 +2379,17 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, download_url.c_str()))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_Headers \ + DISABLED_DownloadExtensionTest_Download_Headers +#else +#define MAYBE_DownloadExtensionTest_Download_Headers \ + DownloadExtensionTest_Download_Headers +#endif // Test that DownloadsDownloadFunction propagates |headers| to the URLRequest. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Headers) { + MAYBE_DownloadExtensionTest_Download_Headers) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = @@ -2366,8 +2445,16 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, // chrome fails to propagate them back to the server. This tests both that // testserver.py does not succeed when it should fail as well as how the // downloads extension api exposes the failure to extensions. +// TODO(https://crbug.com/1249757): DownloadExtensionTest's are flaky +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_Headers_Fail \ + DISABLED_DownloadExtensionTest_Download_Headers_Fail +#else +#define MAYBE_DownloadExtensionTest_Download_Headers_Fail \ + DownloadExtensionTest_Download_Headers_Fail +#endif IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Headers_Fail) { + MAYBE_DownloadExtensionTest_Download_Headers_Fail) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = @@ -2451,8 +2538,16 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, // Test that DownloadsDownloadFunction propagates the |method| and |body| // parameters to the URLRequest. +#if defined(OS_WIN) +// TODO(https://crbug.com/1245173) Flaky on Win7 +#define MAYBE_DownloadExtensionTest_Download_Post \ + DISABLED_DownloadExtensionTest_Download_Post +#else +#define MAYBE_DownloadExtensionTest_Download_Post \ + DownloadExtensionTest_Download_Post +#endif IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Post) { + MAYBE_DownloadExtensionTest_Download_Post) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = embedded_test_server() @@ -2507,8 +2602,16 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, // server. This tests both that testserver.py does not succeed when it should // fail, and this tests how the downloads extension api exposes the failure to // extensions. +// TODO(https://crbug.com/1249757): DownloadExtensionTest's are flaky +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_Post_Get \ + DISABLED_DownloadExtensionTest_Download_Post_Get +#else +#define MAYBE_DownloadExtensionTest_Download_Post_Get \ + DownloadExtensionTest_Download_Post_Get +#endif IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Post_Get) { + MAYBE_DownloadExtensionTest_Download_Post_Get) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = embedded_test_server() @@ -2548,8 +2651,16 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, // server. This tests both that testserver.py does not succeed when it should // fail, and this tests how the downloads extension api exposes the failure to // extensions. +// TODO(https://crbug.com/1249757): DownloadExtensionTest's are flaky +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_Download_Post_NoBody \ + DISABLED_DownloadExtensionTest_Download_Post_NoBody +#else +#define MAYBE_DownloadExtensionTest_Download_Post_NoBody \ + DownloadExtensionTest_Download_Post_NoBody +#endif IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_Download_Post_NoBody) { + MAYBE_DownloadExtensionTest_Download_Post_NoBody) { LoadExtension("downloads_split"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = embedded_test_server() @@ -2630,8 +2741,9 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, result_id))); } -// flaky on mac: crbug.com/392288 -#if defined(OS_MAC) +// TODO(https://crbug.com/392288): Flaky on macOS +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_DownloadExtensionTest_Download_FileSystemURL \ DISABLED_DownloadExtensionTest_Download_FileSystemURL #else @@ -2701,8 +2813,17 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, EXPECT_STREQ(kPayloadData, disk_data.c_str()); } -IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_NoChange) { +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_NoChange \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_NoChange +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_NoChange \ + DownloadExtensionTest_OnDeterminingFilename_NoChange +#endif +IN_PROC_BROWSER_TEST_F( + DownloadExtensionTest, + MAYBE_DownloadExtensionTest_OnDeterminingFilename_NoChange) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -2825,8 +2946,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } -IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_Twice) { +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_Twice \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_Twice +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_Twice \ + DownloadExtensionTest_OnDeterminingFilename_Twice +#endif +IN_PROC_BROWSER_TEST_F( + DownloadExtensionTest, + MAYBE_DownloadExtensionTest_OnDeterminingFilename_Twice) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -2939,11 +3069,19 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, EXPECT_FALSE(determine_result.get()); // No return value. } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_DangerousOverride \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_DangerousOverride +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_DangerousOverride \ + DownloadExtensionTest_OnDeterminingFilename_DangerousOverride +#endif // Tests that overriding a safe file extension to a dangerous extension will not // trigger the dangerous prompt and will not change the extension. IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_DangerousOverride) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_DangerousOverride) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3072,9 +3210,17 @@ IN_PROC_BROWSER_TEST_F( item->GetTargetFilePath()); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid \ + DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3134,9 +3280,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_IllegalFilename \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_IllegalFilename +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_IllegalFilename \ + DownloadExtensionTest_OnDeterminingFilename_IllegalFilename +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_IllegalFilename) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_IllegalFilename) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3196,9 +3350,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension \ + DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3327,9 +3489,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid \ + DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3389,9 +3559,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid \ + DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid) { ASSERT_TRUE(StartEmbeddedTestServer()); GoOnTheRecord(); LoadExtension("downloads_split"); @@ -3451,9 +3629,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid \ + DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3578,10 +3764,18 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_Overwrite \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_Overwrite +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_Overwrite \ + DownloadExtensionTest_OnDeterminingFilename_Overwrite +#endif // conflictAction may be specified without filename. IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_Overwrite) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_Overwrite) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3695,9 +3889,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_Override \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_Override +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_Override \ + DownloadExtensionTest_OnDeterminingFilename_Override +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_Override) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_Override) { GoOnTheRecord(); LoadExtension("downloads_split"); AddFilenameDeterminer(); @@ -3815,7 +4017,8 @@ IN_PROC_BROWSER_TEST_F( // TODO test precedence rules: install_time -#if defined(OS_MAC) +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_DownloadExtensionTest_OnDeterminingFilename_RemoveFilenameDeterminer \ DISABLED_DownloadExtensionTest_OnDeterminingFilename_RemoveFilenameDeterminer #else @@ -3874,7 +4077,10 @@ IN_PROC_BROWSER_TEST_F( } // This test is flaky on Linux ASan LSan Tests bot. https://crbug.com/1114226 -#if (defined(OS_LINUX) || defined(OS_CHROMEOS)) && defined(ADDRESS_SANITIZER) +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if ((defined(OS_LINUX) || defined(OS_CHROMEOS)) && \ + defined(ADDRESS_SANITIZER)) || \ + defined(OS_WIN) #define MAYBE_DownloadExtensionTest_OnDeterminingFilename_IncognitoSplit \ DISABLED_DownloadExtensionTest_OnDeterminingFilename_IncognitoSplit #else @@ -4021,9 +4227,17 @@ IN_PROC_BROWSER_TEST_F( result_id))); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning \ + DISABLED_DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning +#else +#define MAYBE_DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning \ + DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning +#endif IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, - DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning) { + MAYBE_DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning) { LoadExtension("downloads_spanning"); ASSERT_TRUE(StartEmbeddedTestServer()); std::string download_url = embedded_test_server()->GetURL("/slow?0").spec(); @@ -4376,10 +4590,18 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, observer->WaitForFinished(); } +// TODO(https://crbug.com/1244128): Flaky on Win7 +#if defined(OS_WIN) +#define MAYBE_DownloadExtensionTest_DeleteFileAfterCompletion \ + DISABLED_DownloadExtensionTest_DeleteFileAfterCompletion +#else +#define MAYBE_DownloadExtensionTest_DeleteFileAfterCompletion \ + DownloadExtensionTest_DeleteFileAfterCompletion +#endif // Test that file deletion event is correctly generated after download // completion. IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, - DownloadExtensionTest_DeleteFileAfterCompletion) { + MAYBE_DownloadExtensionTest_DeleteFileAfterCompletion) { ASSERT_TRUE(StartEmbeddedTestServer()); GoOnTheRecord(); LoadExtension("downloads_split"); @@ -4425,10 +4647,11 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, class DownloadsApiTest : public ExtensionApiTest { public: DownloadsApiTest() {} - ~DownloadsApiTest() override {} - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsApiTest); + DownloadsApiTest(const DownloadsApiTest&) = delete; + DownloadsApiTest& operator=(const DownloadsApiTest&) = delete; + + ~DownloadsApiTest() override {} }; @@ -4480,15 +4703,9 @@ TEST(ExtensionDetermineDownloadFilenameInternal, warnings.clear(); ExtensionDownloadsEventRouter::DetermineFilenameInternal( base::FilePath(FILE_PATH_LITERAL("b")), - downloads::FILENAME_CONFLICT_ACTION_PROMPT, - "suggester", - base::Time::Now() - base::TimeDelta::FromDays(1), - "incumbent", - base::Time::Now(), - &winner_id, - &filename, - &conflict_action, - &warnings); + downloads::FILENAME_CONFLICT_ACTION_PROMPT, "suggester", + base::Time::Now() - base::Days(1), "incumbent", base::Time::Now(), + &winner_id, &filename, &conflict_action, &warnings); EXPECT_EQ("incumbent", winner_id); EXPECT_EQ(FILE_PATH_LITERAL("a"), filename.value()); EXPECT_EQ(downloads::FILENAME_CONFLICT_ACTION_OVERWRITE, conflict_action); @@ -4501,15 +4718,9 @@ TEST(ExtensionDetermineDownloadFilenameInternal, warnings.clear(); ExtensionDownloadsEventRouter::DetermineFilenameInternal( base::FilePath(FILE_PATH_LITERAL("b")), - downloads::FILENAME_CONFLICT_ACTION_PROMPT, - "suggester", - base::Time::Now(), - "incumbent", - base::Time::Now() - base::TimeDelta::FromDays(1), - &winner_id, - &filename, - &conflict_action, - &warnings); + downloads::FILENAME_CONFLICT_ACTION_PROMPT, "suggester", + base::Time::Now(), "incumbent", base::Time::Now() - base::Days(1), + &winner_id, &filename, &conflict_action, &warnings); EXPECT_EQ("suggester", winner_id); EXPECT_EQ(FILE_PATH_LITERAL("b"), filename.value()); EXPECT_EQ(downloads::FILENAME_CONFLICT_ACTION_PROMPT, conflict_action); diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc index 34fcfe579d5..57290947203 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_unittest.cc @@ -29,6 +29,10 @@ class TestDownloadCoreService : public DownloadCoreServiceImpl { public: explicit TestDownloadCoreService(Profile* profile) : DownloadCoreServiceImpl(profile), profile_(profile) {} + + TestDownloadCoreService(const TestDownloadCoreService&) = delete; + TestDownloadCoreService& operator=(const TestDownloadCoreService&) = delete; + ~TestDownloadCoreService() override {} void Shutdown() override { @@ -57,8 +61,6 @@ class TestDownloadCoreService : public DownloadCoreServiceImpl { std::unique_ptr<DownloadHistory> download_history_; std::unique_ptr<ExtensionDownloadsEventRouter> router_; Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(TestDownloadCoreService); }; } // namespace @@ -66,6 +68,10 @@ class TestDownloadCoreService : public DownloadCoreServiceImpl { class DownloadsApiUnitTest : public ExtensionApiUnittest { public: DownloadsApiUnitTest() {} + + DownloadsApiUnitTest(const DownloadsApiUnitTest&) = delete; + DownloadsApiUnitTest& operator=(const DownloadsApiUnitTest&) = delete; + ~DownloadsApiUnitTest() override {} void SetUp() override { ExtensionApiUnittest::SetUp(); @@ -111,8 +117,6 @@ class DownloadsApiUnitTest : public ExtensionApiUnittest { std::unique_ptr<MockDownloadManager> manager_; content::DownloadManager::Observer* download_history_manager_observer_; - - DISALLOW_COPY_AND_ASSIGN(DownloadsApiUnitTest); }; // static diff --git a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc index d4ce667dc71..e62063de92d 100644 --- a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc @@ -22,10 +22,11 @@ typedef extensions::api::downloads_internal::DetermineFilename::Params ExtensionFunction::ResponseAction DownloadsInternalDetermineFilenameFunction::Run() { std::unique_ptr<DetermineFilenameParams> params( - DetermineFilenameParams::Create(*args_)); + DetermineFilenameParams::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); - std::string filename; - EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filename)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 2); + EXTENSION_FUNCTION_VALIDATE(args()[1].is_string()); + const std::string& filename = args()[1].GetString(); std::string error; bool result = ExtensionDownloadsEventRouter::DetermineFilename( browser_context(), include_incognito_information(), extension()->id(), diff --git a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h index 490c94eed33..ab24f007c7e 100644 --- a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h +++ b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h @@ -15,13 +15,16 @@ class DownloadsInternalDetermineFilenameFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("downloadsInternal.determineFilename", DOWNLOADSINTERNAL_DETERMINEFILENAME) DownloadsInternalDetermineFilenameFunction(); + + DownloadsInternalDetermineFilenameFunction( + const DownloadsInternalDetermineFilenameFunction&) = delete; + DownloadsInternalDetermineFilenameFunction& operator=( + const DownloadsInternalDetermineFilenameFunction&) = delete; + ResponseAction Run() override; protected: ~DownloadsInternalDetermineFilenameFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DownloadsInternalDetermineFilenameFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h b/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h index 0d691184809..00e6c538efc 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api.h @@ -16,6 +16,13 @@ class EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction public: EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction(); + EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction( + const EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction&) = + delete; + EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction& operator=( + const EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction&) = + delete; + protected: ~EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction() override; @@ -27,9 +34,6 @@ class EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction ENTERPRISE_HARDWAREPLATFORM_GETHARDWAREPLATFORMINFO) void OnHardwarePlatformInfo(base::SysInfo::HardwareInfo info); - - DISALLOW_COPY_AND_ASSIGN( - EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api_unittest.cc index 5c9bb05fb58..0cb04d4de97 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_hardware_platform/enterprise_hardware_platform_api_unittest.cc @@ -21,6 +21,12 @@ class EnterpriseHardwarePlatformAPITest : public ExtensionServiceTestWithInstall { public: EnterpriseHardwarePlatformAPITest() = default; + + EnterpriseHardwarePlatformAPITest(const EnterpriseHardwarePlatformAPITest&) = + delete; + EnterpriseHardwarePlatformAPITest& operator=( + const EnterpriseHardwarePlatformAPITest&) = delete; + ~EnterpriseHardwarePlatformAPITest() override = default; protected: @@ -48,8 +54,6 @@ class EnterpriseHardwarePlatformAPITest scoped_refptr<const Extension> extension_; scoped_refptr<EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction> function_; - - DISALLOW_COPY_AND_ASSIGN(EnterpriseHardwarePlatformAPITest); }; TEST_F(EnterpriseHardwarePlatformAPITest, GetHardwarePlatformInfoAllowed) { diff --git a/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_ash_apitest.cc b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_ash_apitest.cc index a5d2ae43bf4..725b8033620 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_ash_apitest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_networking_attributes/enterprise_networking_attributes_ash_apitest.cc @@ -118,8 +118,8 @@ class EnterpriseNetworkingAttributesTest ipconfig_v6_dictionary); base::ListValue ip_configs; - ip_configs.AppendString(kWifiIPConfigV4Path); - ip_configs.AppendString(kWifiIPConfigV6Path); + ip_configs.Append(kWifiIPConfigV4Path); + ip_configs.Append(kWifiIPConfigV6Path); shill_device_client->SetDeviceProperty( kWifiDevicePath, shill::kIPConfigsProperty, ip_configs, /*notify_changed=*/false); diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc index 588fda1c912..95d0b3b0be6 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.cc @@ -146,15 +146,27 @@ EnterprisePlatformKeysInternalGenerateKeyFunction:: ExtensionFunction::ResponseAction EnterprisePlatformKeysInternalGenerateKeyFunction::Run() { + std::unique_ptr<api_epki::GenerateKey::Params> params( + api_epki::GenerateKey::Params::Create(args())); + #if BUILDFLAG(IS_CHROMEOS_LACROS) // TODO(b/191958380): Lift the restriction when *.platformKeys.* APIs are // implemented for secondary profiles in Lacros. if (!Profile::FromBrowserContext(browser_context())->IsMainProfile()) return RespondNow(Error(kUnsupportedProfile)); -#endif // BUILDFLAG(IS_CHROMEOS_LACROS) - std::unique_ptr<api_epki::GenerateKey::Params> params( - api_epki::GenerateKey::Params::Create(*args_)); + if (params->software_backed) { + // Software-backed RSA keys are only supported starting with KeyStore + // interface version 16. + // TODO(https://crbug.com/1252410): Remove this code with M-100. + const uint32_t kSoftwareBackedRsaMinVersion = 16; + std::string error = + ValidateCrosapi(kSoftwareBackedRsaMinVersion, browser_context()); + if (!error.empty()) { + return RespondNow(Error(error)); + } + } +#endif // BUILDFLAG(IS_CHROMEOS_LACROS) EXTENSION_FUNCTION_VALIDATE(params); absl::optional<chromeos::platform_keys::TokenId> platform_keys_token_id = @@ -173,7 +185,7 @@ EnterprisePlatformKeysInternalGenerateKeyFunction::Run() { *(params->algorithm.modulus_length) >= 0); service->GenerateRSAKey( platform_keys_token_id.value(), *(params->algorithm.modulus_length), - extension_id(), + params->software_backed, extension_id(), base::BindOnce( &EnterprisePlatformKeysInternalGenerateKeyFunction::OnGeneratedKey, this)); @@ -210,7 +222,7 @@ void EnterprisePlatformKeysInternalGenerateKeyFunction::OnGeneratedKey( ExtensionFunction::ResponseAction EnterprisePlatformKeysGetCertificatesFunction::Run() { std::unique_ptr<api_epk::GetCertificates::Params> params( - api_epk::GetCertificates::Params::Create(*args_)); + api_epk::GetCertificates::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::string error = @@ -256,7 +268,7 @@ void EnterprisePlatformKeysGetCertificatesFunction::OnGetCertificates( ExtensionFunction::ResponseAction EnterprisePlatformKeysImportCertificateFunction::Run() { std::unique_ptr<api_epk::ImportCertificate::Params> params( - api_epk::ImportCertificate::Params::Create(*args_)); + api_epk::ImportCertificate::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::string error = ValidateCrosapi( @@ -290,7 +302,7 @@ void EnterprisePlatformKeysImportCertificateFunction::OnAddCertificate( ExtensionFunction::ResponseAction EnterprisePlatformKeysRemoveCertificateFunction::Run() { std::unique_ptr<api_epk::RemoveCertificate::Params> params( - api_epk::RemoveCertificate::Params::Create(*args_)); + api_epk::RemoveCertificate::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::string error = @@ -326,7 +338,7 @@ void EnterprisePlatformKeysRemoveCertificateFunction::OnRemoveCertificate( ExtensionFunction::ResponseAction EnterprisePlatformKeysInternalGetTokensFunction::Run() { - EXTENSION_FUNCTION_VALIDATE(args_->GetList().empty()); + EXTENSION_FUNCTION_VALIDATE(args().empty()); std::string error = ValidateCrosapi( KeystoreService::kDEPRECATED_GetKeyStoresMinVersion, browser_context()); @@ -372,7 +384,7 @@ void EnterprisePlatformKeysInternalGetTokensFunction::OnGetKeyStores( ExtensionFunction::ResponseAction EnterprisePlatformKeysChallengeMachineKeyFunction::Run() { std::unique_ptr<api_epk::ChallengeMachineKey::Params> params( - api_epk::ChallengeMachineKey::Params::Create(*args_)); + api_epk::ChallengeMachineKey::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const std::string error = ValidateCrosapi( @@ -416,7 +428,7 @@ void EnterprisePlatformKeysChallengeMachineKeyFunction:: ExtensionFunction::ResponseAction EnterprisePlatformKeysChallengeUserKeyFunction::Run() { std::unique_ptr<api_epk::ChallengeUserKey::Params> params( - api_epk::ChallengeUserKey::Params::Create(*args_)); + api_epk::ChallengeUserKey::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const std::string error = ValidateCrosapi( diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc index 5c118d470a8..238d596c92e 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api_unittest.cc @@ -39,12 +39,14 @@ namespace { const char kUserEmail[] = "test@google.com"; -void FakeRunCheckNotRegister(chromeos::attestation::AttestationKeyType key_type, - Profile* profile, - ash::attestation::TpmChallengeKeyCallback callback, - const std::string& challenge, - bool register_key, - const std::string& key_name_for_spkac) { +void FakeRunCheckNotRegister( + chromeos::attestation::AttestationKeyType key_type, + Profile* profile, + ash::attestation::TpmChallengeKeyCallback callback, + const std::string& challenge, + bool register_key, + const std::string& key_name_for_spkac, + const absl::optional<::attestation::DeviceTrustSignals>& signals) { EXPECT_FALSE(register_key); std::move(callback).Run( ash::attestation::TpmChallengeKeyResult::MakeChallengeResponse( @@ -217,7 +219,7 @@ TEST_F(EPKChallengeMachineKeyTest, KeyNotRegisteredByDefault) { SetMockTpmChallenger(); base::ListValue allowlist; - allowlist.AppendString(extension_->id()); + allowlist.Append(extension_->id()); prefs_->Set(prefs::kAttestationExtensionAllowlist, allowlist); EXPECT_CALL(*mock_tpm_challenge_key_, BuildResponse) diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc index b452befd3b7..4b3088d76f8 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_apitest_nss.cc @@ -19,8 +19,8 @@ #include "base/values.h" #include "chrome/browser/ash/login/test/device_state_mixin.h" #include "chrome/browser/ash/profiles/profile_helper.h" +#include "chrome/browser/ash/scoped_test_system_nss_key_slot_mixin.h" #include "chrome/browser/chromeos/platform_keys/platform_keys_service_factory.h" -#include "chrome/browser/chromeos/scoped_test_system_nss_key_slot_mixin.h" #include "chrome/browser/extensions/api/platform_keys/platform_keys_test_base.h" #include "chrome/browser/net/nss_context.h" #include "chrome/browser/policy/extension_force_install_mixin.h" @@ -208,6 +208,10 @@ class EnterprisePlatformKeysTest GetParam().enrollment_status_, GetParam().user_status_) {} + EnterprisePlatformKeysTest(const EnterprisePlatformKeysTest&) = delete; + EnterprisePlatformKeysTest& operator=(const EnterprisePlatformKeysTest&) = + delete; + void SetUpCommandLine(base::CommandLine* command_line) override { PlatformKeysTestBase::SetUpCommandLine(command_line); @@ -251,8 +255,6 @@ class EnterprisePlatformKeysTest base::size(privateKeyPkcs8System), system_slot->slot()); } - - DISALLOW_COPY_AND_ASSIGN(EnterprisePlatformKeysTest); }; } // namespace @@ -363,9 +365,9 @@ class EnterprisePlatformKeysLoginScreenTest kExtensionId); } - chromeos::DeviceStateMixin device_state_mixin_{ + ash::DeviceStateMixin device_state_mixin_{ &mixin_host_, - chromeos::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; + ash::DeviceStateMixin::State::OOBE_COMPLETED_CLOUD_ENROLLED}; chromeos::ScopedTestSystemNSSKeySlotMixin system_nss_key_slot_mixin_{ &mixin_host_}; ExtensionForceInstallMixin extension_force_install_mixin_{&mixin_host_}; diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc index 3017152738d..214ccf90585 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.cc @@ -61,7 +61,8 @@ void EPKPChallengeKey::Run(chromeos::attestation::AttestationKeyType type, impl_ = ash::attestation::TpmChallengeKeyFactory::Create(); impl_->BuildResponse(type, profile, std::move(callback), challenge, - register_key, key_name_for_spkac); + register_key, key_name_for_spkac, + /*signals=*/absl::nullopt); } EnterprisePlatformKeysPrivateChallengeMachineKeyFunction:: @@ -73,7 +74,7 @@ EnterprisePlatformKeysPrivateChallengeMachineKeyFunction:: ExtensionFunction::ResponseAction EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::Run() { std::unique_ptr<api_epkp::ChallengeMachineKey::Params> params( - api_epkp::ChallengeMachineKey::Params::Create(*args_)); + api_epkp::ChallengeMachineKey::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); ash::attestation::TpmChallengeKeyCallback callback = base::BindOnce(&EnterprisePlatformKeysPrivateChallengeMachineKeyFunction:: @@ -119,7 +120,7 @@ EnterprisePlatformKeysPrivateChallengeUserKeyFunction:: ExtensionFunction::ResponseAction EnterprisePlatformKeysPrivateChallengeUserKeyFunction::Run() { std::unique_ptr<api_epkp::ChallengeUserKey::Params> params( - api_epkp::ChallengeUserKey::Params::Create(*args_)); + api_epkp::ChallengeUserKey::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); ash::attestation::TpmChallengeKeyCallback callback = base::BindOnce( &EnterprisePlatformKeysPrivateChallengeUserKeyFunction::OnChallengedKey, diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc index a42929d41a2..bf4a42ba098 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api_unittest.cc @@ -104,7 +104,7 @@ TEST_F(EPKPChallengeMachineKeyTest, Success) { SetMockTpmChallenger(); base::ListValue allowlist; - allowlist.AppendString(extension_->id()); + allowlist.Append(extension_->id()); prefs_->Set(prefs::kAttestationExtensionAllowlist, allowlist); std::unique_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( @@ -143,7 +143,7 @@ TEST_F(EPKPChallengeUserKeyTest, Success) { SetMockTpmChallenger(); base::ListValue allowlist; - allowlist.AppendString(extension_->id()); + allowlist.Append(extension_->id()); prefs_->Set(prefs::kAttestationExtensionAllowlist, allowlist); std::unique_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc index b18ebc140f9..a5eee111631 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.cc @@ -71,6 +71,7 @@ api::enterprise_reporting_private::ContextInfo ToContextInfo( ? std::make_unique<bool>(signals.third_party_blocking_enabled.value()) : nullptr; info.os_firewall = ToInfoSettingValue(signals.os_firewall); + info.system_dns_servers = std::move(signals.system_dns_servers); switch (signals.realtime_url_check_mode) { case safe_browsing::REAL_TIME_CHECK_DISABLED: info.realtime_url_check_mode = extensions::api:: @@ -86,15 +87,15 @@ api::enterprise_reporting_private::ContextInfo ToContextInfo( info.built_in_dns_client_enabled = signals.built_in_dns_client_enabled; switch (signals.safe_browsing_protection_level) { - case safe_browsing::NO_SAFE_BROWSING: + case safe_browsing::SafeBrowsingState::NO_SAFE_BROWSING: info.safe_browsing_protection_level = extensions::api:: enterprise_reporting_private::SAFE_BROWSING_LEVEL_DISABLED; break; - case safe_browsing::STANDARD_PROTECTION: + case safe_browsing::SafeBrowsingState::STANDARD_PROTECTION: info.safe_browsing_protection_level = extensions::api:: enterprise_reporting_private::SAFE_BROWSING_LEVEL_STANDARD; break; - case safe_browsing::ENHANCED_PROTECTION: + case safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION: info.safe_browsing_protection_level = extensions::api:: enterprise_reporting_private::SAFE_BROWSING_LEVEL_ENHANCED; break; @@ -166,7 +167,7 @@ EnterpriseReportingPrivateGetPersistentSecretFunction::Run() { std::unique_ptr< api::enterprise_reporting_private::GetPersistentSecret::Params> params(api::enterprise_reporting_private::GetPersistentSecret::Params:: - Create(*args_)); + Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); bool force_create = params->reset_secret ? *params->reset_secret : false; base::ThreadPool::PostTask( @@ -219,7 +220,7 @@ ExtensionFunction::ResponseAction EnterpriseReportingPrivateGetDeviceDataFunction::Run() { std::unique_ptr<api::enterprise_reporting_private::GetDeviceData::Params> params(api::enterprise_reporting_private::GetDeviceData::Params::Create( - *args_)); + args())); EXTENSION_FUNCTION_VALIDATE(params.get()); base::ThreadPool::PostTask( FROM_HERE, @@ -275,7 +276,7 @@ ExtensionFunction::ResponseAction EnterpriseReportingPrivateSetDeviceDataFunction::Run() { std::unique_ptr<api::enterprise_reporting_private::SetDeviceData::Params> params(api::enterprise_reporting_private::SetDeviceData::Params::Create( - *args_)); + args())); EXTENSION_FUNCTION_VALIDATE(params.get()); base::ThreadPool::PostTask( FROM_HERE, @@ -332,6 +333,18 @@ EnterpriseReportingPrivateGetDeviceInfoFunction::ToDeviceInfo( device_info.disk_encrypted = ToInfoSettingValue(device_signals.disk_encrypted); device_info.mac_addresses = std::move(device_signals.mac_addresses); + if (device_signals.windows_machine_domain.has_value()) { + device_info.windows_machine_domain = std::make_unique<std::string>( + device_signals.windows_machine_domain.value()); + } else { + device_info.windows_machine_domain = nullptr; + } + if (device_signals.windows_user_domain.has_value()) { + device_info.windows_user_domain = std::make_unique<std::string>( + device_signals.windows_user_domain.value()); + } else { + device_info.windows_user_domain = nullptr; + } return device_info; } @@ -408,7 +421,7 @@ ExtensionFunction::ResponseAction EnterpriseReportingPrivateGetCertificateFunction::Run() { std::unique_ptr<api::enterprise_reporting_private::GetCertificate::Params> params(api::enterprise_reporting_private::GetCertificate::Params::Create( - *args_)); + args())); EXTENSION_FUNCTION_VALIDATE(params.get()); // If AutoSelectCertificateForUrl is not set at the machine level, this diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h index 46624ed9a51..d06f508a28d 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_api.h @@ -30,15 +30,19 @@ class EnterpriseReportingPrivateGetDeviceIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("enterprise.reportingPrivate.getDeviceId", ENTERPRISEREPORTINGPRIVATE_GETDEVICEID) + EnterpriseReportingPrivateGetDeviceIdFunction(); + EnterpriseReportingPrivateGetDeviceIdFunction( + const EnterpriseReportingPrivateGetDeviceIdFunction&) = delete; + EnterpriseReportingPrivateGetDeviceIdFunction& operator=( + const EnterpriseReportingPrivateGetDeviceIdFunction&) = delete; + // ExtensionFunction ExtensionFunction::ResponseAction Run() override; private: ~EnterpriseReportingPrivateGetDeviceIdFunction() override; - - DISALLOW_COPY_AND_ASSIGN(EnterpriseReportingPrivateGetDeviceIdFunction); }; #if !defined(OS_LINUX) diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_apitest.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_apitest.cc index 3fb24803b43..0a4b06457f5 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_apitest.cc @@ -4,6 +4,7 @@ #include "build/branding_buildflags.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/version_info/version_info.h" @@ -214,7 +215,46 @@ IN_PROC_BROWSER_TEST_F(EnterpriseReportingPrivateApiTest, GetDeviceInfo) { constexpr char kOSName[] = "linux"; #endif -#if defined(OS_WIN) || defined(OS_MAC) || defined(OS_LINUX) +#if defined(OS_WIN) + // The added conditions for windows are related to the fact that we don't know + // if the machine running the test is managed or not + constexpr char kTest[] = R"( + chrome.test.assertEq( + 'function', + typeof chrome.enterprise.reportingPrivate.getDeviceInfo); + + chrome.enterprise.reportingPrivate.getDeviceInfo((deviceInfo) => { + chrome.test.assertNoLastError(); + let count = 8; + if(deviceInfo.windowsUserDomain){ + count++; + chrome.test.assertEq(typeof deviceInfo.windowsUserDomain, "string"); + } else { + chrome.test.assertEq(typeof deviceInfo.windowsUserDomain, "undefined"); + } + + if(deviceInfo.windowsMachineDomain){ + count++; + chrome.test.assertEq(typeof deviceInfo.windowsMachineDomain, "string"); + } else { + chrome.test.assertEq( + typeof deviceInfo.windowsMachineDomain, + "undefined"); + } + chrome.test.assertEq(count, Object.keys(deviceInfo).length); + chrome.test.assertEq('%s', deviceInfo.osName); + chrome.test.assertEq(typeof deviceInfo.osVersion, 'string'); + chrome.test.assertEq(typeof deviceInfo.deviceHostName, 'string'); + chrome.test.assertEq(typeof deviceInfo.deviceModel, 'string'); + chrome.test.assertEq(typeof deviceInfo.serialNumber, 'string'); + chrome.test.assertEq(typeof deviceInfo.screenLockSecured, 'string'); + chrome.test.assertEq(typeof deviceInfo.diskEncrypted, 'string'); + chrome.test.assertTrue(deviceInfo.macAddresses instanceof Array); + + chrome.test.notifyPass(); + });)"; + RunTest(base::StringPrintf(kTest, kOSName)); +#elif defined(OS_MAC) || defined(OS_LINUX) constexpr char kTest[] = R"( chrome.test.assertEq( 'function', @@ -232,6 +272,8 @@ IN_PROC_BROWSER_TEST_F(EnterpriseReportingPrivateApiTest, GetDeviceInfo) { chrome.test.assertEq(typeof deviceInfo.screenLockSecured, 'string'); chrome.test.assertEq(typeof deviceInfo.diskEncrypted, 'string'); chrome.test.assertTrue(deviceInfo.macAddresses instanceof Array); + chrome.test.assertEq(typeof deviceInfo.windowsMachineDomain, "undefined"); + chrome.test.assertEq(typeof deviceInfo.windowsUserDomain, "undefined"); chrome.test.notifyPass(); });)"; @@ -255,15 +297,15 @@ IN_PROC_BROWSER_TEST_F(EnterpriseReportingPrivateApiTest, GetContextInfo) { constexpr char kChromeCleanupEnabledType[] = "boolean"; #if BUILDFLAG(GOOGLE_CHROME_BRANDING) constexpr char kThirdPartyBlockingEnabledType[] = "boolean"; - constexpr char kCount[] = "16"; + constexpr char kCount[] = "17"; #else constexpr char kThirdPartyBlockingEnabledType[] = "undefined"; - constexpr char kCount[] = "15"; + constexpr char kCount[] = "16"; #endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) #else constexpr char kChromeCleanupEnabledType[] = "undefined"; constexpr char kThirdPartyBlockingEnabledType[] = "undefined"; - constexpr char kCount[] = "14"; + constexpr char kCount[] = "15"; #endif // defined(OS_WIN) constexpr char kTest[] = R"( @@ -292,6 +334,7 @@ IN_PROC_BROWSER_TEST_F(EnterpriseReportingPrivateApiTest, GetContextInfo) { (typeof info.chromeRemoteDesktopAppBlocked, 'boolean'); chrome.test.assertEq(typeof info.thirdPartyBlockingEnabled,'%s'); chrome.test.assertEq(typeof info.osFirewall, 'string'); + chrome.test.assertTrue(info.systemDnsServers instanceof Array); chrome.test.notifyPass(); });)"; diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_browsertest.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_browsertest.cc index e42f5cff4cb..809e54153f3 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_browsertest.cc @@ -5,6 +5,7 @@ #include "base/command_line.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/content_settings/host_content_settings_map_factory.h" #include "chrome/browser/enterprise/util/managed_browser_utils.h" @@ -36,11 +37,14 @@ #include "net/test/cert_test_util.h" #include "net/test/test_data_directory.h" +#if defined(OS_CHROMEOS) +#include "chrome/browser/policy/dm_token_utils.h" +#endif + #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" #include "chrome/browser/ash/policy/core/user_cloud_policy_manager_ash.h" #include "chrome/browser/browser_process_platform_part.h" -#include "chrome/browser/policy/dm_token_utils.h" #include "chromeos/dbus/constants/dbus_switches.h" #endif @@ -117,7 +121,7 @@ class EnterpriseReportingPrivateGetContextInfoBaseBrowserTest #endif void SetupDMToken() { -#if BUILDFLAG(IS_CHROMEOS_ASH) +#if defined(OS_CHROMEOS) policy::SetDMTokenForTesting( policy::DMToken::CreateValidTokenForTesting("dm_token")); #else diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc index 3702a591282..71423ea9b4b 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/enterprise_reporting_private_unittest.cc @@ -60,14 +60,17 @@ class EnterpriseReportingPrivateGetDeviceIdTest : public ExtensionApiUnittest { public: EnterpriseReportingPrivateGetDeviceIdTest() = default; + EnterpriseReportingPrivateGetDeviceIdTest( + const EnterpriseReportingPrivateGetDeviceIdTest&) = delete; + EnterpriseReportingPrivateGetDeviceIdTest& operator=( + const EnterpriseReportingPrivateGetDeviceIdTest&) = delete; + void SetClientId(const std::string& client_id) { storage_.SetClientId(client_id); } private: policy::FakeBrowserDMTokenStorage storage_; - - DISALLOW_COPY_AND_ASSIGN(EnterpriseReportingPrivateGetDeviceIdTest); }; TEST_F(EnterpriseReportingPrivateGetDeviceIdTest, GetDeviceId) { @@ -95,6 +98,11 @@ class EnterpriseReportingPrivateDeviceDataFunctionsTest public: EnterpriseReportingPrivateDeviceDataFunctionsTest() = default; + EnterpriseReportingPrivateDeviceDataFunctionsTest( + const EnterpriseReportingPrivateDeviceDataFunctionsTest&) = delete; + EnterpriseReportingPrivateDeviceDataFunctionsTest& operator=( + const EnterpriseReportingPrivateDeviceDataFunctionsTest&) = delete; + void SetUp() override { ExtensionApiUnittest::SetUp(); ASSERT_TRUE(fake_appdata_dir_.CreateUniqueTempDir()); @@ -103,22 +111,20 @@ class EnterpriseReportingPrivateDeviceDataFunctionsTest private: base::ScopedTempDir fake_appdata_dir_; - - DISALLOW_COPY_AND_ASSIGN(EnterpriseReportingPrivateDeviceDataFunctionsTest); }; TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, StoreDeviceData) { auto function = base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>(); std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>(); - values->AppendString("a"); + values->Append("a"); values->Append( std::make_unique<base::Value>(base::Value::BlobStorage({1, 2, 3}))); extension_function_test_utils::RunFunction(function.get(), std::move(values), browser(), extensions::api_test_utils::NONE); ASSERT_TRUE(function->GetResultList()); - EXPECT_EQ(0u, function->GetResultList()->GetSize()); + EXPECT_EQ(0u, function->GetResultList()->GetList().size()); EXPECT_TRUE(function->GetError().empty()); } @@ -126,12 +132,12 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, DeviceDataMissing) { auto function = base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>(); std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>(); - values->AppendString("b"); + values->Append("b"); extension_function_test_utils::RunFunction(function.get(), std::move(values), browser(), extensions::api_test_utils::NONE); ASSERT_TRUE(function->GetResultList()); - EXPECT_EQ(1u, function->GetResultList()->GetSize()); + EXPECT_EQ(1u, function->GetResultList()->GetList().size()); EXPECT_TRUE(function->GetError().empty()); const base::Value* single_result = nullptr; @@ -146,7 +152,7 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, DeviceBadId) { base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>(); std::unique_ptr<base::ListValue> set_values = std::make_unique<base::ListValue>(); - set_values->AppendString("a/b"); + set_values->Append("a/b"); set_values->Append( std::make_unique<base::Value>(base::Value::BlobStorage({1, 2, 3}))); extension_function_test_utils::RunFunction(set_function.get(), @@ -158,12 +164,12 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, DeviceBadId) { auto function = base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>(); std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>(); - values->AppendString("a"); + values->Append("a"); extension_function_test_utils::RunFunction(function.get(), std::move(values), browser(), extensions::api_test_utils::NONE); ASSERT_TRUE(function->GetResultList()); - EXPECT_EQ(0u, function->GetResultList()->GetSize()); + EXPECT_EQ(0u, function->GetResultList()->GetList().size()); EXPECT_FALSE(function->GetError().empty()); } @@ -172,7 +178,7 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, RetrieveDeviceData) { base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>(); std::unique_ptr<base::ListValue> set_values = std::make_unique<base::ListValue>(); - set_values->AppendString("c"); + set_values->Append("c"); set_values->Append( std::make_unique<base::Value>(base::Value::BlobStorage({1, 2, 3}))); extension_function_test_utils::RunFunction(set_function.get(), @@ -183,7 +189,7 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, RetrieveDeviceData) { auto get_function = base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>(); std::unique_ptr<base::ListValue> values = std::make_unique<base::ListValue>(); - values->AppendString("c"); + values->Append("c"); extension_function_test_utils::RunFunction(get_function.get(), std::move(values), browser(), extensions::api_test_utils::NONE); @@ -200,7 +206,7 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, RetrieveDeviceData) { base::MakeRefCounted<EnterpriseReportingPrivateSetDeviceDataFunction>(); std::unique_ptr<base::ListValue> reset_values = std::make_unique<base::ListValue>(); - reset_values->AppendString("c"); + reset_values->Append("c"); extension_function_test_utils::RunFunction(set_function2.get(), std::move(reset_values), browser(), extensions::api_test_utils::NONE); @@ -210,12 +216,12 @@ TEST_F(EnterpriseReportingPrivateDeviceDataFunctionsTest, RetrieveDeviceData) { base::MakeRefCounted<EnterpriseReportingPrivateGetDeviceDataFunction>(); std::unique_ptr<base::ListValue> values2 = std::make_unique<base::ListValue>(); - values2->AppendString("c"); + values2->Append("c"); extension_function_test_utils::RunFunction(get_function2.get(), std::move(values2), browser(), extensions::api_test_utils::NONE); ASSERT_TRUE(get_function2->GetResultList()); - EXPECT_EQ(1u, get_function2->GetResultList()->GetSize()); + EXPECT_EQ(1u, get_function2->GetResultList()->GetList().size()); EXPECT_TRUE(get_function2->GetError().empty()); EXPECT_TRUE(get_function2->GetResultList()->Get(0, &single_result)); @@ -233,6 +239,13 @@ class EnterpriseReportingPrivateGetPersistentSecretFunctionTest public: EnterpriseReportingPrivateGetPersistentSecretFunctionTest() = default; + EnterpriseReportingPrivateGetPersistentSecretFunctionTest( + const EnterpriseReportingPrivateGetPersistentSecretFunctionTest&) = + delete; + EnterpriseReportingPrivateGetPersistentSecretFunctionTest& operator=( + const EnterpriseReportingPrivateGetPersistentSecretFunctionTest&) = + delete; + void SetUp() override { ExtensionApiUnittest::SetUp(); #if defined(OS_WIN) @@ -245,9 +258,6 @@ class EnterpriseReportingPrivateGetPersistentSecretFunctionTest #if defined(OS_WIN) registry_util::RegistryOverrideManager registry_override_manager_; #endif - - DISALLOW_COPY_AND_ASSIGN( - EnterpriseReportingPrivateGetPersistentSecretFunctionTest); }; TEST_F(EnterpriseReportingPrivateGetPersistentSecretFunctionTest, GetSecret) { @@ -313,11 +323,9 @@ TEST_F(EnterpriseReportingPrivateGetDeviceInfoTest, GetDeviceInfo) { std::unique_ptr<base::Value> device_info_value = RunFunctionAndReturnValue(function.get(), "[]"); ASSERT_TRUE(device_info_value.get()); - enterprise_reporting_private::DeviceInfo info; ASSERT_TRUE(enterprise_reporting_private::DeviceInfo::Populate( *device_info_value, &info)); - #if defined(OS_MAC) EXPECT_EQ("macOS", info.os_name); #elif defined(OS_WIN) @@ -340,6 +348,8 @@ TEST_F(EnterpriseReportingPrivateGetDeviceInfoTest, GetDeviceInfo) { info.disk_encrypted); ASSERT_EQ(1u, info.mac_addresses.size()); EXPECT_EQ("00:00:00:00:00:00", info.mac_addresses[0]); + EXPECT_EQ(*info.windows_machine_domain, "MACHINE_DOMAIN"); + EXPECT_EQ(*info.windows_user_domain, "USER_DOMAIN"); #endif } @@ -363,6 +373,8 @@ TEST_F(EnterpriseReportingPrivateGetDeviceInfoTest, GetDeviceInfoConversion) { info.disk_encrypted); ASSERT_EQ(1u, info.mac_addresses.size()); EXPECT_EQ("00:00:00:00:00:00", info.mac_addresses[0]); + EXPECT_EQ(*info.windows_machine_domain, "MACHINE_DOMAIN"); + EXPECT_EQ(*info.windows_user_domain, "USER_DOMAIN"); } #endif // !defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc b/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc index 93cd9dfd4b4..064063e51fb 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/browser_action_apitest.cc @@ -8,8 +8,6 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/macros.h" -#include "base/run_loop.h" -#include "base/scoped_observation.h" #include "base/strings/string_piece.h" #include "base/strings/stringprintf.h" #include "base/test/metrics/histogram_tester.h" @@ -52,7 +50,7 @@ #include "extensions/browser/extension_action.h" #include "extensions/browser/extension_action_manager.h" #include "extensions/browser/extension_host.h" -#include "extensions/browser/extension_host_observer.h" +#include "extensions/browser/extension_host_test_helper.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/process_manager.h" @@ -65,11 +63,11 @@ #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/geometry/size.h" +#include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/image/canvas_image_source.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/image/image_unittest_util.h" -#include "ui/gfx/skia_util.h" using content::WebContents; @@ -102,9 +100,12 @@ void VerifyIconsMatch(const gfx::Image& bar_rendering, .GetBitmap())); } +using ContextType = ExtensionBrowserTest::ContextType; + class BrowserActionApiTest : public ExtensionApiTest { public: - BrowserActionApiTest() = default; + explicit BrowserActionApiTest(ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) {} ~BrowserActionApiTest() override = default; BrowserActionApiTest(const BrowserActionApiTest&) = delete; BrowserActionApiTest& operator=(const BrowserActionApiTest&) = delete; @@ -149,13 +150,11 @@ class BrowserActionApiCanvasTest : public BrowserActionApiTest { } }; -using ContextType = ExtensionBrowserTest::ContextType; - class BrowserActionApiTestWithContextType : public BrowserActionApiTest, public testing::WithParamInterface<ContextType> { public: - BrowserActionApiTestWithContextType() = default; + BrowserActionApiTestWithContextType() : BrowserActionApiTest(GetParam()) {} ~BrowserActionApiTestWithContextType() override = default; BrowserActionApiTestWithContextType( const BrowserActionApiTestWithContextType&) = delete; @@ -163,17 +162,11 @@ class BrowserActionApiTestWithContextType const BrowserActionApiTestWithContextType&) = delete; protected: - const extensions::Extension* LoadExtensionWithParamOptions( - const base::FilePath& path) { - return LoadExtension(path, {.load_as_service_worker = - GetParam() == ContextType::kServiceWorker}); - } - void RunUpdateTest(base::StringPiece path, bool expect_failure) { ExtensionTestMessageListener ready_listener("ready", true); ASSERT_TRUE(embedded_test_server()->Start()); const Extension* extension = - LoadExtensionWithParamOptions(test_data_dir_.AppendASCII(path)); + LoadExtension(test_data_dir_.AppendASCII(path)); ASSERT_TRUE(extension) << message_; // Test that there is a browser action in the toolbar. ASSERT_EQ(1, GetBrowserActionsBar()->NumberOfBrowserActions()); @@ -210,7 +203,7 @@ class BrowserActionApiTestWithContextType void RunEnableTest(base::StringPiece path, bool start_enabled) { ExtensionTestMessageListener ready_listener("ready", true); const Extension* extension = - LoadExtensionWithParamOptions(test_data_dir_.AppendASCII(path)); + LoadExtension(test_data_dir_.AppendASCII(path)); ASSERT_TRUE(extension) << message_; // Test that there is a browser action in the toolbar. ASSERT_EQ(1, GetBrowserActionsBar()->NumberOfBrowserActions()); @@ -235,12 +228,6 @@ class BrowserActionApiTestWithContextType action->GetIsVisible(ExtensionAction::kDefaultTabId)); } - bool RunTest(const char* name) WARN_UNUSED_RESULT { - return RunExtensionTest( - name, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } - private: base::test::ScopedFeatureList feature_list_; }; @@ -248,8 +235,8 @@ class BrowserActionApiTestWithContextType IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, Basic) { ExtensionTestMessageListener ready_listener("ready", false); ASSERT_TRUE(embedded_test_server()->Start()); - const Extension* extension = LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("browser_action/basics")); + const Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("browser_action/basics")); ASSERT_TRUE(extension) << message_; // Test that there is a browser action in the toolbar. @@ -259,8 +246,8 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, Basic) { // Open a URL in the tab, so the event handler can check the tab's // "url" and "title" properties. - ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("/extensions/test_file.txt")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/extensions/test_file.txt"))); ResultCatcher catcher; // Simulate the browser action being clicked. @@ -305,8 +292,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiCanvasTest, DynamicBrowserAction) { // We need this on mac so we don't loose 2x representations from browser icon // in transformations gfx::ImageSkia -> NSImage -> gfx::ImageSkia. std::vector<ui::ResourceScaleFactor> supported_scale_factors; - supported_scale_factors.push_back(ui::SCALE_FACTOR_100P); - supported_scale_factors.push_back(ui::SCALE_FACTOR_200P); + supported_scale_factors.push_back(ui::k100Percent); + supported_scale_factors.push_back(ui::k200Percent); ui::SetSupportedResourceScaleFactors(supported_scale_factors); #endif @@ -541,7 +528,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiCanvasTest, InvisibleIconBrowserAction) { IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, TabSpecificBrowserActionState) { - ASSERT_TRUE(RunTest("browser_action/tab_specific_state")) << message_; + ASSERT_TRUE(RunExtensionTest("browser_action/tab_specific_state")) + << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -567,14 +555,14 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, GetBrowserActionsBar()->GetTooltip(extension->id())); // Reload that tab, default title should come back. - ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank"))); EXPECT_EQ("hi!", GetBrowserActionsBar()->GetTooltip(extension->id())); } // Test that calling chrome.browserAction.setIcon() can set the icon for // extension. IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, SetIcon) { - ASSERT_TRUE(RunTest("browser_action/set_icon")) << message_; + ASSERT_TRUE(RunExtensionTest("browser_action/set_icon")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -608,7 +596,7 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, SetIcon) { // Test that calling chrome.browserAction.setPopup() can enable and change // a popup. IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, AddPopup) { - ASSERT_TRUE(RunTest("browser_action/add_popup")) << message_; + ASSERT_TRUE(RunExtensionTest("browser_action/add_popup")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -647,9 +635,8 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, AddPopup) { // a page which removes the popup using chrome.browserAction.setPopup(). { ResultCatcher catcher; - ui_test_utils::NavigateToURL( - browser(), - GURL(extension->GetResourceURL("change_popup.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("change_popup.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -664,7 +651,7 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, AddPopup) { // Test that calling chrome.browserAction.setPopup() can remove a popup. IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, RemovePopup) { // Load the extension, which has a browser action with a default popup. - ASSERT_TRUE(RunTest("browser_action/remove_popup")) << message_; + ASSERT_TRUE(RunExtensionTest("browser_action/remove_popup")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -683,9 +670,8 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, RemovePopup) { // Load a page which removes the popup using chrome.browserAction.setPopup(). { ResultCatcher catcher; - ui_test_utils::NavigateToURL( - browser(), - GURL(extension->GetResourceURL("remove_popup.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("remove_popup.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -699,8 +685,8 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, RemovePopup) { IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, IncognitoBasic) { ExtensionTestMessageListener ready_listener("ready", false); ASSERT_TRUE(embedded_test_server()->Start()); - scoped_refptr<const Extension> extension = LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("browser_action/basics")); + scoped_refptr<const Extension> extension = + LoadExtension(test_data_dir_.AppendASCII("browser_action/basics")); ASSERT_TRUE(extension) << message_; // Test that there is a browser action in the toolbar. @@ -733,9 +719,9 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, IncognitoBasic) { // Open a URL in the tab, so the event handler can check the tab's // "url" and "title" properties. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( incognito_browser, - embedded_test_server()->GetURL("/extensions/test_file.txt")); + embedded_test_server()->GetURL("/extensions/test_file.txt"))); ResultCatcher catcher; // Simulate the browser action being clicked. @@ -748,8 +734,8 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, IncognitoUpdate) { ASSERT_TRUE(embedded_test_server()->Start()); ExtensionTestMessageListener incognito_not_allowed_listener( "incognito not allowed", false); - scoped_refptr<const Extension> extension = LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("browser_action/update")); + scoped_refptr<const Extension> extension = + LoadExtension(test_data_dir_.AppendASCII("browser_action/update")); ASSERT_TRUE(extension) << message_; ASSERT_TRUE(incognito_not_allowed_listener.WaitUntilSatisfied()); // Test that there is a browser action in the toolbar. @@ -807,25 +793,34 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, IncognitoUpdate) { // Tests that events are dispatched to the correct profile for split mode // extensions. -// TODO(https://crbug.com/1212866): Crashes or times out when running as a -// Service Worker-based extension. When fixed, make this a -// BrowserActionApiTestWithContextType test. -IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, IncognitoSplit) { +IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, IncognitoSplit) { + ExtensionTestMessageListener listener_ready("regular ready", false); + ExtensionTestMessageListener incognito_ready("incognito ready", false); + + // Open an incognito browser. + // Note: It is important that we create incognito profile before loading + // |extension| below. "event_page" based test fails otherwise. + Browser* incognito_browser = CreateIncognitoBrowser(browser()->profile()); + ResultCatcher catcher; const Extension* extension = LoadExtension(test_data_dir_.AppendASCII("browser_action/split_mode"), {.allow_in_incognito = true}); ASSERT_TRUE(extension) << message_; - // Open an incognito browser. - Browser* incognito_browser = CreateIncognitoBrowser(browser()->profile()); ASSERT_EQ(1, ExtensionActionTestHelper::Create(incognito_browser) ->NumberOfBrowserActions()); + // NOTE: It is necessary to ensure that browser.onClicked listener was + // registered from the extension. Otherwise SW based extension occasionally + // times out. + EXPECT_TRUE(listener_ready.WaitUntilSatisfied()); + // A click in the regular profile should open a tab in the regular profile. ExecuteExtensionAction(browser(), extension); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); + EXPECT_TRUE(incognito_ready.WaitUntilSatisfied()); // A click in the incognito profile should open a tab in the // incognito profile. ExecuteExtensionAction(incognito_browser, extension); @@ -851,40 +846,13 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, CloseBackgroundPage) { ASSERT_EQ("", action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); - // A helper class to wait for the ExtensionHost to shut down. - // TODO(devlin): Hoist this somewhere more common and track down other similar - // usages. - class ExtensionHostDestructionObserver : public ExtensionHostObserver { - public: - explicit ExtensionHostDestructionObserver(ExtensionHost* host) { - host_observation_.Observe(host); - } - ExtensionHostDestructionObserver( - const ExtensionHostDestructionObserver& other) = delete; - ExtensionHostDestructionObserver& operator=( - const ExtensionHostDestructionObserver& other) = delete; - ~ExtensionHostDestructionObserver() override = default; - - void OnExtensionHostDestroyed(ExtensionHost* host) override { - ASSERT_TRUE(host_observation_.IsObservingSource(host)); - host_observation_.Reset(); - run_loop_.QuitWhenIdle(); - } - - void Wait() { run_loop_.Run(); } - - private: - base::RunLoop run_loop_; - base::ScopedObservation<ExtensionHost, ExtensionHostObserver> - host_observation_{this}; - }; - - ExtensionHostDestructionObserver host_destroyed_observer(extension_host); + ExtensionHostTestHelper host_destroyed_observer(profile()); + host_destroyed_observer.RestrictToHost(extension_host); // Click the browser action. ExecuteExtensionAction(browser(), extension); - host_destroyed_observer.Wait(); + host_destroyed_observer.WaitForHostDestroyed(); EXPECT_FALSE(manager->GetBackgroundHostForExtension(extension->id())); EXPECT_EQ("X", @@ -894,7 +862,7 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, CloseBackgroundPage) { IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, BadgeBackgroundColor) { ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(RunTest("browser_action/color")) << message_; + ASSERT_TRUE(RunExtensionTest("browser_action/color")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -908,24 +876,24 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, // Tell the extension to update the browser action state. ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update.html")))); ASSERT_TRUE(catcher.GetNextResult()); // Test that CSS values (#0F0) set color correctly. ASSERT_EQ(SkColorSetARGB(255, 0, 255, 0), action->GetBadgeBackgroundColor(ExtensionAction::kDefaultTabId)); - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update2.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update2.html")))); ASSERT_TRUE(catcher.GetNextResult()); // Test that array values set color correctly. ASSERT_EQ(SkColorSetARGB(255, 255, 255, 255), action->GetBadgeBackgroundColor(ExtensionAction::kDefaultTabId)); - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update3.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update3.html")))); ASSERT_TRUE(catcher.GetNextResult()); // Test that hsl() values 'hsl(120, 100%, 50%)' set color correctly. @@ -933,8 +901,8 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, action->GetBadgeBackgroundColor(ExtensionAction::kDefaultTabId)); // Test basic color keyword set correctly. - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update4.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update4.html")))); ASSERT_TRUE(catcher.GetNextResult()); ASSERT_EQ(SkColorSetARGB(255, 0, 0, 255), @@ -942,7 +910,7 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, } IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, Getters) { - ASSERT_TRUE(RunTest("browser_action/getters")) << message_; + ASSERT_TRUE(RunExtensionTest("browser_action/getters")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -951,13 +919,13 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, Getters) { // Test the getters for defaults. ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update.html")))); ASSERT_TRUE(catcher.GetNextResult()); // Test the getters for a specific tab. - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update2.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update2.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -966,15 +934,15 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, TestTriggerBrowserAction) { ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(RunTest("trigger_actions/browser_action")) << message_; + ASSERT_TRUE(RunExtensionTest("trigger_actions/browser_action")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; // Test that there is a browser action in the toolbar. ASSERT_EQ(1, GetBrowserActionsBar()->NumberOfBrowserActions()); - ui_test_utils::NavigateToURL(browser(), - embedded_test_server()->GetURL("/simple.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/simple.html"))); ExtensionAction* browser_action = GetBrowserAction(browser(), *extension); EXPECT_TRUE(browser_action); @@ -1003,7 +971,7 @@ IN_PROC_BROWSER_TEST_P(BrowserActionApiTestWithContextType, WithRectangularIcon) { ExtensionTestMessageListener ready_listener("ready", true); - const Extension* extension = LoadExtensionWithParamOptions( + const Extension* extension = LoadExtension( test_data_dir_.AppendASCII("browser_action").AppendASCII("rect_icon")); ASSERT_TRUE(extension); EXPECT_TRUE(ready_listener.WaitUntilSatisfied()); diff --git a/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc b/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc index 2d7dc883530..6bb6ddcc3b0 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/browser_action_interactive_test.cc @@ -5,6 +5,7 @@ #include <memory> #include "base/run_loop.h" +#include "base/scoped_observation.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" @@ -34,8 +35,9 @@ #include "extensions/browser/extension_action.h" #include "extensions/browser/extension_action_manager.h" #include "extensions/browser/extension_host.h" +#include "extensions/browser/extension_host_registry.h" +#include "extensions/browser/extension_host_test_helper.h" #include "extensions/browser/extension_registry.h" -#include "extensions/browser/notification_types.h" #include "extensions/common/extension.h" #include "extensions/common/extension_set.h" #include "extensions/common/mojom/view_type.mojom.h" @@ -59,18 +61,20 @@ namespace { // Helper to ensure all extension hosts are destroyed during the test. If a host // is still alive, the Profile can not be destroyed in -// BrowserProcessImpl::StartTearDown(). TODO(tapted): The existence of this -// helper is probably a bug. Extension hosts do not currently block shutdown the -// way a browser tab does. Maybe they should. See http://crbug.com/729476. -class PopupHostWatcher : public content::NotificationObserver { +// BrowserProcessImpl::StartTearDown(). +// TODO(tapted): The existence of this helper is probably a bug. Extension +// hosts do not currently block shutdown the way a browser tab does. Maybe they +// should. See http://crbug.com/729476. +class PopupHostWatcher : public ExtensionHostRegistry::Observer { public: - PopupHostWatcher() { - registrar_.Add(this, NOTIFICATION_EXTENSION_HOST_CREATED, - content::NotificationService::AllSources()); - registrar_.Add(this, NOTIFICATION_EXTENSION_HOST_DESTROYED, - content::NotificationService::AllSources()); + explicit PopupHostWatcher(content::BrowserContext* browser_context) { + host_registry_observation_.Observe( + ExtensionHostRegistry::Get(browser_context)); } + PopupHostWatcher(const PopupHostWatcher&) = delete; + PopupHostWatcher& operator=(const PopupHostWatcher&) = delete; + void Wait() { if (created_ == destroyed_) return; @@ -85,29 +89,40 @@ class PopupHostWatcher : public content::NotificationObserver { int created() const { return created_; } int destroyed() const { return destroyed_; } - // NotificationObserver: - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override { + // ExtensionHostRegistry::Observer: + void OnExtensionHostRenderProcessReady( + content::BrowserContext* browser_context, + ExtensionHost* host) override { + // Only track lifetimes for popup window ExtensionHost instances. + if (host->extension_host_type() != mojom::ViewType::kExtensionPopup) + return; + + ++created_; + QuitIfSatisfied(); + } + + void OnExtensionHostDestroyed(content::BrowserContext* browser_context, + ExtensionHost* host) override { // Only track lifetimes for popup window ExtensionHost instances. - const ExtensionHost* host = - content::Details<const ExtensionHost>(details).ptr(); - DCHECK(host); if (host->extension_host_type() != mojom::ViewType::kExtensionPopup) return; - ++(type == NOTIFICATION_EXTENSION_HOST_CREATED ? created_ : destroyed_); + ++destroyed_; + QuitIfSatisfied(); + } + + private: + void QuitIfSatisfied() { if (!quit_closure_.is_null() && created_ == destroyed_) quit_closure_.Run(); } - private: - content::NotificationRegistrar registrar_; base::RepeatingClosure quit_closure_; int created_ = 0; int destroyed_ = 0; - - DISALLOW_COPY_AND_ASSIGN(PopupHostWatcher); + base::ScopedObservation<ExtensionHostRegistry, + ExtensionHostRegistry::Observer> + host_registry_observation_{this}; }; // chrome.browserAction API tests that interact with the UI in such a way that @@ -116,12 +131,17 @@ class PopupHostWatcher : public content::NotificationObserver { class BrowserActionInteractiveTest : public ExtensionApiTest { public: BrowserActionInteractiveTest() {} + + BrowserActionInteractiveTest(const BrowserActionInteractiveTest&) = delete; + BrowserActionInteractiveTest& operator=(const BrowserActionInteractiveTest&) = + delete; + ~BrowserActionInteractiveTest() override {} // BrowserTestBase: void SetUpOnMainThread() override { - host_watcher_ = std::make_unique<PopupHostWatcher>(); ExtensionApiTest::SetUpOnMainThread(); + host_watcher_ = std::make_unique<PopupHostWatcher>(profile()); host_resolver()->AddRule("*", "127.0.0.1"); EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); } @@ -131,9 +151,11 @@ class BrowserActionInteractiveTest : public ExtensionApiTest { // called after this. But relying on the window close to close the // extension host can cause flakes. See http://crbug.com/729476. // Waiting here requires individual tests to ensure their popup has closed. - ExtensionApiTest::TearDownOnMainThread(); host_watcher_->Wait(); EXPECT_EQ(host_watcher_->created(), host_watcher_->destroyed()); + // Destroy the PopupHostWatcher to ensure it stops watching the profile. + host_watcher_.reset(); + ExtensionApiTest::TearDownOnMainThread(); } protected: @@ -191,9 +213,8 @@ class BrowserActionInteractiveTest : public ExtensionApiTest { // Trigger a focus loss to close the popup. void ClosePopupViaFocusLoss() { EXPECT_TRUE(ExtensionActionTestHelper::Create(browser())->HasPopup()); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, - content::NotificationService::AllSources()); + + ExtensionHostTestHelper host_helper(profile()); #if defined(OS_MAC) // ClickOnView() in an inactive window is not robust on Mac. The click does @@ -213,7 +234,7 @@ class BrowserActionInteractiveTest : public ExtensionApiTest { // Wait for the notification to achieve a consistent state and verify that // the popup was properly torn down. - observer.Wait(); + host_helper.WaitForHostDestroyed(); base::RunLoop().RunUntilIdle(); } @@ -221,8 +242,6 @@ class BrowserActionInteractiveTest : public ExtensionApiTest { private: std::unique_ptr<PopupHostWatcher> host_watcher_; - - DISALLOW_COPY_AND_ASSIGN(BrowserActionInteractiveTest); }; // Tests opening a popup using the chrome.browserAction.openPopup API. This test @@ -390,13 +409,11 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, TabSwitchClosesPopup) { browser()->tab_strip_model()->GetActiveWebContents()); OpenPopupViaAPI(false); - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, - content::NotificationService::AllSources()); + ExtensionHostTestHelper host_helper(profile()); // Change active tabs, the extension popup should close. browser()->tab_strip_model()->ActivateTabAt( 0, {TabStripModel::GestureType::kOther}); - observer.Wait(); + host_helper.WaitForHostDestroyed(); EXPECT_FALSE(ExtensionActionTestHelper::Create(browser())->HasPopup()); } @@ -430,8 +447,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, PopupZoomsIndependently) { ASSERT_TRUE(extension) << message_; // Navigate to one of the extension's pages in a tab. - ui_test_utils::NavigateToURL(browser(), - extension->GetResourceURL("popup.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension->GetResourceURL("popup.html"))); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -448,13 +465,10 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, PopupZoomsIndependently) { zoom_change_watcher.Wait(); // Open the extension's popup. - content::WindowedNotificationObserver popup_observer( - NOTIFICATION_EXTENSION_HOST_CREATED, - content::NotificationService::AllSources()); + ExtensionHostTestHelper host_helper(profile(), extension->id()); OpenPopupViaToolbar(extension->id()); - popup_observer.Wait(); - ExtensionHost* extension_host = - content::Details<ExtensionHost>(popup_observer.details()).ptr(); + ExtensionHost* extension_host = host_helper.WaitForRenderProcessReady(); + ASSERT_TRUE(extension_host); content::WebContents* popup_contents = extension_host->host_contents(); // The popup should not use the per-origin zoom level that was set by zooming @@ -494,10 +508,13 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, PopupZoomsIndependently) { class BrowserActionInteractiveViewsTest : public BrowserActionInteractiveTest { public: BrowserActionInteractiveViewsTest() = default; - ~BrowserActionInteractiveViewsTest() override = default; - private: - DISALLOW_COPY_AND_ASSIGN(BrowserActionInteractiveViewsTest); + BrowserActionInteractiveViewsTest(const BrowserActionInteractiveViewsTest&) = + delete; + BrowserActionInteractiveViewsTest& operator=( + const BrowserActionInteractiveViewsTest&) = delete; + + ~BrowserActionInteractiveViewsTest() override = default; }; // Test closing the browser while inspecting an extension popup with dev tools. @@ -573,7 +590,13 @@ class MainFrameSizeWaiter : public content::WebContentsObserver { base::RunLoop run_loop_; }; -IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, BrowserActionPopup) { +// TODO(crbug.com/1249851): Test crashes on Windows +#if defined(OS_WIN) +#define MAYBE_BrowserActionPopup DISABLED_BrowserActionPopup +#else +#define MAYBE_BrowserActionPopup BrowserActionPopup +#endif +IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, MAYBE_BrowserActionPopup) { ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("browser_action/popup"))); const Extension* extension = GetSingleLoadedExtension(); diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc index 6463c89b6e4..7b30965ec9d 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.cc @@ -30,7 +30,6 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/toolbar_actions_model.h" #include "components/sessions/content/session_tab_helper.h" -#include "content/public/browser/notification_service.h" #include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/browser/api/declarative_net_request/utils.h" #include "extensions/browser/event_router.h" @@ -39,7 +38,6 @@ #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_util.h" -#include "extensions/browser/notification_types.h" #include "extensions/common/api/extension_action/action_info.h" #include "extensions/common/error_utils.h" #include "extensions/common/feature_switch.h" @@ -283,18 +281,19 @@ bool ExtensionActionFunction::ExtractDataFromArguments() { // The tabId might appear in details (if it exists), as the first // argument besides the action type (depends on the function), or be omitted // entirely. - base::Value* first_arg = NULL; - if (!args_->Get(0, &first_arg)) + if (args().empty()) return true; - switch (first_arg->type()) { + base::Value& first_arg = mutable_args()[0]; + + switch (first_arg.type()) { case base::Value::Type::INTEGER: - tab_id_ = first_arg->GetInt(); + tab_id_ = first_arg.GetInt(); break; case base::Value::Type::DICTIONARY: { // Found the details argument. - details_ = static_cast<base::DictionaryValue*>(first_arg); + details_ = static_cast<base::DictionaryValue*>(&first_arg); // Still need to check for the tabId within details. base::Value* tab_id_value = NULL; if (details_->Get("tabId", &tab_id_value)) { @@ -540,10 +539,10 @@ ExtensionFunction::ResponseAction ExtensionActionGetBadgeBackgroundColorFunction::RunExtensionAction() { std::unique_ptr<base::ListValue> list(new base::ListValue()); SkColor color = extension_action_->GetBadgeBackgroundColor(tab_id_); - list->AppendInteger(static_cast<int>(SkColorGetR(color))); - list->AppendInteger(static_cast<int>(SkColorGetG(color))); - list->AppendInteger(static_cast<int>(SkColorGetB(color))); - list->AppendInteger(static_cast<int>(SkColorGetA(color))); + list->Append(static_cast<int>(SkColorGetR(color))); + list->Append(static_cast<int>(SkColorGetG(color))); + list->Append(static_cast<int>(SkColorGetB(color))); + list->Append(static_cast<int>(SkColorGetA(color))); return RespondNow( OneArgument(base::Value::FromUniquePtrValue(std::move(list)))); } @@ -577,6 +576,7 @@ ExtensionFunction::ResponseAction ActionGetUserSettingsFunction::Run() { } BrowserActionOpenPopupFunction::BrowserActionOpenPopupFunction() = default; +BrowserActionOpenPopupFunction::~BrowserActionOpenPopupFunction() = default; ExtensionFunction::ResponseAction BrowserActionOpenPopupFunction::Run() { // We only allow the popup in the active window. @@ -608,8 +608,7 @@ ExtensionFunction::ResponseAction BrowserActionOpenPopupFunction::Run() { // If the extension is spanning, then extension hosts are created with the // original profile, and if it's split, then we know the api call came from // the right profile. - registrar_.Add(this, NOTIFICATION_EXTENSION_HOST_DID_STOP_FIRST_LOAD, - content::Source<Profile>(profile)); + host_registry_observation_.Observe(ExtensionHostRegistry::Get(profile)); // Set a timeout for waiting for the notification that the popup is loaded. // Waiting is required so that the popup view can be retrieved by the custom @@ -618,10 +617,19 @@ ExtensionFunction::ResponseAction BrowserActionOpenPopupFunction::Run() { base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&BrowserActionOpenPopupFunction::OpenPopupTimedOut, this), - base::TimeDelta::FromSeconds(10)); + base::Seconds(10)); return RespondLater(); } +void BrowserActionOpenPopupFunction::OnBrowserContextShutdown() { + // No point in responding at this point (the context is gone). However, we + // need to explicitly remove the ExtensionHostRegistry observation, since the + // ExtensionHostRegistry's lifetime is tied to the BrowserContext. Otherwise, + // this would cause a UAF when the observation is destructed as part of this + // instance's destruction. + host_registry_observation_.Reset(); +} + void BrowserActionOpenPopupFunction::OpenPopupTimedOut() { if (did_respond()) return; @@ -630,21 +638,18 @@ void BrowserActionOpenPopupFunction::OpenPopupTimedOut() { Respond(Error(kOpenPopupError)); } -void BrowserActionOpenPopupFunction::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - DCHECK_EQ(NOTIFICATION_EXTENSION_HOST_DID_STOP_FIRST_LOAD, type); +void BrowserActionOpenPopupFunction::OnExtensionHostCompletedFirstLoad( + content::BrowserContext* browser_context, + ExtensionHost* host) { if (did_respond()) return; - ExtensionHost* host = content::Details<ExtensionHost>(details).ptr(); if (host->extension_host_type() != mojom::ViewType::kExtensionPopup || host->extension()->id() != extension_->id()) return; Respond(NoArguments()); - registrar_.RemoveAll(); + host_registry_observation_.Reset(); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h index 1fa5f9d74eb..501ed8759b8 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h +++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_api.h @@ -9,12 +9,12 @@ #include "base/macros.h" #include "base/observer_list.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" +#include "base/scoped_observation.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/extension_action.h" #include "extensions/browser/extension_event_histogram_value.h" #include "extensions/browser/extension_function.h" +#include "extensions/browser/extension_host_registry.h" #include "third_party/skia/include/core/SkColor.h" namespace base { @@ -29,6 +29,7 @@ class WebContents; class Browser; namespace extensions { +class ExtensionHost; class ExtensionPrefs; class ExtensionActionAPI : public BrowserContextKeyedAPI { @@ -55,6 +56,10 @@ class ExtensionActionAPI : public BrowserContextKeyedAPI { }; explicit ExtensionActionAPI(content::BrowserContext* context); + + ExtensionActionAPI(const ExtensionActionAPI&) = delete; + ExtensionActionAPI& operator=(const ExtensionActionAPI&) = delete; + ~ExtensionActionAPI() override; // Convenience method to get the instance for a profile. @@ -112,8 +117,6 @@ class ExtensionActionAPI : public BrowserContextKeyedAPI { content::BrowserContext* browser_context_; ExtensionPrefs* extension_prefs_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionActionAPI); }; // Implementation of the browserAction and pageAction APIs. @@ -454,26 +457,34 @@ class BrowserActionDisableFunction : public ExtensionActionHideFunction { }; class BrowserActionOpenPopupFunction : public ExtensionFunction, - public content::NotificationObserver { + public ExtensionHostRegistry::Observer { public: DECLARE_EXTENSION_FUNCTION("browserAction.openPopup", BROWSERACTION_OPEN_POPUP) BrowserActionOpenPopupFunction(); + BrowserActionOpenPopupFunction(const BrowserActionOpenPopupFunction&) = + delete; + BrowserActionOpenPopupFunction& operator=( + const BrowserActionOpenPopupFunction&) = delete; + private: - ~BrowserActionOpenPopupFunction() override {} + ~BrowserActionOpenPopupFunction() override; // ExtensionFunction: ResponseAction Run() override; + void OnBrowserContextShutdown() override; - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; - void OpenPopupTimedOut(); + // ExtensionHostRegistry::Observer: + void OnExtensionHostCompletedFirstLoad( + content::BrowserContext* browser_context, + ExtensionHost* host) override; - content::NotificationRegistrar registrar_; + void OpenPopupTimedOut(); - DISALLOW_COPY_AND_ASSIGN(BrowserActionOpenPopupFunction); + base::ScopedObservation<ExtensionHostRegistry, + ExtensionHostRegistry::Observer> + host_registry_observation_{this}; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc index 408ae9e0781..58715e01eb3 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/extension_action_apitest.cc @@ -12,6 +12,7 @@ #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" #include "chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h" #include "chrome/browser/extensions/api/extension_action/test_icon_image_observer.h" #include "chrome/browser/extensions/extension_apitest.h" @@ -46,11 +47,16 @@ namespace { // A background script that allows for setting the icon dynamically. constexpr char kSetIconBackgroundJsTemplate[] = R"(function setIcon(details) { - chrome.%s.setIcon(details, () => { - chrome.test.assertNoLastError(); - chrome.test.notifyPass(); - }); - })"; + chrome.%s.setIcon(details, () => { + chrome.test.assertNoLastError(); + chrome.test.notifyPass(); + }); + } + function setIconPromise(details) { + chrome.%s.setIcon(details) + .then(chrome.test.notifyPass) + .catch(chrome.test.notifyFail); + })"; constexpr char kPageHtmlTemplate[] = R"(<html><script src="page.js"></script></html>)"; @@ -74,6 +80,10 @@ class TestStateStoreObserver : public StateStore::TestObserver { : extension_id_(extension_id) { scoped_observation_.Observe(ExtensionSystem::Get(context)->state_store()); } + + TestStateStoreObserver(const TestStateStoreObserver&) = delete; + TestStateStoreObserver& operator=(const TestStateStoreObserver&) = delete; + ~TestStateStoreObserver() override {} void WillSetExtensionValue(const std::string& extension_id, @@ -93,8 +103,6 @@ class TestStateStoreObserver : public StateStore::TestObserver { base::ScopedObservation<StateStore, StateStore::TestObserver> scoped_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(TestStateStoreObserver); }; // A helper class to handle setting or getting the values for an action from JS. @@ -110,6 +118,10 @@ class ActionTestHelper { get_method_name_(get_method_name), js_property_key_(js_property_key), web_contents_(web_contents) {} + + ActionTestHelper(const ActionTestHelper&) = delete; + ActionTestHelper& operator=(const ActionTestHelper&) = delete; + ~ActionTestHelper() = default; // Checks the value for the given |tab_id|. @@ -176,8 +188,6 @@ class ActionTestHelper { const char* const js_property_key_; // The WebContents to use to execute API calls. content::WebContents* const web_contents_; - - DISALLOW_COPY_AND_ASSIGN(ActionTestHelper); }; // Forces a flush of the StateStore, where action state is persisted. @@ -369,7 +379,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, // Navigating should clear the title. GURL second_url = embedded_test_server()->GetURL("/title2.html"); - ui_test_utils::NavigateToURL(browser(), second_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), second_url)); EXPECT_EQ(second_url, web_contents->GetLastCommittedURL()); EXPECT_FALSE(action->HasTitle(tab_id)); @@ -549,8 +559,16 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, PopupCreation) { // Tests that sessionStorage does not persist between closing and opening of a // popup. +// TODO(crbug/1256760): Flaky on Linux. +#if defined(OS_LINUX) +#define MAYBE_SessionStorageDoesNotPersistBetweenOpenings \ + DISABLED_SessionStorageDoesNotPersistBetweenOpenings +#else +#define MAYBE_SessionStorageDoesNotPersistBetweenOpenings \ + SessionStorageDoesNotPersistBetweenOpenings +#endif IN_PROC_BROWSER_TEST_P(MultiActionAPITest, - SessionStorageDoesNotPersistBetweenOpenings) { + MAYBE_SessionStorageDoesNotPersistBetweenOpenings) { constexpr char kManifestTemplate[] = R"({ "name": "Test sessionStorage", @@ -741,6 +759,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPICanvasTest, DynamicSetIcon) { test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), kPageHtmlTemplate); test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), base::StringPrintf(kSetIconBackgroundJsTemplate, + GetAPINameForActionType(GetParam()), GetAPINameForActionType(GetParam()))); test_dir.CopyFileTo(test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"), FILE_PATH_LITERAL("blue_icon.png")); @@ -834,6 +853,19 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPICanvasTest, DynamicSetIcon) { EXPECT_FALSE(new_tab_icon.IsEmpty()); EXPECT_EQ(SK_ColorGREEN, new_tab_icon.AsBitmap().getColor(mid_x, mid_y)); + // Manifest V3 extensions using the action API should also be able to use a + // promise version of setIcon. + if (GetManifestVersionForActionType(GetParam()) == 3) { + constexpr char kSetIconPromiseScript[] = + "setIconPromise({tabId: %d, path: 'blue_icon.png'});"; + RunTestAndWaitForSuccess( + web_contents, base::StringPrintf(kSetIconPromiseScript, new_tab_id)); + + new_tab_icon = toolbar_helper->GetIcon(extension->id()); + EXPECT_FALSE(new_tab_icon.IsEmpty()); + EXPECT_EQ(SK_ColorBLUE, new_tab_icon.AsBitmap().getColor(mid_x, mid_y)); + } + // Switch back to the first tab. The icon should still be red, since the other // changes were for specific tabs. browser()->tab_strip_model()->ActivateTabAt(0); @@ -864,6 +896,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, SetIconWithJavascriptHooks) { test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), kPageHtmlTemplate); test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), base::StringPrintf(kSetIconBackgroundJsTemplate, + GetAPINameForActionType(GetParam()), GetAPINameForActionType(GetParam()))); test_dir.CopyFileTo(test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"), FILE_PATH_LITERAL("blue_icon.png")); @@ -934,6 +967,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, SetIconWithSelfDefined) { test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), kPageHtmlTemplate); test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), base::StringPrintf(kSetIconBackgroundJsTemplate, + GetAPINameForActionType(GetParam()), GetAPINameForActionType(GetParam()))); test_dir.CopyFileTo(test_data_dir_.AppendASCII("icon_rgb_0_0_255.png"), FILE_PATH_LITERAL("blue_icon.png")); diff --git a/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc b/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc index 002338fa762..7c8ef6f371e 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/page_action_apitest.cc @@ -36,7 +36,7 @@ using ContextType = ExtensionBrowserTest::ContextType; class PageActionApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - PageActionApiTest() = default; + PageActionApiTest() : ExtensionApiTest(GetParam()) {} ~PageActionApiTest() override = default; PageActionApiTest(const PageActionApiTest&) = delete; PageActionApiTest& operator=(const PageActionApiTest&) = delete; @@ -50,12 +50,6 @@ class PageActionApiTest : public ExtensionApiTest, ? extension_action : nullptr; } - - bool RunTest(const char* name) { - return RunExtensionTest( - name, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -67,14 +61,14 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, IN_PROC_BROWSER_TEST_P(PageActionApiTest, Basic) { ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(RunTest("page_action/basics")) << message_; + ASSERT_TRUE(RunExtensionTest("page_action/basics")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; { // Tell the extension to update the page action state. ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -99,8 +93,8 @@ IN_PROC_BROWSER_TEST_P(PageActionApiTest, Basic) { { // Tell the extension to update the page action state again. ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update2.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update2.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -119,7 +113,7 @@ IN_PROC_BROWSER_TEST_P(PageActionApiTest, Basic) { // Test that calling chrome.pageAction.setPopup() can enable a popup. IN_PROC_BROWSER_TEST_P(PageActionApiTest, AddPopup) { // Load the extension, which has no default popup. - ASSERT_TRUE(RunTest("page_action/add_popup")) << message_; + ASSERT_TRUE(RunExtensionTest("page_action/add_popup")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -152,9 +146,8 @@ IN_PROC_BROWSER_TEST_P(PageActionApiTest, AddPopup) { // Load a page which removes the popup using chrome.pageAction.setPopup(). { ResultCatcher catcher; - ui_test_utils::NavigateToURL( - browser(), - GURL(extension->GetResourceURL("change_popup.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("change_popup.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -166,7 +159,7 @@ IN_PROC_BROWSER_TEST_P(PageActionApiTest, AddPopup) { // Test that calling chrome.pageAction.setPopup() can remove a popup. IN_PROC_BROWSER_TEST_P(PageActionApiTest, RemovePopup) { // Load the extension, which has a page action with a default popup. - ASSERT_TRUE(RunTest("page_action/remove_popup")) << message_; + ASSERT_TRUE(RunExtensionTest("page_action/remove_popup")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; @@ -183,9 +176,8 @@ IN_PROC_BROWSER_TEST_P(PageActionApiTest, RemovePopup) { // Load a page which removes the popup using chrome.pageAction.setPopup(). { ResultCatcher catcher; - ui_test_utils::NavigateToURL( - browser(), - GURL(extension->GetResourceURL("remove_popup.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("remove_popup.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -196,29 +188,24 @@ IN_PROC_BROWSER_TEST_P(PageActionApiTest, RemovePopup) { // Test http://crbug.com/57333: that two page action extensions using the same // icon for the page action icon and the extension icon do not crash. IN_PROC_BROWSER_TEST_P(PageActionApiTest, TestCrash57333) { - const bool load_as_service_worker = GetParam() == ContextType::kServiceWorker; // Load extension A. - ASSERT_TRUE( - LoadExtension(test_data_dir_.AppendASCII("page_action") - .AppendASCII("crash_57333") - .AppendASCII("Extension1"), - {.load_as_service_worker = load_as_service_worker})); + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("page_action") + .AppendASCII("crash_57333") + .AppendASCII("Extension1"))); // Load extension B. - ASSERT_TRUE( - LoadExtension(test_data_dir_.AppendASCII("page_action") - .AppendASCII("crash_57333") - .AppendASCII("Extension2"), - {.load_as_service_worker = load_as_service_worker})); + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("page_action") + .AppendASCII("crash_57333") + .AppendASCII("Extension2"))); } IN_PROC_BROWSER_TEST_P(PageActionApiTest, Getters) { - ASSERT_TRUE(RunTest("page_action/getters")) << message_; + ASSERT_TRUE(RunExtensionTest("page_action/getters")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - GURL(extension->GetResourceURL("update.html"))); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL(extension->GetResourceURL("update.html")))); ASSERT_TRUE(catcher.GetNextResult()); } @@ -226,13 +213,13 @@ IN_PROC_BROWSER_TEST_P(PageActionApiTest, Getters) { IN_PROC_BROWSER_TEST_P(PageActionApiTest, TestTriggerPageAction) { ASSERT_TRUE(embedded_test_server()->Start()); - ASSERT_TRUE(RunTest("trigger_actions/page_action")) << message_; + ASSERT_TRUE(RunExtensionTest("trigger_actions/page_action")) << message_; const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; // Page action icon is displayed when a tab is created. - ui_test_utils::NavigateToURL(browser(), - embedded_test_server()->GetURL("/simple.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/simple.html"))); chrome::NewTab(browser()); browser()->tab_strip_model()->ActivateTabAt( 0, {TabStripModel::GestureType::kOther}); diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h index e2423448cf2..e55d1afec29 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h +++ b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h @@ -29,6 +29,12 @@ class TestExtensionActionAPIObserver : public ExtensionActionAPI::Observer { content::BrowserContext* context, const ExtensionId& extension_id, const std::set<content::WebContents*>& contents_to_observe); + + TestExtensionActionAPIObserver(const TestExtensionActionAPIObserver&) = + delete; + TestExtensionActionAPIObserver& operator=( + const TestExtensionActionAPIObserver&) = delete; + ~TestExtensionActionAPIObserver() override; // Waits until the extension action is updated and the update is seen for all @@ -57,8 +63,6 @@ class TestExtensionActionAPIObserver : public ExtensionActionAPI::Observer { // An optional set of web contents to observe for extension action updates. std::set<content::WebContents*> contents_to_observe_; - - DISALLOW_COPY_AND_ASSIGN(TestExtensionActionAPIObserver); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h index 310eef3c44f..172f11e66f6 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h +++ b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h @@ -19,6 +19,10 @@ class Extension; class TestIconImageObserver : public IconImage::Observer { public: TestIconImageObserver(); + + TestIconImageObserver(const TestIconImageObserver&) = delete; + TestIconImageObserver& operator=(const TestIconImageObserver&) = delete; + ~TestIconImageObserver() override; void Wait(IconImage* icon); @@ -33,8 +37,6 @@ class TestIconImageObserver : public IconImage::Observer { base::RunLoop run_loop_; base::ScopedObservation<IconImage, IconImage::Observer> observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(TestIconImageObserver); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h b/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h index 8507c8f3d15..eb802bfe505 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h +++ b/chromium/chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h @@ -16,6 +16,11 @@ namespace extensions { class ChromeFeedbackPrivateDelegate : public FeedbackPrivateDelegate { public: ChromeFeedbackPrivateDelegate(); + + ChromeFeedbackPrivateDelegate(const ChromeFeedbackPrivateDelegate&) = delete; + ChromeFeedbackPrivateDelegate& operator=( + const ChromeFeedbackPrivateDelegate&) = delete; + ~ChromeFeedbackPrivateDelegate() override; // FeedbackPrivateDelegate: @@ -40,9 +45,6 @@ class ChromeFeedbackPrivateDelegate : public FeedbackPrivateDelegate { void NotifyFeedbackDelayed() const override; feedback::FeedbackUploader* GetFeedbackUploaderForContext( content::BrowserContext* context) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeFeedbackPrivateDelegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc b/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc index 0f308b5c299..d27d0d4949f 100644 --- a/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/feedback_private/feedback_browsertest.cc @@ -64,11 +64,12 @@ class FeedbackTest : public ExtensionBrowserTest { void StartFeedbackUI(FeedbackFlow flow, const std::string& extra_diagnostics, bool from_assistant = false, - bool include_bluetooth_logs = false) { + bool include_bluetooth_logs = false, + bool show_questionnaire = false) { base::OnceClosure callback = base::BindOnce(&StopMessageLoopCallback); extensions::FeedbackPrivateGetStringsFunction::set_test_callback(&callback); InvokeFeedbackUI(flow, extra_diagnostics, from_assistant, - include_bluetooth_logs); + include_bluetooth_logs, show_questionnaire); content::RunMessageLoop(); extensions::FeedbackPrivateGetStringsFunction::set_test_callback(nullptr); } @@ -87,14 +88,15 @@ class FeedbackTest : public ExtensionBrowserTest { void InvokeFeedbackUI(FeedbackFlow flow, const std::string& extra_diagnostics, bool from_assistant, - bool include_bluetooth_logs) { + bool include_bluetooth_logs, + bool show_questionnaire) { extensions::FeedbackPrivateAPI* api = extensions::FeedbackPrivateAPI::GetFactoryInstance()->Get( browser()->profile()); - api->RequestFeedbackForFlow("Test description", "Test placeholder", - "Test tag", extra_diagnostics, - GURL("http://www.test.com"), flow, - from_assistant, include_bluetooth_logs); + api->RequestFeedbackForFlow( + "Test description", "Test placeholder", "Test tag", extra_diagnostics, + GURL("http://www.test.com"), flow, from_assistant, + include_bluetooth_logs, show_questionnaire); } }; @@ -110,7 +112,7 @@ class TestFeedbackUploaderDelegate base::RunLoop* quit_on_dispatch_; }; -// Disabled due to flake: https://crbug.com/1240591 +// TODO(crbug.com/1241504): disable tests. IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_ShowFeedback) { WaitForExtensionViewsToLoad(); @@ -119,7 +121,7 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_ShowFeedback) { VerifyFeedbackAppLaunch(); } -// Disabled due to flake: https://crbug.com/1240591 +// TODO(crbug.com/1241504): disable tests. IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_ShowLoginFeedback) { WaitForExtensionViewsToLoad(); @@ -143,7 +145,7 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_ShowLoginFeedback) { } // Tests that there's an option in the email drop down box with a value ''. -// Disabled due to flake: https://crbug.com/1240591 +// TODO(crbug.com/1241504): disable tests. IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_AnonymousUser) { WaitForExtensionViewsToLoad(); @@ -175,7 +177,7 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_AnonymousUser) { // Ensures that when extra diagnostics are provided with feedback, they are // injected properly in the system information. -// Disabled due to flake: https://crbug.com/1240591 +// TODO(crbug.com/1241504): disable tests. IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_ExtraDiagnostics) { WaitForExtensionViewsToLoad(); @@ -287,6 +289,107 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, ProvideBluetoothLogs) { &bool_result)); EXPECT_TRUE(bool_result); } + +// Ensures that when triggered from a Google account and a Bluetooth related +// string is entered into the description, that we append Bluetooth-related +// questions to the issue description. +IN_PROC_BROWSER_TEST_F(FeedbackTest, AppendQuestionnaire) { + WaitForExtensionViewsToLoad(); + + ASSERT_TRUE(IsFeedbackAppAvailable()); + StartFeedbackUI(FeedbackFlow::FEEDBACK_FLOW_GOOGLEINTERNAL, std::string(), + /*from_assistant*/ false, /*include_bluetooth_logs*/ true, + /*show_questionnaire*/ true); + VerifyFeedbackAppLaunch(); + + AppWindow* const window = + PlatformAppBrowserTest::GetFirstAppWindowForBrowser(browser()); + ASSERT_TRUE(window); + content::WebContents* const content = window->web_contents(); + + // Questionnaire shouldn't be visible until we put the Bluetooth text into the + // description. + bool bool_result = false; + ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + content, + "domAutomationController.send(" + " ((function() {" + " return !$('description-text').value.includes('please answer');" + " })()));", + &bool_result)); + EXPECT_TRUE(bool_result); + + // Bluetooth questions should appear. + bool_result = false; + ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + content, + "domAutomationController.send(" + " ((function() {" + " var elem = document.getElementById('description-text');" + " elem.value = 'bluetooth';" + " elem.dispatchEvent(new Event('input', {}));" + " return elem.value.includes('please answer')" + " && elem.value.includes('[Bluetooth]')" + " && !elem.value.includes('[WiFi]');" + " })()));", + &bool_result)); + EXPECT_TRUE(bool_result); + + // WiFi questions should appear. + bool_result = false; + ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + content, + "domAutomationController.send(" + " ((function() {" + " var elem = document.getElementById('description-text');" + " elem.value = 'wifi issue';" + " elem.dispatchEvent(new Event('input', {}));" + " return elem.value.includes('[WiFi]');" + " })()));", + &bool_result)); + EXPECT_TRUE(bool_result); +} + +// Questionnaires should not be displayed if it's not a Googler session. +IN_PROC_BROWSER_TEST_F(FeedbackTest, AppendQuestionnaireNotGoogler) { + WaitForExtensionViewsToLoad(); + + ASSERT_TRUE(IsFeedbackAppAvailable()); + StartFeedbackUI(FeedbackFlow::FEEDBACK_FLOW_REGULAR, std::string(), + /*from_assistant*/ false, /*include_bluetooth_logs*/ false, + /*show_questionnaire*/ false); + VerifyFeedbackAppLaunch(); + + AppWindow* const window = + PlatformAppBrowserTest::GetFirstAppWindowForBrowser(browser()); + ASSERT_TRUE(window); + content::WebContents* const content = window->web_contents(); + + // Questionnaire shouldn't be visible in the beginning. + bool bool_result = false; + ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + content, + "domAutomationController.send(" + " ((function() {" + " return !$('description-text').value.includes('[Bluetooth]');" + " })()));", + &bool_result)); + EXPECT_TRUE(bool_result); + + // Questionnaire should not appear even with a Bluetooth keyword. + bool_result = false; + ASSERT_TRUE(content::ExecuteScriptAndExtractBool( + content, + "domAutomationController.send(" + " ((function() {" + " var elem = document.getElementById('description-text');" + " elem.value = 'bluetooth';" + " elem.dispatchEvent(new Event('input', {}));" + " return !elem.value.includes('please answer');" + " })()));", + &bool_result)); + EXPECT_TRUE(bool_result); +} #endif // BUILDFLAG(IS_CHROMEOS_ASH) // Disabled due to flake: https://crbug.com/1069870 @@ -300,7 +403,7 @@ IN_PROC_BROWSER_TEST_F(FeedbackTest, DISABLED_GetTargetTabUrl) { for (const auto& test_case : test_cases) { GURL expected_url = GURL(test_case.second); - ui_test_utils::NavigateToURL(browser(), GURL(test_case.first)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL(test_case.first))); // Sanity check that we always have one tab in the browser. ASSERT_EQ(browser()->tab_strip_model()->count(), 1); diff --git a/chromium/chrome/browser/extensions/api/file_handlers/non_native_file_system_delegate_chromeos.h b/chromium/chrome/browser/extensions/api/file_handlers/non_native_file_system_delegate_chromeos.h index f7fadf8059d..7621d2147a7 100644 --- a/chromium/chrome/browser/extensions/api/file_handlers/non_native_file_system_delegate_chromeos.h +++ b/chromium/chrome/browser/extensions/api/file_handlers/non_native_file_system_delegate_chromeos.h @@ -22,6 +22,12 @@ class NonNativeFileSystemDelegateChromeOS : public extensions::NonNativeFileSystemDelegate { public: NonNativeFileSystemDelegateChromeOS(); + + NonNativeFileSystemDelegateChromeOS( + const NonNativeFileSystemDelegateChromeOS&) = delete; + NonNativeFileSystemDelegateChromeOS& operator=( + const NonNativeFileSystemDelegateChromeOS&) = delete; + ~NonNativeFileSystemDelegateChromeOS() override; // extensions::NonNativeFileSystemDelegate: @@ -42,9 +48,6 @@ class NonNativeFileSystemDelegateChromeOS content::BrowserContext* context, const base::FilePath& path, base::OnceCallback<void(bool)> callback) override; - - private: - DISALLOW_COPY_AND_ASSIGN(NonNativeFileSystemDelegateChromeOS); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/file_system/OWNERS b/chromium/chrome/browser/extensions/api/file_system/OWNERS index 64f66776b4a..babd8458cd4 100644 --- a/chromium/chrome/browser/extensions/api/file_system/OWNERS +++ b/chromium/chrome/browser/extensions/api/file_system/OWNERS @@ -1,2 +1,2 @@ -benwells@chromium.org sammc@chromium.org +file://ui/file_manager/OWNERS diff --git a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h index 721d2068f1b..25f7a96435f 100644 --- a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h +++ b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h @@ -28,6 +28,10 @@ void DispatchVolumeListChangeEvent(content::BrowserContext* browser_context); class ChromeFileSystemDelegate : public FileSystemDelegate { public: ChromeFileSystemDelegate(); + + ChromeFileSystemDelegate(const ChromeFileSystemDelegate&) = delete; + ChromeFileSystemDelegate& operator=(const ChromeFileSystemDelegate&) = delete; + ~ChromeFileSystemDelegate() override; // FileSystemDelegate: @@ -64,9 +68,6 @@ class ChromeFileSystemDelegate : public FileSystemDelegate { #endif // BUILDFLAG(IS_CHROMEOS_ASH) SavedFilesServiceInterface* GetSavedFilesService( content::BrowserContext* browser_context) override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeFileSystemDelegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/file_system/consent_provider.cc b/chromium/chrome/browser/extensions/api/file_system/consent_provider.cc index 8044f7b35f8..70ad9360ab5 100644 --- a/chromium/chrome/browser/extensions/api/file_system/consent_provider.cc +++ b/chromium/chrome/browser/extensions/api/file_system/consent_provider.cc @@ -32,9 +32,8 @@ namespace { // List of allowlisted component apps and extensions by their ids for // chrome.fileSystem.requestFileSystem. const char* const kRequestFileSystemComponentAllowlist[] = { - file_manager::kFileManagerAppId, file_manager::kVideoPlayerAppId, - file_manager::kAudioPlayerAppId, file_manager::kImageLoaderExtensionId, - file_manager::kZipArchiverId, + file_manager::kFileManagerAppId, file_manager::kAudioPlayerAppId, + file_manager::kImageLoaderExtensionId, // TODO(henryhsu,b/110126438): Remove this extension id, and add it only // for tests. "pkplfbidichfdicaijlchgnapepdginl" // Testing extensions. diff --git a/chromium/chrome/browser/extensions/api/file_system/consent_provider.h b/chromium/chrome/browser/extensions/api/file_system/consent_provider.h index 722aacfdc76..501bd2566c4 100644 --- a/chromium/chrome/browser/extensions/api/file_system/consent_provider.h +++ b/chromium/chrome/browser/extensions/api/file_system/consent_provider.h @@ -69,6 +69,10 @@ class ConsentProvider { }; explicit ConsentProvider(DelegateInterface* delegate); + + ConsentProvider(const ConsentProvider&) = delete; + ConsentProvider& operator=(const ConsentProvider&) = delete; + ~ConsentProvider(); // Requests consent for granting |writable| permissions to the |volume| @@ -91,8 +95,6 @@ class ConsentProvider { private: DelegateInterface* const delegate_; - - DISALLOW_COPY_AND_ASSIGN(ConsentProvider); }; // Handles interaction with user as well as environment checks (allowlists, @@ -100,6 +102,10 @@ class ConsentProvider { class ConsentProviderDelegate : public ConsentProvider::DelegateInterface { public: explicit ConsentProviderDelegate(Profile* profile); + + ConsentProviderDelegate(const ConsentProviderDelegate&) = delete; + ConsentProviderDelegate& operator=(const ConsentProviderDelegate&) = delete; + ~ConsentProviderDelegate(); private: @@ -124,8 +130,6 @@ class ConsentProviderDelegate : public ConsentProvider::DelegateInterface { bool HasRequestDownloadsPermission(const Extension& extension) override; Profile* const profile_; - - DISALLOW_COPY_AND_ASSIGN(ConsentProviderDelegate); }; } // namespace file_system_api diff --git a/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc b/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc index 13071acef84..d31c5dd8df9 100644 --- a/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc +++ b/chromium/chrome/browser/extensions/api/file_system/consent_provider_unittest.cc @@ -44,6 +44,11 @@ class TestingConsentProviderDelegate dialog_button_(ui::DIALOG_BUTTON_NONE), is_auto_launched_(false) {} + TestingConsentProviderDelegate(const TestingConsentProviderDelegate&) = + delete; + TestingConsentProviderDelegate& operator=( + const TestingConsentProviderDelegate&) = delete; + ~TestingConsentProviderDelegate() {} // Sets a fake dialog response. @@ -97,8 +102,6 @@ class TestingConsentProviderDelegate ui::DialogButton dialog_button_; bool is_auto_launched_; std::string allowlisted_component_id_; - - DISALLOW_COPY_AND_ASSIGN(TestingConsentProviderDelegate); }; // Rewrites result of a consent request from |result| to |log|. diff --git a/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.h b/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.h index 53a7dbf635d..57bd1f730da 100644 --- a/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.h +++ b/chromium/chrome/browser/extensions/api/file_system/file_entry_picker.h @@ -38,6 +38,9 @@ class FileEntryPicker : public ui::SelectFileDialog::Listener { FileSystemDelegate::FilesSelectedCallback files_selected_callback, base::OnceClosure file_selection_canceled_callback); + FileEntryPicker(const FileEntryPicker&) = delete; + FileEntryPicker& operator=(const FileEntryPicker&) = delete; + private: ~FileEntryPicker() override; // FileEntryPicker deletes itself. @@ -58,8 +61,6 @@ class FileEntryPicker : public ui::SelectFileDialog::Listener { FileSystemDelegate::FilesSelectedCallback files_selected_callback_; base::OnceClosure file_selection_canceled_callback_; scoped_refptr<ui::SelectFileDialog> select_file_dialog_; - - DISALLOW_COPY_AND_ASSIGN(FileEntryPicker); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc index ad8898b37cd..a7ee388b81b 100644 --- a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc +++ b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest.cc @@ -41,6 +41,9 @@ class AppLoadObserver : public ExtensionRegistryObserver { ExtensionRegistry::Get(browser_context)); } + AppLoadObserver(const AppLoadObserver&) = delete; + AppLoadObserver& operator=(const AppLoadObserver&) = delete; + void OnExtensionLoaded(content::BrowserContext* browser_context, const Extension* extension) override { callback_.Run(extension); @@ -50,7 +53,6 @@ class AppLoadObserver : public ExtensionRegistryObserver { base::RepeatingCallback<void(const Extension*)> callback_; base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; - DISALLOW_COPY_AND_ASSIGN(AppLoadObserver); }; void SetLastChooseEntryDirectory(const base::FilePath& choose_entry_directory, diff --git a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc index 88f4353ba63..f18a78e281b 100644 --- a/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/file_system/file_system_apitest_chromeos.cc @@ -61,13 +61,16 @@ class ScopedSkipRequestFileSystemDialog { file_system_api::ConsentProviderDelegate::SetAutoDialogButtonForTest( button); } + + ScopedSkipRequestFileSystemDialog(const ScopedSkipRequestFileSystemDialog&) = + delete; + ScopedSkipRequestFileSystemDialog& operator=( + const ScopedSkipRequestFileSystemDialog&) = delete; + ~ScopedSkipRequestFileSystemDialog() { file_system_api::ConsentProviderDelegate::SetAutoDialogButtonForTest( ui::DIALOG_BUTTON_NONE); } - - private: - DISALLOW_COPY_AND_ASSIGN(ScopedSkipRequestFileSystemDialog); }; // Observers adding a listener to the |event_name| event by |extension|, and @@ -85,6 +88,10 @@ class ScopedAddListenerObserver : public EventRouter::Observer { event_router_->RegisterObserver(this, event_name); } + ScopedAddListenerObserver(const ScopedAddListenerObserver&) = delete; + ScopedAddListenerObserver& operator=(const ScopedAddListenerObserver&) = + delete; + ~ScopedAddListenerObserver() override { event_router_->UnregisterObserver(this); } @@ -103,8 +110,6 @@ class ScopedAddListenerObserver : public EventRouter::Observer { const std::string extension_id_; base::OnceClosure callback_; EventRouter* const event_router_; - - DISALLOW_COPY_AND_ASSIGN(ScopedAddListenerObserver); }; // This class contains chrome.filesystem API test specific to Chrome OS, namely, diff --git a/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc b/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc index 6772b7bde97..2d2164eb7f8 100644 --- a/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc +++ b/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc @@ -40,6 +40,9 @@ class AppNotificationLauncher : public AppIconLoaderDelegate { // This class owns and deletes itself after showing the notification. AppNotificationLauncher() = default; + AppNotificationLauncher(const AppNotificationLauncher&) = delete; + AppNotificationLauncher& operator=(const AppNotificationLauncher&) = delete; + void InitAndShow(Profile* profile, const Extension& extension, std::unique_ptr<message_center::Notification> notification) { @@ -72,8 +75,6 @@ class AppNotificationLauncher : public AppIconLoaderDelegate { std::unique_ptr<AppIconLoader> icon_loader_; gfx::Image extension_icon_; std::unique_ptr<message_center::Notification> pending_notification_; - - DISALLOW_COPY_AND_ASSIGN(AppNotificationLauncher); }; } // namespace diff --git a/chromium/chrome/browser/extensions/api/font_settings/OWNERS b/chromium/chrome/browser/extensions/api/font_settings/OWNERS deleted file mode 100644 index 4794cccee13..00000000000 --- a/chromium/chrome/browser/extensions/api/font_settings/OWNERS +++ /dev/null @@ -1 +0,0 @@ -falken@chromium.org diff --git a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc index d7262fd203b..afba0241c40 100644 --- a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc +++ b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.cc @@ -212,7 +212,7 @@ ExtensionFunction::ResponseAction FontSettingsClearFontFunction::Run() { return RespondNow(Error(kSetFromIncognitoError)); std::unique_ptr<fonts::ClearFont::Params> params( - fonts::ClearFont::Params::Create(*args_)); + fonts::ClearFont::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string pref_path = GetFontNamePrefPath(params->details.generic_family, @@ -228,7 +228,7 @@ ExtensionFunction::ResponseAction FontSettingsClearFontFunction::Run() { ExtensionFunction::ResponseAction FontSettingsGetFontFunction::Run() { std::unique_ptr<fonts::GetFont::Params> params( - fonts::GetFont::Params::Create(*args_)); + fonts::GetFont::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string pref_path = GetFontNamePrefPath(params->details.generic_family, @@ -267,7 +267,7 @@ ExtensionFunction::ResponseAction FontSettingsSetFontFunction::Run() { return RespondNow(Error(kSetFromIncognitoError)); std::unique_ptr<fonts::SetFont::Params> params( - fonts::SetFont::Params::Create(*args_)); + fonts::SetFont::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string pref_path = GetFontNamePrefPath(params->details.generic_family, @@ -298,23 +298,23 @@ ExtensionFunction::ResponseValue FontSettingsGetFontListFunction::CopyFontsToResult(base::ListValue* fonts) { std::unique_ptr<base::ListValue> result(new base::ListValue()); for (const auto& entry : fonts->GetList()) { - const base::ListValue* font_list_value; - if (!entry.GetAsList(&font_list_value)) { + if (!entry.is_list()) { NOTREACHED(); return Error(""); } + const base::Value::ConstListView font_list_value = entry.GetList(); - std::string name; - if (!font_list_value->GetString(0, &name)) { + if (font_list_value.size() < 2 || !font_list_value[0].is_string()) { NOTREACHED(); return Error(""); } + const std::string& name = font_list_value[0].GetString(); - std::string localized_name; - if (!font_list_value->GetString(1, &localized_name)) { + if (!font_list_value[1].is_string()) { NOTREACHED(); return Error(""); } + const std::string& localized_name = font_list_value[1].GetString(); std::unique_ptr<base::DictionaryValue> font_name( new base::DictionaryValue()); @@ -364,11 +364,11 @@ ExtensionFunction::ResponseAction SetFontPrefExtensionFunction::Run() { if (profile->IsOffTheRecord()) return RespondNow(Error(kSetFromIncognitoError)); - base::DictionaryValue* details = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &details)); - - base::Value* value; - EXTENSION_FUNCTION_VALIDATE(details->Get(GetKey(), &value)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 1); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_dict()); + const base::Value& details = args()[0]; + const base::Value* value = details.FindKey(GetKey()); + EXTENSION_FUNCTION_VALIDATE(value); PreferenceAPI::Get(profile)->SetExtensionControlledPref( extension_id(), GetPrefName(), kExtensionPrefsScopeRegular, diff --git a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h index c4d9224a14b..58d591405d9 100644 --- a/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h +++ b/chromium/chrome/browser/extensions/api/font_settings/font_settings_api.h @@ -36,6 +36,10 @@ class FontSettingsEventRouter { // pointer to |profile| but does not take ownership. |profile| must be // non-NULL and remain alive for the lifetime of the instance. explicit FontSettingsEventRouter(Profile* profile); + + FontSettingsEventRouter(const FontSettingsEventRouter&) = delete; + FontSettingsEventRouter& operator=(const FontSettingsEventRouter&) = delete; + virtual ~FontSettingsEventRouter(); private: @@ -73,8 +77,6 @@ class FontSettingsEventRouter { // Weak, owns us (transitively via ExtensionService). Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(FontSettingsEventRouter); }; // The profile-keyed service that manages the font_settings extension API. diff --git a/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc b/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc index 59220802e14..fd3d6536b9d 100644 --- a/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc +++ b/chromium/chrome/browser/extensions/api/force_installed_affiliated_extension_apitest.cc @@ -107,7 +107,7 @@ void ForceInstalledAffiliatedExtensionApiTest::TestExtension( SetCustomArg(custom_arg); extensions::ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser, GURL(page_url)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser, GURL(page_url))); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc b/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc index 52ad4d2d496..029031adb13 100644 --- a/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc +++ b/chromium/chrome/browser/extensions/api/gcm/gcm_api.cc @@ -110,7 +110,7 @@ GcmRegisterFunction::~GcmRegisterFunction() {} ExtensionFunction::ResponseAction GcmRegisterFunction::Run() { std::unique_ptr<api::gcm::Register::Params> params( - api::gcm::Register::Params::Create(*args_)); + api::gcm::Register::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); GetGCMDriver()->Register( @@ -125,7 +125,7 @@ void GcmRegisterFunction::CompleteFunctionWithResult( const std::string& registration_id, gcm::GCMClient::Result gcm_result) { auto result = std::make_unique<base::ListValue>(); - result->AppendString(registration_id); + result->Append(registration_id); const bool succeeded = gcm::GCMClient::SUCCESS == gcm_result; Respond(succeeded @@ -160,7 +160,7 @@ GcmSendFunction::~GcmSendFunction() {} ExtensionFunction::ResponseAction GcmSendFunction::Run() { std::unique_ptr<api::gcm::Send::Params> params( - api::gcm::Send::Params::Create(*args_)); + api::gcm::Send::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); EXTENSION_FUNCTION_VALIDATE( ValidateMessageData(params->message.data.additional_properties)); @@ -183,7 +183,7 @@ void GcmSendFunction::CompleteFunctionWithResult( const std::string& message_id, gcm::GCMClient::Result gcm_result) { auto result = std::make_unique<base::ListValue>(); - result->AppendString(message_id); + result->Append(message_id); const bool succeeded = gcm::GCMClient::SUCCESS == gcm_result; Respond(succeeded diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc index ad5389c9bb8..736fc0a2752 100644 --- a/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc +++ b/chromium/chrome/browser/extensions/api/gcm/gcm_apitest.cc @@ -117,8 +117,8 @@ const Extension* GcmApiTest::LoadTestExtension( const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(extension_path)); if (extension) { - ui_test_utils::NavigateToURL( - browser(), extension->GetResourceURL(page_name)); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), extension->GetResourceURL(page_name))); } return extension; } diff --git a/chromium/chrome/browser/extensions/api/history/history_api.cc b/chromium/chrome/browser/extensions/api/history/history_api.cc index 9fba6eecaee..e74ff98a1fa 100644 --- a/chromium/chrome/browser/extensions/api/history/history_api.cc +++ b/chromium/chrome/browser/extensions/api/history/history_api.cc @@ -258,7 +258,7 @@ HistoryFunctionWithCallback::HistoryFunctionWithCallback() {} HistoryFunctionWithCallback::~HistoryFunctionWithCallback() {} ExtensionFunction::ResponseAction HistoryGetVisitsFunction::Run() { - std::unique_ptr<GetVisits::Params> params(GetVisits::Params::Create(*args_)); + std::unique_ptr<GetVisits::Params> params(GetVisits::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); GURL url; @@ -289,7 +289,7 @@ void HistoryGetVisitsFunction::QueryComplete(history::QueryURLResult result) { } ExtensionFunction::ResponseAction HistorySearchFunction::Run() { - std::unique_ptr<Search::Params> params(Search::Params::Create(*args_)); + std::unique_ptr<Search::Params> params(Search::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::u16string search_text = base::UTF8ToUTF16(params->query.text); @@ -327,7 +327,7 @@ void HistorySearchFunction::SearchComplete(history::QueryResults results) { } ExtensionFunction::ResponseAction HistoryAddUrlFunction::Run() { - std::unique_ptr<AddUrl::Params> params(AddUrl::Params::Create(*args_)); + std::unique_ptr<AddUrl::Params> params(AddUrl::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); GURL url; @@ -343,7 +343,7 @@ ExtensionFunction::ResponseAction HistoryAddUrlFunction::Run() { } ExtensionFunction::ResponseAction HistoryDeleteUrlFunction::Run() { - std::unique_ptr<DeleteUrl::Params> params(DeleteUrl::Params::Create(*args_)); + std::unique_ptr<DeleteUrl::Params> params(DeleteUrl::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; @@ -375,7 +375,7 @@ ExtensionFunction::ResponseAction HistoryDeleteUrlFunction::Run() { ExtensionFunction::ResponseAction HistoryDeleteRangeFunction::Run() { std::unique_ptr<DeleteRange::Params> params( - DeleteRange::Params::Create(*args_)); + DeleteRange::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; diff --git a/chromium/chrome/browser/extensions/api/history/history_api.h b/chromium/chrome/browser/extensions/api/history/history_api.h index 93a3ace9e60..fdfb1f45392 100644 --- a/chromium/chrome/browser/extensions/api/history/history_api.h +++ b/chromium/chrome/browser/extensions/api/history/history_api.h @@ -30,6 +30,10 @@ class HistoryEventRouter : public history::HistoryServiceObserver { public: HistoryEventRouter(Profile* profile, history::HistoryService* history_service); + + HistoryEventRouter(const HistoryEventRouter&) = delete; + HistoryEventRouter& operator=(const HistoryEventRouter&) = delete; + ~HistoryEventRouter() override; private: @@ -51,8 +55,6 @@ class HistoryEventRouter : public history::HistoryServiceObserver { base::ScopedObservation<history::HistoryService, history::HistoryServiceObserver> history_service_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(HistoryEventRouter); }; class HistoryAPI : public BrowserContextKeyedAPI, public EventRouter::Observer { diff --git a/chromium/chrome/browser/extensions/api/history/history_apitest.cc b/chromium/chrome/browser/extensions/api/history/history_apitest.cc index 03fefdef0ec..a793779d1a6 100644 --- a/chromium/chrome/browser/extensions/api/history/history_apitest.cc +++ b/chromium/chrome/browser/extensions/api/history/history_apitest.cc @@ -132,7 +132,7 @@ IN_PROC_BROWSER_TEST_F(HistoryApiTest, Incognito) { embedded_test_server()->GetURL("www.b.com", "/simple.html"); content::TestNavigationObserver incognito_observer( incognito_browser->tab_strip_model()->GetActiveWebContents()); - ui_test_utils::NavigateToURL(incognito_browser, b_com); + ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, b_com)); EXPECT_TRUE(incognito_observer.last_navigation_succeeded()); // Check history in regular mode is not modified by incognito navigation. @@ -147,7 +147,7 @@ IN_PROC_BROWSER_TEST_F(HistoryApiTest, Incognito) { // Perform navigation in regular mode. content::TestNavigationObserver regular_observer( browser()->tab_strip_model()->GetActiveWebContents()); - ui_test_utils::NavigateToURL(browser(), b_com); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), b_com)); EXPECT_TRUE(regular_observer.last_navigation_succeeded()); // Check history in regular mode is modified by navigation. diff --git a/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc b/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc index fcb0a765565..084871dd48f 100644 --- a/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc +++ b/chromium/chrome/browser/extensions/api/i18n/i18n_apitest.cc @@ -43,9 +43,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, I18NUpdate) { ResultCatcher catcher; // Test that the messages.json file is loaded and the i18n message is loaded. - ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("/extensions/test_file.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/extensions/test_file.html"))); EXPECT_TRUE(catcher.GetNextResult()); std::u16string title; @@ -59,9 +58,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, I18NUpdate) { ReloadExtension(extension->id()); // Check that the i18n message is also changed. - ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("/extensions/test_file.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/extensions/test_file.html"))); EXPECT_TRUE(catcher.GetNextResult()); ui_test_utils::GetCurrentTabTitle(browser(), &title); diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc index f4ebc716a64..39ab02f1c6f 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc @@ -79,11 +79,12 @@ #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" +#include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "chrome/browser/ash/login/users/mock_user_manager.h" -#include "chrome/browser/chromeos/net/network_portal_detector_test_impl.h" +#include "chrome/browser/ash/net/network_portal_detector_test_impl.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state.h" #include "chromeos/network/network_state_handler.h" @@ -139,10 +140,10 @@ class AsyncFunctionRunner { content::BrowserContext* browser_context) { response_delegate_ = std::make_unique<api_test_utils::SendResponseHelper>(function); - std::unique_ptr<base::ListValue> parsed_args(utils::ParseList(args)); - ASSERT_TRUE(parsed_args.get()) + absl::optional<base::Value> parsed_args(utils::ParseList(args)); + ASSERT_TRUE(parsed_args) << "Could not parse extension function arguments: " << args; - function->SetArgs(base::Value::FromUniquePtrValue(std::move(parsed_args))); + function->SetArgs(std::move(*parsed_args)); if (!function->extension()) { scoped_refptr<const Extension> empty_extension( @@ -408,9 +409,8 @@ class FakeGetAuthTokenFunction : public IdentityGetAuthTokenFunction { error = GoogleServiceAuthError( GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS); } - OnGetAccessTokenComplete( - access_token, base::Time::Now() + base::TimeDelta::FromHours(1LL), - error); + OnGetAccessTokenComplete(access_token, + base::Time::Now() + base::Hours(1LL), error); } else { // Make a request to the IdentityManager. The test now must tell the // service to issue an access token (or an error). @@ -863,8 +863,7 @@ class GetAuthTokenFunctionTest std::string access_token = "access_token-" + account_id.ToString(); identity_test_env() ->WaitForAccessTokenRequestIfNecessaryAndRespondWithToken( - account_id, access_token, - base::Time::Now() + base::TimeDelta::FromSeconds(3600)); + account_id, access_token, base::Time::Now() + base::Seconds(3600)); return access_token; } @@ -1794,7 +1793,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, NonInteractiveCacheHit) { // Pre-populate the cache with a token. IdentityTokenCacheValue token = - CreateToken(kAccessToken, base::TimeDelta::FromSeconds(3600)); + CreateToken(kAccessToken, base::Seconds(3600)); SetCachedToken(token); // Get a token. Should not require a GAIA request. @@ -1834,7 +1833,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, // Pre-populate the cache with a token. IdentityTokenCacheValue token = - CreateToken(kAccessToken, base::TimeDelta::FromSeconds(3600)); + CreateToken(kAccessToken, base::Seconds(3600)); SetCachedTokenForAccount(account_info, token); if (id_api()->AreExtensionsRestrictedToPrimaryAccount()) { @@ -1935,7 +1934,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, InteractiveCacheHit) { // Populate the cache with a token while the request is blocked. IdentityTokenCacheValue token = - CreateToken(kAccessToken, base::TimeDelta::FromSeconds(3600)); + CreateToken(kAccessToken, base::Seconds(3600)); SetCachedToken(token); // When we wake up the request, it returns the cached token without @@ -1965,7 +1964,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, LoginInvalidatesTokenCache) { // Pre-populate the cache with a token. IdentityTokenCacheValue token = - CreateToken(kAccessToken, base::TimeDelta::FromSeconds(3600)); + CreateToken(kAccessToken, base::Seconds(3600)); SetCachedToken(token); // Because the user is not signed in, the token will be removed, @@ -2732,7 +2731,7 @@ IN_PROC_BROWSER_TEST_F(GetAuthTokenFunctionTest, SubsetMatchCacheHit) { std::set<std::string> scopes = {"email", "foo", "bar"}; IdentityTokenCacheValue token = IdentityTokenCacheValue::CreateToken( - kAccessToken, scopes, base::TimeDelta::FromSeconds(3600)); + kAccessToken, scopes, base::Seconds(3600)); SetCachedToken(token); std::string access_token; @@ -3227,7 +3226,7 @@ IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, RemoteConsent) { IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, NonMatchingToken) { IdentityTokenCacheValue token = - CreateToken("non_matching_token", base::TimeDelta::FromSeconds(3600)); + CreateToken("non_matching_token", base::Seconds(3600)); SetCachedToken(token); EXPECT_TRUE(InvalidateDefaultToken()); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, @@ -3237,7 +3236,7 @@ IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, NonMatchingToken) { IN_PROC_BROWSER_TEST_F(RemoveCachedAuthTokenFunctionTest, MatchingToken) { IdentityTokenCacheValue token = - CreateToken(kAccessToken, base::TimeDelta::FromSeconds(3600)); + CreateToken(kAccessToken, base::Seconds(3600)); SetCachedToken(token); EXPECT_EQ(IdentityTokenCacheValue::CACHE_STATUS_TOKEN, GetCachedToken().status()); @@ -3255,14 +3254,7 @@ class LaunchWebAuthFlowFunctionTest : public AsyncExtensionBrowserTest { } }; -#if defined(OS_LINUX) || defined(OS_CHROMEOS) -// This test times out on Linux MSan Tests. -// See https://crbug.com/831848 . -#define MAYBE_UserCloseWindow DISABLED_UserCloseWindow -#else -#define MAYBE_UserCloseWindow UserCloseWindow -#endif -IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, MAYBE_UserCloseWindow) { +IN_PROC_BROWSER_TEST_F(LaunchWebAuthFlowFunctionTest, UserCloseWindow) { net::EmbeddedTestServer https_server(net::EmbeddedTestServer::TYPE_HTTPS); https_server.ServeFilesFromSourceDirectory( "chrome/test/data/extensions/api_test/identity"); @@ -3433,9 +3425,8 @@ IN_PROC_BROWSER_TEST_F(ClearAllCachedAuthTokensFunctionTest, EraseCachedTokens) { ExtensionTokenKey token_key(extension()->id(), CoreAccountInfo(), {"foo"}); id_api()->token_cache()->SetToken( - token_key, - IdentityTokenCacheValue::CreateToken("access_token", {"foo"}, - base::TimeDelta::FromSeconds(3600))); + token_key, IdentityTokenCacheValue::CreateToken("access_token", {"foo"}, + base::Seconds(3600))); EXPECT_NE(IdentityTokenCacheValue::CACHE_STATUS_NOTFOUND, id_api()->token_cache()->GetToken(token_key).status()); ASSERT_TRUE(RunClearAllCachedAuthTokensFunction()); diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc index 9f9e9eb0704..18d62d4a495 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.cc @@ -113,7 +113,7 @@ ExtensionFunction::ResponseAction IdentityGetAuthTokenFunction::Run() { } std::unique_ptr<api::identity::GetAuthToken::Params> params( - api::identity::GetAuthToken::Params::Create(*args_)); + api::identity::GetAuthToken::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); interactive_ = params->details.get() && params->details->interactive.get() && *params->details->interactive; @@ -559,7 +559,7 @@ void IdentityGetAuthTokenFunction::OnMintTokenSuccess( TRACE_EVENT_NESTABLE_ASYNC_INSTANT0("identity", "OnMintTokenSuccess", this); IdentityTokenCacheValue token = IdentityTokenCacheValue::CreateToken( - access_token, granted_scopes, base::TimeDelta::FromSeconds(time_to_live)); + access_token, granted_scopes, base::Seconds(time_to_live)); IdentityAPI::GetFactoryInstance() ->Get(GetProfile()) ->token_cache() diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h index dc9259349ea..fd4958bfe33 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_auth_token_function.h @@ -10,6 +10,7 @@ #include <string> #include "base/callback_list.h" +#include "base/gtest_prod_util.h" #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "build/chromeos_buildflags.h" diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc index d0e4371465e..dbdaf890e53 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc @@ -49,7 +49,7 @@ ExtensionFunction::ResponseAction IdentityGetProfileUserInfoFunction::Run() { } std::unique_ptr<api::identity::GetProfileUserInfo::Params> params( - api::identity::GetProfileUserInfo::Params::Create(*args_)); + api::identity::GetProfileUserInfo::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); api::identity::ProfileUserInfo profile_user_info; diff --git a/chromium/chrome/browser/extensions/api/identity/identity_launch_web_auth_flow_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_launch_web_auth_flow_function.cc index f87afd6891c..be763a94df5 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_launch_web_auth_flow_function.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_launch_web_auth_flow_function.cc @@ -35,7 +35,7 @@ ExtensionFunction::ResponseAction IdentityLaunchWebAuthFlowFunction::Run() { } std::unique_ptr<api::identity::LaunchWebAuthFlow::Params> params( - api::identity::LaunchWebAuthFlow::Params::Create(*args_)); + api::identity::LaunchWebAuthFlow::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); GURL auth_url(params->details.url); diff --git a/chromium/chrome/browser/extensions/api/identity/identity_private_api.cc b/chromium/chrome/browser/extensions/api/identity/identity_private_api.cc index a0342d733df..d21ad116be3 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_private_api.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_private_api.cc @@ -15,7 +15,7 @@ IdentityPrivateSetConsentResultFunction:: ExtensionFunction::ResponseAction IdentityPrivateSetConsentResultFunction::Run() { - std::unique_ptr<Params> params = Params::Create(*args_); + std::unique_ptr<Params> params = Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params); IdentityAPI::GetFactoryInstance() diff --git a/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.cc index d8d80fb72cc..8518605654d 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.cc @@ -22,7 +22,7 @@ ExtensionFunction::ResponseAction IdentityRemoveCachedAuthTokenFunction::Run() { return RespondNow(Error(identity_constants::kOffTheRecord)); std::unique_ptr<api::identity::RemoveCachedAuthToken::Params> params( - api::identity::RemoveCachedAuthToken::Params::Create(*args_)); + api::identity::RemoveCachedAuthToken::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); IdentityAPI::GetFactoryInstance() ->Get(browser_context()) diff --git a/chromium/chrome/browser/extensions/api/identity/identity_token_cache.cc b/chromium/chrome/browser/extensions/api/identity/identity_token_cache.cc index e65d905b67c..1870aa43dab 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_token_cache.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_token_cache.cc @@ -27,8 +27,7 @@ IdentityTokenCacheValue IdentityTokenCacheValue::CreateRemoteConsent( cache_value.value_ = resolution_data; cache_value.expiration_time_ = base::Time::Now() + - base::TimeDelta::FromSeconds( - identity_constants::kCachedRemoteConsentTTLSeconds); + base::Seconds(identity_constants::kCachedRemoteConsentTTLSeconds); return cache_value; } @@ -39,8 +38,7 @@ IdentityTokenCacheValue IdentityTokenCacheValue::CreateRemoteConsentApproved( cache_value.value_ = consent_result; cache_value.expiration_time_ = base::Time::Now() + - base::TimeDelta::FromSeconds( - identity_constants::kCachedRemoteConsentTTLSeconds); + base::Seconds(identity_constants::kCachedRemoteConsentTTLSeconds); return cache_value; } @@ -56,7 +54,7 @@ IdentityTokenCacheValue IdentityTokenCacheValue::CreateToken( // Remove 20 minutes from the ttl so cached tokens will have some time // to live any time they are returned. - time_to_live -= base::TimeDelta::FromMinutes(20); + time_to_live -= base::Minutes(20); base::TimeDelta zero_delta; if (time_to_live < zero_delta) diff --git a/chromium/chrome/browser/extensions/api/identity/identity_token_cache_unittest.cc b/chromium/chrome/browser/extensions/api/identity/identity_token_cache_unittest.cc index a35343aa029..be4dcd8c275 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_token_cache_unittest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_token_cache_unittest.cc @@ -23,17 +23,15 @@ class IdentityTokenCacheTest : public testing::Test { void SetAccessToken(const std::string& ext_id, const std::string& token_string, const std::set<std::string>& scopes) { - SetAccessTokenInternal(ext_id, token_string, scopes, - base::TimeDelta::FromSeconds(3600)); + SetAccessTokenInternal(ext_id, token_string, scopes, base::Seconds(3600)); } void SetExpiredAccessToken(const std::string& ext_id, const std::string& token_string, const std::set<std::string>& scopes) { // Token must not be expired at the insertion moment. - SetAccessTokenInternal(ext_id, token_string, scopes, - base::TimeDelta::FromMilliseconds(1)); - task_environment_.FastForwardBy(base::TimeDelta::FromMilliseconds(2)); + SetAccessTokenInternal(ext_id, token_string, scopes, base::Milliseconds(1)); + task_environment_.FastForwardBy(base::Milliseconds(2)); } void SetRemoteConsentApprovedToken(const std::string& ext_id, diff --git a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc index 50dfb35d564..6a5dab8aa9d 100644 --- a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc +++ b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.cc @@ -106,13 +106,13 @@ void WebAuthFlow::Start() { // identityPrivate.onWebFlowRequest(app_window_key, provider_url_, mode_) std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->AppendString(app_window_key_); - args->AppendString(provider_url_.spec()); + args->Append(app_window_key_); + args->Append(provider_url_.spec()); if (mode_ == WebAuthFlow::INTERACTIVE) - args->AppendString("interactive"); + args->Append("interactive"); else - args->AppendString("silent"); - args->AppendString(GetPartitionName(partition_)); + args->Append("silent"); + args->Append(GetPartitionName(partition_)); auto event = std::make_unique<Event>(events::IDENTITY_PRIVATE_ON_WEB_FLOW_REQUEST, diff --git a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h index bef7a9b9e86..deb63605702 100644 --- a/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h +++ b/chromium/chrome/browser/extensions/api/identity/web_auth_flow.h @@ -82,6 +82,9 @@ class WebAuthFlow : public content::WebContentsObserver, Mode mode, Partition partition); + WebAuthFlow(const WebAuthFlow&) = delete; + WebAuthFlow& operator=(const WebAuthFlow&) = delete; + ~WebAuthFlow() override; // Starts the flow. @@ -135,8 +138,6 @@ class WebAuthFlow : public content::WebContentsObserver, AppWindow* app_window_; std::string app_window_key_; bool embedded_window_created_; - - DISALLOW_COPY_AND_ASSIGN(WebAuthFlow); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc b/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc index 2f69fccc443..b54ad539360 100644 --- a/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc +++ b/chromium/chrome/browser/extensions/api/idltest/idltest_api.cc @@ -27,15 +27,15 @@ base::Value CopyBinaryValueToIntegerList( } // namespace ExtensionFunction::ResponseAction IdltestSendArrayBufferFunction::Run() { - EXTENSION_FUNCTION_VALIDATE(args_ && !args_->GetList().empty()); - const auto& value = args_->GetList()[0]; + EXTENSION_FUNCTION_VALIDATE(has_args() && !args().empty()); + const auto& value = args()[0]; EXTENSION_FUNCTION_VALIDATE(value.is_blob()); return RespondNow(OneArgument(CopyBinaryValueToIntegerList(value.GetBlob()))); } ExtensionFunction::ResponseAction IdltestSendArrayBufferViewFunction::Run() { - EXTENSION_FUNCTION_VALIDATE(args_ && !args_->GetList().empty()); - const auto& value = args_->GetList()[0]; + EXTENSION_FUNCTION_VALIDATE(has_args() && !args().empty()); + const auto& value = args()[0]; EXTENSION_FUNCTION_VALIDATE(value.is_blob()); return RespondNow(OneArgument(CopyBinaryValueToIntegerList(value.GetBlob()))); } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc index 21429a95297..4c500d517a3 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.cc @@ -8,7 +8,6 @@ #include "base/bind.h" #include "base/task/post_task.h" -#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "chrome/browser/extensions/api/image_writer_private/operation_manager.h" #include "chrome/browser/profiles/profile.h" @@ -80,7 +79,7 @@ ImageWriterPrivateWriteFromUrlFunction::Run() { } #endif std::unique_ptr<image_writer_api::WriteFromUrl::Params> params( - image_writer_api::WriteFromUrl::Params::Create(*args_)); + image_writer_api::WriteFromUrl::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); GURL url(params->image_url); @@ -124,13 +123,14 @@ ImageWriterPrivateWriteFromFileFunction::Run() { return RespondNow(Error(image_writer::error::kDeviceWriteError)); } #endif - std::string filesystem_name; - std::string filesystem_path; - std::string storage_unit_id; + EXTENSION_FUNCTION_VALIDATE(args().size() >= 3); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); + EXTENSION_FUNCTION_VALIDATE(args()[1].is_string()); + EXTENSION_FUNCTION_VALIDATE(args()[2].is_string()); - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &storage_unit_id)); - EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filesystem_name)); - EXTENSION_FUNCTION_VALIDATE(args_->GetString(2, &filesystem_path)); + const std::string& storage_unit_id = args()[0].GetString(); + const std::string& filesystem_name = args()[1].GetString(); + const std::string& filesystem_path = args()[2].GetString(); base::FilePath path; @@ -197,7 +197,7 @@ ImageWriterPrivateDestroyPartitionsFunction::Run() { #endif std::unique_ptr<image_writer_api::DestroyPartitions::Params> params( - image_writer_api::DestroyPartitions::Params::Create(*args_)); + image_writer_api::DestroyPartitions::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); #if BUILDFLAG(IS_CHROMEOS_LACROS) diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h index a428ac3bafb..cfa345bc439 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_api.h @@ -4,6 +4,7 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_IMAGE_WRITER_PRIVATE_API_H_ #define CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_IMAGE_WRITER_PRIVATE_API_H_ +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h" #include "chrome/common/extensions/api/image_writer_private.h" #include "extensions/browser/extension_function.h" @@ -18,6 +19,11 @@ class ImageWriterPrivateBaseFunction : public ExtensionFunction { public: ImageWriterPrivateBaseFunction(); + ImageWriterPrivateBaseFunction(const ImageWriterPrivateBaseFunction&) = + delete; + ImageWriterPrivateBaseFunction& operator=( + const ImageWriterPrivateBaseFunction&) = delete; + #if BUILDFLAG(IS_CHROMEOS_LACROS) virtual void OnComplete(const absl::optional<std::string>& error); #else @@ -26,9 +32,6 @@ class ImageWriterPrivateBaseFunction : public ExtensionFunction { protected: ~ImageWriterPrivateBaseFunction() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ImageWriterPrivateBaseFunction); }; class ImageWriterPrivateWriteFromUrlFunction diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc index 5f17e5c7448..c13396aa5a9 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.cc @@ -10,8 +10,8 @@ #include "base/files/file_path.h" #include "base/location.h" #include "build/build_config.h" -#include "chrome/browser/service_sandbox_type.h" #include "chrome/grit/generated_resources.h" +#include "chrome/services/removable_storage_writer/public/mojom/removable_storage_writer.mojom.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/service_process_host.h" #include "mojo/public/cpp/bindings/receiver.h" @@ -46,6 +46,11 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl image_writer_utility_client_)); } + RemovableStorageWriterClientImpl(const RemovableStorageWriterClientImpl&) = + delete; + RemovableStorageWriterClientImpl& operator=( + const RemovableStorageWriterClientImpl&) = delete; + ~RemovableStorageWriterClientImpl() override = default; private: @@ -65,8 +70,6 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl // |image_writer_utility_client_| owns |this|. ImageWriterUtilityClient* const image_writer_utility_client_; - - DISALLOW_COPY_AND_ASSIGN(RemovableStorageWriterClientImpl); }; ImageWriterUtilityClient::ImageWriterUtilityClient( diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h index 731404ef5b6..4ff865c66da 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h @@ -33,6 +33,9 @@ class ImageWriterUtilityClient using ImageWriterUtilityClientFactory = base::RepeatingCallback<scoped_refptr<ImageWriterUtilityClient>()>; + ImageWriterUtilityClient(const ImageWriterUtilityClient&) = delete; + ImageWriterUtilityClient& operator=(const ImageWriterUtilityClient&) = delete; + static scoped_refptr<ImageWriterUtilityClient> Create( const scoped_refptr<base::SequencedTaskRunner>& task_runner); @@ -102,8 +105,6 @@ class ImageWriterUtilityClient removable_storage_writer_client_; SEQUENCE_CHECKER(sequence_checker_); - - DISALLOW_COPY_AND_ASSIGN(ImageWriterUtilityClient); }; } // namespace image_writer diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc index df2e6226da4..61ae80063ad 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_utility_client_browsertest.cc @@ -37,6 +37,10 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { EXPECT_TRUE(temp_dir_.CreateUniqueTempDir()); } + ImageWriterUtilityClientTest(const ImageWriterUtilityClientTest&) = delete; + ImageWriterUtilityClientTest& operator=(const ImageWriterUtilityClientTest&) = + delete; + void FillImageFileWithPattern(char pattern) { base::ScopedAllowBlockingForTesting allow_blocking; EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &image_)); @@ -250,8 +254,6 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { bool cancel_ = false; std::string error_; scoped_refptr<base::SequencedTaskRunner> task_runner_; - - DISALLOW_COPY_AND_ASSIGN(ImageWriterUtilityClientTest); }; IN_PROC_BROWSER_TEST_F(ImageWriterUtilityClientTest, WriteNoImage) { diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h index e97f90efdbd..3ce36b7e062 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h @@ -68,6 +68,9 @@ class Operation : public base::RefCountedThreadSafe<Operation> { const std::string& device_path, const base::FilePath& download_folder); + Operation(const Operation&) = delete; + Operation& operator=(const Operation&) = delete; + // Starts the operation. void Start(); @@ -245,8 +248,6 @@ class Operation : public base::RefCountedThreadSafe<Operation> { // Sequenced task runner where all I/O operation will be performed. // Most of the methods of this class run in this task runner. scoped_refptr<base::SequencedTaskRunner> task_runner_; - - DISALLOW_COPY_AND_ASSIGN(Operation); }; } // namespace image_writer diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc index 4fc6ae24152..6240c94afd8 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.cc @@ -329,8 +329,9 @@ base::FilePath OperationManager::GetAssociatedDownloadFolder() { #if BUILDFLAG(IS_CHROMEOS_ASH) Profile* profile = Profile::FromBrowserContext(browser_context_); return file_manager::util::GetDownloadsFolderForProfile(profile); -#endif +#else return base::FilePath(); +#endif } Operation* OperationManager::GetOperation(const ExtensionId& extension_id) { diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h index 7265d5b2506..3a0aad41ec6 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager.h @@ -44,6 +44,10 @@ class OperationManager : public BrowserContextKeyedAPI, public base::SupportsWeakPtr<OperationManager> { public: explicit OperationManager(content::BrowserContext* context); + + OperationManager(const OperationManager&) = delete; + OperationManager& operator=(const OperationManager&) = delete; + ~OperationManager() override; void Shutdown() override; @@ -124,8 +128,6 @@ class OperationManager : public BrowserContextKeyedAPI, process_manager_observation_{this}; base::WeakPtrFactory<OperationManager> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(OperationManager); }; } // namespace image_writer diff --git a/chromium/chrome/browser/extensions/api/input_ime/OWNERS b/chromium/chrome/browser/extensions/api/input_ime/OWNERS index 764e0d62d01..9924ace56d5 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/OWNERS +++ b/chromium/chrome/browser/extensions/api/input_ime/OWNERS @@ -1,2 +1,3 @@ # primary reviewer keithlee@chromium.org +shend@chromium.org diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc index c5b1e08b4ac..2e0042668ba 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.cc @@ -11,8 +11,8 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/common/extensions/api/input_method_private.h" #include "extensions/browser/extension_registry.h" -#include "ui/base/ime/chromeos/ime_bridge.h" -#include "ui/base/ime/chromeos/ime_keymap.h" +#include "ui/base/ime/ash/ime_bridge.h" +#include "ui/base/ime/ash/ime_keymap.h" #include "ui/base/ime/constants.h" #include "ui/events/base_event_utils.h" #include "ui/events/keycodes/dom/dom_code.h" @@ -436,7 +436,7 @@ void InputImeEventRouterFactory::RemoveProfile(Profile* profile) { ExtensionFunction::ResponseAction InputImeKeyEventHandledFunction::Run() { std::unique_ptr<KeyEventHandled::Params> params( - KeyEventHandled::Params::Create(*args_)); + KeyEventHandled::Params::Create(args())); std::string error; InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id(), &error); @@ -455,7 +455,7 @@ ExtensionFunction::ResponseAction InputImeSetCompositionFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); std::unique_ptr<SetComposition::Params> parent_params( - SetComposition::Params::Create(*args_)); + SetComposition::Params::Create(args())); const SetComposition::Params::Parameters& params = parent_params->parameters; std::vector<InputMethodEngineBase::SegmentInfo> segments; if (params.segments) { @@ -501,7 +501,7 @@ ExtensionFunction::ResponseAction InputImeCommitTextFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); std::unique_ptr<CommitText::Params> parent_params( - CommitText::Params::Create(*args_)); + CommitText::Params::Create(args())); const CommitText::Params::Parameters& params = parent_params->parameters; if (!engine->CommitText(params.context_id, base::UTF8ToUTF16(params.text), &error)) { @@ -522,7 +522,7 @@ ExtensionFunction::ResponseAction InputImeSendKeyEventsFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); std::unique_ptr<SendKeyEvents::Params> parent_params( - SendKeyEvents::Params::Create(*args_)); + SendKeyEvents::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(parent_params); const SendKeyEvents::Params::Parameters& params = parent_params->parameters; @@ -548,6 +548,7 @@ InputImeAPI::InputImeAPI(content::BrowserContext* context) event_router->RegisterObserver(this, input_ime::OnFocus::kEventName); event_router->RegisterObserver( this, api::input_method_private::OnFocus::kEventName); + event_router->RegisterObserver(this, input_ime::OnKeyEvent::kEventName); } InputImeAPI::~InputImeAPI() = default; diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h index a3ec7fe65ca..a469329ec41 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api.h @@ -26,8 +26,8 @@ #include "extensions/browser/extension_registry_factory.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/extension.h" -#include "ui/base/ime/chromeos/ime_bridge_observer.h" -#include "ui/base/ime/chromeos/ime_engine_handler_interface.h" +#include "ui/base/ime/ash/ime_bridge_observer.h" +#include "ui/base/ime/ash/ime_engine_handler_interface.h" #include "ui/base/ime/text_input_flags.h" #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -43,6 +43,9 @@ class ImeObserver : public ash::input_method::InputMethodEngineBase::Observer { public: ImeObserver(const std::string& extension_id, Profile* profile); + ImeObserver(const ImeObserver&) = delete; + ImeObserver& operator=(const ImeObserver&) = delete; + ~ImeObserver() override = default; // InputMethodEngineBase::Observer overrides. @@ -104,8 +107,6 @@ class ImeObserver : public ash::input_method::InputMethodEngineBase::Observer { extensions::api::input_ime::AutoCapitalizeType ConvertInputContextAutoCapitalize( IMEEngineHandlerInterface::InputContext input_context); - - DISALLOW_COPY_AND_ASSIGN(ImeObserver); }; } // namespace ui @@ -116,6 +117,10 @@ class ExtensionRegistry; class InputImeEventRouterFactory { public: + InputImeEventRouterFactory(const InputImeEventRouterFactory&) = delete; + InputImeEventRouterFactory& operator=(const InputImeEventRouterFactory&) = + delete; + static InputImeEventRouterFactory* GetInstance(); InputImeEventRouter* GetRouter(Profile* profile); void RemoveProfile(Profile* profile); @@ -126,8 +131,6 @@ class InputImeEventRouterFactory { ~InputImeEventRouterFactory(); std::map<Profile*, InputImeEventRouter*, ProfileCompare> router_map_; - - DISALLOW_COPY_AND_ASSIGN(InputImeEventRouterFactory); }; class InputImeKeyEventHandledFunction : public ExtensionFunction { @@ -197,6 +200,7 @@ class InputImeAPI : public BrowserContextKeyedAPI, // EventRouter::Observer implementation. void OnListenerAdded(const EventListenerInfo& details) override; + void OnListenerRemoved(const EventListenerInfo& details) override; private: friend class BrowserContextKeyedAPIFactory<InputImeAPI>; diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc index 2ecc9f7607c..7a58f9be691 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.cc @@ -27,10 +27,10 @@ #include "extensions/browser/extension_registry.h" #include "extensions/browser/process_manager.h" #include "extensions/common/manifest_handlers/background_info.h" -#include "ui/base/ime/chromeos/component_extension_ime_manager.h" -#include "ui/base/ime/chromeos/extension_ime_util.h" -#include "ui/base/ime/chromeos/ime_engine_handler_interface.h" -#include "ui/base/ime/chromeos/input_method_manager.h" +#include "ui/base/ime/ash/component_extension_ime_manager.h" +#include "ui/base/ime/ash/extension_ime_util.h" +#include "ui/base/ime/ash/ime_engine_handler_interface.h" +#include "ui/base/ime/ash/input_method_manager.h" #include "ui/base/ui_base_features.h" namespace { @@ -72,9 +72,8 @@ const char kErrorUpdateMenuItemsFail[] = "Could not update menu items."; const char kErrorEngineNotActive[] = "The engine is not active."; const char kErrorRouterNotAvailable[] = "The router is not available."; -void SetMenuItemToMenu( - const input_ime::MenuItem& input, - chromeos::input_method::InputMethodManager::MenuItem* out) { +void SetMenuItemToMenu(const input_ime::MenuItem& input, + ash::input_method::InputMethodManager::MenuItem* out) { out->modified = 0; out->id = input.id; if (input.label) { @@ -85,7 +84,7 @@ void SetMenuItemToMenu( if (input.style != input_ime::MENU_ITEM_STYLE_NONE) { out->modified |= InputMethodEngine::MENU_ITEM_MODIFIED_STYLE; out->style = - static_cast<chromeos::input_method::InputMethodManager::MenuItemStyle>( + static_cast<ash::input_method::InputMethodManager::MenuItemStyle>( input.style); } @@ -158,9 +157,12 @@ class ImeObserverChromeOS : public ui::ImeObserver { ImeObserverChromeOS(const std::string& extension_id, Profile* profile) : ImeObserver(extension_id, profile) {} + ImeObserverChromeOS(const ImeObserverChromeOS&) = delete; + ImeObserverChromeOS& operator=(const ImeObserverChromeOS&) = delete; + ~ImeObserverChromeOS() override = default; - // chromeos::InputMethodEngineBase::Observer overrides. + // ash::InputMethodEngineBase::Observer overrides. void OnCandidateClicked( const std::string& component_id, int candidate_id, @@ -376,16 +378,16 @@ class ImeObserverChromeOS : public ui::ImeObserver { // lock screen, login screen, etc.) so that its on-screen keyboard page // won't open new windows/pages. See crbug.com/395621. std::string GetCurrentScreenType() override { - switch (chromeos::input_method::InputMethodManager::Get() + switch (ash::input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetUIStyle()) { - case chromeos::input_method::InputMethodManager::UIStyle::kLogin: + case ash::input_method::InputMethodManager::UIStyle::kLogin: return "login"; - case chromeos::input_method::InputMethodManager::UIStyle::kSecondaryLogin: + case ash::input_method::InputMethodManager::UIStyle::kSecondaryLogin: return "secondary-login"; - case chromeos::input_method::InputMethodManager::UIStyle::kLock: + case ash::input_method::InputMethodManager::UIStyle::kLock: return "lock"; - case chromeos::input_method::InputMethodManager::UIStyle::kNormal: + case ash::input_method::InputMethodManager::UIStyle::kNormal: return "normal"; } } @@ -489,8 +491,6 @@ class ImeObserverChromeOS : public ui::ImeObserver { } return input_mode_type; } - - DISALLOW_COPY_AND_ASSIGN(ImeObserverChromeOS); }; } // namespace @@ -534,12 +534,11 @@ bool InputImeEventRouter::RegisterImeExtension( if (engine_map_[extension_id]) return false; - chromeos::input_method::InputMethodManager* manager = - chromeos::input_method::InputMethodManager::Get(); - chromeos::ComponentExtensionIMEManager* comp_ext_ime_manager = + auto* manager = ash::input_method::InputMethodManager::Get(); + ash::ComponentExtensionIMEManager* comp_ext_ime_manager = manager->GetComponentExtensionIMEManager(); - chromeos::input_method::InputMethodDescriptors descriptors; + ash::input_method::InputMethodDescriptors descriptors; // Only creates descriptors for 3rd party IME extension, because the // descriptors for component IME extensions are managed by InputMethodUtil. if (!comp_ext_ime_manager->IsAllowlistedExtension(extension_id)) { @@ -559,9 +558,8 @@ bool InputImeEventRouter::RegisterImeExtension( languages.assign(component.languages.begin(), component.languages.end()); const std::string& input_method_id = - chromeos::extension_ime_util::GetInputMethodID(extension_id, - component.id); - descriptors.push_back(chromeos::input_method::InputMethodDescriptor( + ash::extension_ime_util::GetInputMethodID(extension_id, component.id); + descriptors.push_back(ash::input_method::InputMethodDescriptor( input_method_id, component.name, std::string(), // TODO(uekawa): Set short name. layout, languages, @@ -576,12 +574,11 @@ bool InputImeEventRouter::RegisterImeExtension( bool is_login = false; // When Chrome starts with the Login screen, sometimes active IME State was // not set yet. It's asynchronous process. So we need a fallback for that. - scoped_refptr<chromeos::input_method::InputMethodManager::State> - active_state = chromeos::input_method::InputMethodManager::Get() - ->GetActiveIMEState(); + scoped_refptr<ash::input_method::InputMethodManager::State> active_state = + ash::input_method::InputMethodManager::Get()->GetActiveIMEState(); if (active_state) { is_login = active_state->GetUIStyle() == - chromeos::input_method::InputMethodManager::UIStyle::kLogin; + ash::input_method::InputMethodManager::UIStyle::kLogin; } else { is_login = chromeos::ProfileHelper::IsSigninProfile(profile); } @@ -609,7 +606,7 @@ bool InputImeEventRouter::RegisterImeExtension( void InputImeEventRouter::UnregisterAllImes(const std::string& extension_id) { auto it = engine_map_.find(extension_id); if (it != engine_map_.end()) { - chromeos::input_method::InputMethodManager::Get() + ash::input_method::InputMethodManager::Get() ->GetActiveIMEState() ->RemoveInputMethodExtension(extension_id); engine_map_.erase(it); @@ -653,7 +650,7 @@ ExtensionFunction::ResponseAction InputImeClearCompositionFunction::Run() { } std::unique_ptr<ClearComposition::Params> parent_params( - ClearComposition::Params::Create(*args_)); + ClearComposition::Params::Create(args())); const ClearComposition::Params::Parameters& params = parent_params->parameters; @@ -687,7 +684,7 @@ InputImeSetAssistiveWindowPropertiesFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); } std::unique_ptr<SetAssistiveWindowProperties::Params> parent_params( - SetAssistiveWindowProperties::Params::Create(*args_)); + SetAssistiveWindowProperties::Params::Create(args())); const SetAssistiveWindowProperties::Params::Parameters& params = parent_params->parameters; const input_ime::AssistiveWindowProperties& window = params.properties; @@ -715,7 +712,7 @@ InputImeSetAssistiveWindowButtonHighlightedFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); } std::unique_ptr<SetAssistiveWindowButtonHighlighted::Params> parent_params( - SetAssistiveWindowButtonHighlighted::Params::Create(*args_)); + SetAssistiveWindowButtonHighlighted::Params::Create(args())); const SetAssistiveWindowButtonHighlighted::Params::Parameters& params = parent_params->parameters; ui::ime::AssistiveWindowButton button; @@ -736,7 +733,7 @@ InputImeSetAssistiveWindowButtonHighlightedFunction::Run() { ExtensionFunction::ResponseAction InputImeSetCandidateWindowPropertiesFunction::Run() { std::unique_ptr<SetCandidateWindowProperties::Params> parent_params( - SetCandidateWindowProperties::Params::Create(*args_)); + SetCandidateWindowProperties::Params::Create(args())); const SetCandidateWindowProperties::Params::Parameters& params = parent_params->parameters; @@ -824,7 +821,7 @@ ExtensionFunction::ResponseAction InputImeSetCandidatesFunction::Run() { } std::unique_ptr<SetCandidates::Params> parent_params( - SetCandidates::Params::Create(*args_)); + SetCandidates::Params::Create(args())); const SetCandidates::Params::Parameters& params = parent_params->parameters; @@ -864,7 +861,7 @@ ExtensionFunction::ResponseAction InputImeSetCursorPositionFunction::Run() { } std::unique_ptr<SetCursorPosition::Params> parent_params( - SetCursorPosition::Params::Create(*args_)); + SetCursorPosition::Params::Create(args())); const SetCursorPosition::Params::Parameters& params = parent_params->parameters; @@ -882,7 +879,7 @@ ExtensionFunction::ResponseAction InputImeSetCursorPositionFunction::Run() { ExtensionFunction::ResponseAction InputImeSetMenuItemsFunction::Run() { std::unique_ptr<SetMenuItems::Params> parent_params( - SetMenuItems::Params::Create(*args_)); + SetMenuItems::Params::Create(args())); const input_ime::MenuParameters& params = parent_params->parameters; std::string error; @@ -892,7 +889,7 @@ ExtensionFunction::ResponseAction InputImeSetMenuItemsFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); } - std::vector<chromeos::input_method::InputMethodManager::MenuItem> items_out; + std::vector<ash::input_method::InputMethodManager::MenuItem> items_out; for (const input_ime::MenuItem& item_in : params.items) { items_out.emplace_back(); SetMenuItemToMenu(item_in, &items_out.back()); @@ -908,7 +905,7 @@ ExtensionFunction::ResponseAction InputImeSetMenuItemsFunction::Run() { ExtensionFunction::ResponseAction InputImeUpdateMenuItemsFunction::Run() { std::unique_ptr<UpdateMenuItems::Params> parent_params( - UpdateMenuItems::Params::Create(*args_)); + UpdateMenuItems::Params::Create(args())); const input_ime::MenuParameters& params = parent_params->parameters; std::string error; @@ -918,7 +915,7 @@ ExtensionFunction::ResponseAction InputImeUpdateMenuItemsFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); } - std::vector<chromeos::input_method::InputMethodManager::MenuItem> items_out; + std::vector<ash::input_method::InputMethodManager::MenuItem> items_out; for (const input_ime::MenuItem& item_in : params.items) { items_out.emplace_back(); SetMenuItemToMenu(item_in, &items_out.back()); @@ -934,7 +931,7 @@ ExtensionFunction::ResponseAction InputImeUpdateMenuItemsFunction::Run() { ExtensionFunction::ResponseAction InputImeDeleteSurroundingTextFunction::Run() { std::unique_ptr<DeleteSurroundingText::Params> parent_params( - DeleteSurroundingText::Params::Create(*args_)); + DeleteSurroundingText::Params::Create(args())); const DeleteSurroundingText::Params::Parameters& params = parent_params->parameters; @@ -960,7 +957,7 @@ InputMethodPrivateFinishComposingTextFunction::Run() { if (!engine) return RespondNow(Error(InformativeError(error, static_function_name()))); std::unique_ptr<FinishComposingText::Params> parent_params( - FinishComposingText::Params::Create(*args_)); + FinishComposingText::Params::Create(args())); const FinishComposingText::Params::Parameters& params = parent_params->parameters; engine->FinishComposingText(params.context_id, &error); @@ -971,12 +968,12 @@ InputMethodPrivateFinishComposingTextFunction::Run() { ExtensionFunction::ResponseAction InputMethodPrivateNotifyImeMenuItemActivatedFunction::Run() { - chromeos::input_method::InputMethodDescriptor current_input_method = - chromeos::input_method::InputMethodManager::Get() + ash::input_method::InputMethodDescriptor current_input_method = + ash::input_method::InputMethodManager::Get() ->GetActiveIMEState() ->GetCurrentInputMethod(); std::string active_extension_id = - chromeos::extension_ime_util::GetExtensionIDFromInputMethodID( + ash::extension_ime_util::GetExtensionIDFromInputMethodID( current_input_method.id()); std::string error; InputMethodEngine* engine = @@ -986,7 +983,7 @@ InputMethodPrivateNotifyImeMenuItemActivatedFunction::Run() { return RespondNow(Error(InformativeError(error, static_function_name()))); std::unique_ptr<NotifyImeMenuItemActivated::Params> params( - NotifyImeMenuItemActivated::Params::Create(*args_)); + NotifyImeMenuItemActivated::Params::Create(args())); if (params->engine_id != engine->GetActiveComponentId()) return RespondNow( Error(InformativeError(kErrorEngineNotActive, static_function_name()))); @@ -1056,9 +1053,8 @@ void InputImeAPI::OnExtensionUnloaded(content::BrowserContext* browser_context, GetInputImeEventRouter(Profile::FromBrowserContext(browser_context)); if (!event_router) return; - chromeos::input_method::InputMethodManager* manager = - chromeos::input_method::InputMethodManager::Get(); - chromeos::ComponentExtensionIMEManager* comp_ext_ime_manager = + auto* manager = ash::input_method::InputMethodManager::Get(); + ash::ComponentExtensionIMEManager* comp_ext_ime_manager = manager->GetComponentExtensionIMEManager(); if (comp_ext_ime_manager->IsAllowlistedExtension(extension->id())) { @@ -1088,6 +1084,13 @@ void InputImeAPI::OnExtensionUnloaded(content::BrowserContext* browser_context, void InputImeAPI::OnListenerAdded(const EventListenerInfo& details) { if (!details.browser_context) return; + + // Other listeners may trigger this function, but only reactivate the IME + // on focus event. + if (details.event_name != input_ime::OnFocus::kEventName && + details.event_name != input_method_private::OnFocus::kEventName) + return; + std::string error; InputMethodEngine* engine = GetEngineIfActive(Profile::FromBrowserContext(details.browser_context), @@ -1097,4 +1100,21 @@ void InputImeAPI::OnListenerAdded(const EventListenerInfo& details) { engine->Enable(engine->GetActiveComponentId()); } +void InputImeAPI::OnListenerRemoved(const EventListenerInfo& details) { + if (!details.browser_context) + return; + + // If a key event listener was removed, cancel all the pending key events + // because they might've been dropped by the IME. + if (details.event_name != input_ime::OnKeyEvent::kEventName) + return; + + std::string error; + InputMethodEngine* engine = + GetEngineIfActive(Profile::FromBrowserContext(details.browser_context), + details.extension_id, &error); + if (engine) + engine->CancelPendingKeyEvents(); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h index 76c06be540e..b26a64dfd35 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_chromeos.h @@ -163,6 +163,11 @@ class InputMethodPrivateNotifyImeMenuItemActivatedFunction public: InputMethodPrivateNotifyImeMenuItemActivatedFunction() = default; + InputMethodPrivateNotifyImeMenuItemActivatedFunction( + const InputMethodPrivateNotifyImeMenuItemActivatedFunction&) = delete; + InputMethodPrivateNotifyImeMenuItemActivatedFunction& operator=( + const InputMethodPrivateNotifyImeMenuItemActivatedFunction&) = delete; + protected: ~InputMethodPrivateNotifyImeMenuItemActivatedFunction() override = default; @@ -172,8 +177,6 @@ class InputMethodPrivateNotifyImeMenuItemActivatedFunction private: DECLARE_EXTENSION_FUNCTION("inputMethodPrivate.notifyImeMenuItemActivated", INPUTMETHODPRIVATE_NOTIFYIMEMENUITEMACTIVATED) - DISALLOW_COPY_AND_ASSIGN( - InputMethodPrivateNotifyImeMenuItemActivatedFunction); }; class InputMethodPrivateGetCompositionBoundsFunction @@ -192,6 +195,10 @@ class InputMethodPrivateGetCompositionBoundsFunction class InputImeEventRouter : public InputImeEventRouterBase { public: explicit InputImeEventRouter(Profile* profile); + + InputImeEventRouter(const InputImeEventRouter&) = delete; + InputImeEventRouter& operator=(const InputImeEventRouter&) = delete; + ~InputImeEventRouter() override; bool RegisterImeExtension( @@ -219,8 +226,6 @@ class InputImeEventRouter : public InputImeEventRouterBase { engine_map_; // The first party ime extension which is unloaded unexpectedly. std::string unloaded_component_extension_id_; - - DISALLOW_COPY_AND_ASSIGN(InputImeEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h index a42c8600759..b60575d2b1c 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_event_router_base.h @@ -12,13 +12,17 @@ #include "base/macros.h" #include "chrome/browser/ash/input_method/input_method_engine.h" #include "chrome/browser/profiles/profile.h" -#include "ui/base/ime/chromeos/ime_engine_handler_interface.h" +#include "ui/base/ime/ash/ime_engine_handler_interface.h" namespace extensions { class InputImeEventRouterBase { public: explicit InputImeEventRouterBase(Profile* profile); + + InputImeEventRouterBase(const InputImeEventRouterBase&) = delete; + InputImeEventRouterBase& operator=(const InputImeEventRouterBase&) = delete; + virtual ~InputImeEventRouterBase(); // Gets the input method engine if the extension is active. @@ -30,8 +34,6 @@ class InputImeEventRouterBase { private: Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(InputImeEventRouterBase); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc index fa679979915..5a974b4aba0 100644 --- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc +++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.cc @@ -105,7 +105,7 @@ InstanceIDGetTokenFunction::~InstanceIDGetTokenFunction() {} ExtensionFunction::ResponseAction InstanceIDGetTokenFunction::DoWork() { std::unique_ptr<api::instance_id::GetToken::Params> params = - api::instance_id::GetToken::Params::Create(*args_); + api::instance_id::GetToken::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); GetInstanceID()->GetToken( @@ -132,7 +132,7 @@ InstanceIDDeleteTokenFunction::~InstanceIDDeleteTokenFunction() {} ExtensionFunction::ResponseAction InstanceIDDeleteTokenFunction::DoWork() { std::unique_ptr<api::instance_id::DeleteToken::Params> params = - api::instance_id::DeleteToken::Params::Create(*args_); + api::instance_id::DeleteToken::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); GetInstanceID()->DeleteToken( diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h index 33a0bb0dba5..5daa4cc7955 100644 --- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h +++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_api.h @@ -15,6 +15,9 @@ class InstanceIDApiFunction : public ExtensionFunction { public: InstanceIDApiFunction(); + InstanceIDApiFunction(const InstanceIDApiFunction&) = delete; + InstanceIDApiFunction& operator=(const InstanceIDApiFunction&) = delete; + protected: ~InstanceIDApiFunction() override; @@ -28,8 +31,6 @@ class InstanceIDApiFunction : public ExtensionFunction { bool IsEnabled() const; instance_id::InstanceID* GetInstanceID() const; - - DISALLOW_COPY_AND_ASSIGN(InstanceIDApiFunction); }; class InstanceIDGetIDFunction : public InstanceIDApiFunction { @@ -38,6 +39,9 @@ class InstanceIDGetIDFunction : public InstanceIDApiFunction { InstanceIDGetIDFunction(); + InstanceIDGetIDFunction(const InstanceIDGetIDFunction&) = delete; + InstanceIDGetIDFunction& operator=(const InstanceIDGetIDFunction&) = delete; + protected: ~InstanceIDGetIDFunction() override; @@ -46,8 +50,6 @@ class InstanceIDGetIDFunction : public InstanceIDApiFunction { private: void GetIDCompleted(const std::string& id); - - DISALLOW_COPY_AND_ASSIGN(InstanceIDGetIDFunction); }; class InstanceIDGetCreationTimeFunction : public InstanceIDApiFunction { @@ -57,6 +59,11 @@ class InstanceIDGetCreationTimeFunction : public InstanceIDApiFunction { InstanceIDGetCreationTimeFunction(); + InstanceIDGetCreationTimeFunction(const InstanceIDGetCreationTimeFunction&) = + delete; + InstanceIDGetCreationTimeFunction& operator=( + const InstanceIDGetCreationTimeFunction&) = delete; + protected: ~InstanceIDGetCreationTimeFunction() override; @@ -65,8 +72,6 @@ class InstanceIDGetCreationTimeFunction : public InstanceIDApiFunction { private: void GetCreationTimeCompleted(const base::Time& creation_time); - - DISALLOW_COPY_AND_ASSIGN(InstanceIDGetCreationTimeFunction); }; class InstanceIDGetTokenFunction : public InstanceIDApiFunction { @@ -75,6 +80,10 @@ class InstanceIDGetTokenFunction : public InstanceIDApiFunction { InstanceIDGetTokenFunction(); + InstanceIDGetTokenFunction(const InstanceIDGetTokenFunction&) = delete; + InstanceIDGetTokenFunction& operator=(const InstanceIDGetTokenFunction&) = + delete; + protected: ~InstanceIDGetTokenFunction() override; @@ -84,8 +93,6 @@ class InstanceIDGetTokenFunction : public InstanceIDApiFunction { private: void GetTokenCompleted(const std::string& token, instance_id::InstanceID::Result result); - - DISALLOW_COPY_AND_ASSIGN(InstanceIDGetTokenFunction); }; class InstanceIDDeleteTokenFunction : public InstanceIDApiFunction { @@ -94,6 +101,10 @@ class InstanceIDDeleteTokenFunction : public InstanceIDApiFunction { InstanceIDDeleteTokenFunction(); + InstanceIDDeleteTokenFunction(const InstanceIDDeleteTokenFunction&) = delete; + InstanceIDDeleteTokenFunction& operator=( + const InstanceIDDeleteTokenFunction&) = delete; + protected: ~InstanceIDDeleteTokenFunction() override; @@ -102,8 +113,6 @@ class InstanceIDDeleteTokenFunction : public InstanceIDApiFunction { private: void DeleteTokenCompleted(instance_id::InstanceID::Result result); - - DISALLOW_COPY_AND_ASSIGN(InstanceIDDeleteTokenFunction); }; class InstanceIDDeleteIDFunction : public InstanceIDApiFunction { @@ -112,6 +121,10 @@ class InstanceIDDeleteIDFunction : public InstanceIDApiFunction { InstanceIDDeleteIDFunction(); + InstanceIDDeleteIDFunction(const InstanceIDDeleteIDFunction&) = delete; + InstanceIDDeleteIDFunction& operator=(const InstanceIDDeleteIDFunction&) = + delete; + protected: ~InstanceIDDeleteIDFunction() override; @@ -120,8 +133,6 @@ class InstanceIDDeleteIDFunction : public InstanceIDApiFunction { private: void DeleteIDCompleted(instance_id::InstanceID::Result result); - - DISALLOW_COPY_AND_ASSIGN(InstanceIDDeleteIDFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc b/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc index 6edf1f9c45f..35200ea6519 100644 --- a/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc +++ b/chromium/chrome/browser/extensions/api/instance_id/instance_id_apitest.cc @@ -29,11 +29,12 @@ class InstanceIDApiTest : public ExtensionApiTest { public: InstanceIDApiTest(); + InstanceIDApiTest(const InstanceIDApiTest&) = delete; + InstanceIDApiTest& operator=(const InstanceIDApiTest&) = delete; + private: gcm::GCMProfileServiceFactory::ScopedTestingFactoryInstaller scoped_testing_factory_installer_; - - DISALLOW_COPY_AND_ASSIGN(InstanceIDApiTest); }; InstanceIDApiTest::InstanceIDApiTest() diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc index 373dc6b9cb9..27ee86f6e3f 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.cc @@ -44,17 +44,17 @@ #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_prefs.h" #include "third_party/icu/source/i18n/unicode/coll.h" -#include "ui/base/ime/chromeos/input_method_descriptor.h" +#include "ui/base/ime/ash/input_method_descriptor.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/l10n_util_collator.h" #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/constants/ash_features.h" #include "chrome/grit/generated_resources.h" -#include "ui/base/ime/chromeos/component_extension_ime_manager.h" -#include "ui/base/ime/chromeos/extension_ime_util.h" -#include "ui/base/ime/chromeos/input_method_manager.h" -#include "ui/base/ime/chromeos/input_method_util.h" +#include "ui/base/ime/ash/component_extension_ime_manager.h" +#include "ui/base/ime/ash/extension_ime_util.h" +#include "ui/base/ime/ash/input_method_manager.h" +#include "ui/base/ime/ash/input_method_util.h" #endif namespace extensions { @@ -64,26 +64,14 @@ namespace language_settings_private = api::language_settings_private; namespace { #if BUILDFLAG(IS_CHROMEOS_ASH) -using chromeos::input_method::InputMethodDescriptor; -using chromeos::input_method::InputMethodDescriptors; -using chromeos::input_method::InputMethodManager; -using chromeos::input_method::InputMethodUtil; +using ::ash::input_method::InputMethodDescriptor; +using ::ash::input_method::InputMethodDescriptors; +using ::ash::input_method::InputMethodManager; +using ::ash::input_method::InputMethodUtil; // Number of IMEs that are needed to automatically enable the IME menu option. const size_t kNumImesToAutoEnableImeMenu = 2; -// Returns the set of IDs of all enabled IMEs. -base::flat_set<std::string> GetEnabledIMEs( - scoped_refptr<InputMethodManager::State> ime_state) { - return ime_state->GetAllowedInputMethods(); -} - -// Returns the set of IDs of all allowed IMEs. -base::flat_set<std::string> GetAllowedIMEs( - scoped_refptr<InputMethodManager::State> ime_state) { - return ime_state->GetAllowedInputMethods(); -} - // Returns the set of IDs of enabled IMEs for the given pref. base::flat_set<std::string> GetIMEsFromPref(PrefService* prefs, const char* pref_name) { @@ -131,8 +119,7 @@ std::vector<std::string> GetSortedComponentIMEs( // Get all input methods for this language. std::vector<std::string> input_method_ids; manager->GetInputMethodUtil()->GetInputMethodIdsFromLanguageCode( - language_code, chromeos::input_method::kAllInputMethods, - &input_method_ids); + language_code, ash::input_method::kAllInputMethods, &input_method_ids); // Append the enabled ones to the new list. Also remove them from the set // so they aren't duplicated for other languages. for (const auto& input_method_id : input_method_ids) { @@ -163,7 +150,7 @@ std::vector<std::string> GetSortedThirdPartyIMEs( // Add the fake language for ARC IMEs at the very last of the list. Unlike // Chrome OS IMEs, these ARC ones are not associated with any (real) language. - enabled_languages.push_back(chromeos::extension_ime_util::kArcImeLanguage); + enabled_languages.push_back(ash::extension_ime_util::kArcImeLanguage); InputMethodDescriptors descriptors; ime_state->GetInputMethodExtensions(&descriptors); @@ -270,8 +257,7 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() { language.supports_translate = std::make_unique<bool>(true); } - std::string temp_locale = entry.code; - if (language::ConvertToActualUILocale(&temp_locale)) { + if (l10n_util::IsUserFacingUILocale(entry.code)) { language.supports_ui = std::make_unique<bool>(true); } #if BUILDFLAG(IS_CHROMEOS_ASH) @@ -290,7 +276,7 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() { // drop-down menu doesn't list the fake language. { language_settings_private::Language language; - language.code = chromeos::extension_ime_util::kArcImeLanguage; + language.code = ash::extension_ime_util::kArcImeLanguage; language.display_name = l10n_util::GetStringUTF8(IDS_SETTINGS_LANGUAGES_KEYBOARD_APPS); language_list_->Append(language.ToValue()); @@ -352,7 +338,7 @@ LanguageSettingsPrivateEnableLanguageFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateEnableLanguageFunction::Run() { const auto parameters = - language_settings_private::EnableLanguage::Params::Create(*args_); + language_settings_private::EnableLanguage::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); const std::string& language_code = parameters->language_code; @@ -383,7 +369,7 @@ LanguageSettingsPrivateDisableLanguageFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateDisableLanguageFunction::Run() { const auto parameters = - language_settings_private::DisableLanguage::Params::Create(*args_); + language_settings_private::DisableLanguage::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); const std::string& language_code = parameters->language_code; @@ -417,7 +403,7 @@ LanguageSettingsPrivateSetEnableTranslationForLanguageFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateSetEnableTranslationForLanguageFunction::Run() { const auto parameters = language_settings_private:: - SetEnableTranslationForLanguage::Params::Create(*args_); + SetEnableTranslationForLanguage::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); const std::string& language_code = parameters->language_code; // True if translation enabled, false if disabled. @@ -468,7 +454,7 @@ LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction::Run() { const auto params = language_settings_private:: - SetLanguageAlwaysTranslateState::Params::Create(*args_); + SetLanguageAlwaysTranslateState::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); const std::unique_ptr<translate::TranslatePrefs> translate_prefs = @@ -510,7 +496,7 @@ LanguageSettingsPrivateMoveLanguageFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateMoveLanguageFunction::Run() { const auto parameters = - language_settings_private::MoveLanguage::Params::Create(*args_); + language_settings_private::MoveLanguage::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); const std::string app_locale = g_browser_process->GetApplicationLocale(); @@ -617,7 +603,7 @@ LanguageSettingsPrivateGetSpellcheckWordsFunction::GetSpellcheckWords() const { std::unique_ptr<base::ListValue> word_list(new base::ListValue()); const std::set<std::string>& words = dictionary->GetWords(); for (const std::string& word : words) - word_list->AppendString(word); + word_list->Append(word); return word_list; } @@ -630,7 +616,7 @@ LanguageSettingsPrivateAddSpellcheckWordFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateAddSpellcheckWordFunction::Run() { const auto params = - language_settings_private::AddSpellcheckWord::Params::Create(*args_); + language_settings_private::AddSpellcheckWord::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); SpellcheckService* service = @@ -656,7 +642,7 @@ LanguageSettingsPrivateRemoveSpellcheckWordFunction:: ExtensionFunction::ResponseAction LanguageSettingsPrivateRemoveSpellcheckWordFunction::Run() { const auto params = - language_settings_private::RemoveSpellcheckWord::Params::Create(*args_); + language_settings_private::RemoveSpellcheckWord::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); SpellcheckService* service = @@ -699,7 +685,7 @@ ExtensionFunction::ResponseAction LanguageSettingsPrivateSetTranslateTargetLanguageFunction::Run() { const auto parameters = language_settings_private::SetTranslateTargetLanguage::Params::Create( - *args_); + args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); const std::string& language_code = parameters->language_code; @@ -730,17 +716,15 @@ void PopulateInputMethodListFromDescriptors( if (!ime_state.get()) return; - const base::flat_set<std::string> active_ids(GetEnabledIMEs(ime_state)); - const base::flat_set<std::string> allowed_ids(GetAllowedIMEs(ime_state)); + const base::flat_set<std::string> enabled_ids( + ime_state->GetEnabledInputMethodIds()); + const base::flat_set<std::string> allowed_ids( + ime_state->GetAllowedInputMethodIds()); - // Collator used to sort display names in the given locale. UErrorCode error = U_ZERO_ERROR; - const std::string app_locale = g_browser_process->GetApplicationLocale(); std::unique_ptr<icu::Collator> collator( - icu::Collator::createInstance(icu::Locale(app_locale.c_str()), error)); - if (U_FAILURE(error)) { - collator.reset(); - } + icu::Collator::createInstance(error)); // use current ICU locale + DCHECK(U_SUCCESS(error)); // Map of sorted [display name -> input methods]. std::map<std::u16string, language_settings_private::InputMethod, @@ -753,7 +737,7 @@ void PopulateInputMethodListFromDescriptors( input_method.display_name = util->GetLocalizedDisplayName(descriptor); input_method.language_codes = descriptor.language_codes(); input_method.tags = GetInputMethodTags(&input_method); - if (base::Contains(active_ids, input_method.id)) + if (base::Contains(enabled_ids, input_method.id)) input_method.enabled = std::make_unique<bool>(true); if (descriptor.options_page_url().is_valid()) input_method.has_options_page = std::make_unique<bool>(true); @@ -785,7 +769,7 @@ LanguageSettingsPrivateGetInputMethodListsFunction::Run() { language_settings_private::InputMethodLists input_method_lists; InputMethodManager* manager = InputMethodManager::Get(); - chromeos::ComponentExtensionIMEManager* component_extension_manager = + ash::ComponentExtensionIMEManager* component_extension_manager = manager->GetComponentExtensionIMEManager(); PopulateInputMethodListFromDescriptors( component_extension_manager->GetAllIMEAsInputMethodDescriptor(), @@ -817,7 +801,7 @@ LanguageSettingsPrivateAddInputMethodFunction::Run() { EXTENSION_FUNCTION_VALIDATE(false); #else const auto params = - language_settings_private::AddInputMethod::Params::Create(*args_); + language_settings_private::AddInputMethod::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); InputMethodManager* manager = InputMethodManager::Get(); @@ -828,8 +812,7 @@ LanguageSettingsPrivateAddInputMethodFunction::Run() { std::string new_input_method_id = params->input_method_id; bool is_component_extension_ime = - chromeos::extension_ime_util::IsComponentExtensionIME( - new_input_method_id); + ash::extension_ime_util::IsComponentExtensionIME(new_input_method_id); PrefService* prefs = Profile::FromBrowserContext(browser_context())->GetPrefs(); @@ -892,7 +875,7 @@ LanguageSettingsPrivateRemoveInputMethodFunction::Run() { EXTENSION_FUNCTION_VALIDATE(false); #else const auto params = - language_settings_private::RemoveInputMethod::Params::Create(*args_); + language_settings_private::RemoveInputMethod::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); InputMethodManager* manager = InputMethodManager::Get(); @@ -903,7 +886,7 @@ LanguageSettingsPrivateRemoveInputMethodFunction::Run() { std::string input_method_id = params->input_method_id; bool is_component_extension_ime = - chromeos::extension_ime_util::IsComponentExtensionIME(input_method_id); + ash::extension_ime_util::IsComponentExtensionIME(input_method_id); // Use the pref for the corresponding input method type. PrefService* prefs = @@ -937,7 +920,7 @@ ExtensionFunction::ResponseAction LanguageSettingsPrivateRetryDownloadDictionaryFunction::Run() { const auto parameters = language_settings_private::RetryDownloadDictionary::Params::Create( - *args_); + args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); LanguageSettingsPrivateDelegate* delegate = diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h index 7cbc552c65e..8c9b43a4338 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api.h @@ -17,6 +17,12 @@ class LanguageSettingsPrivateGetLanguageListFunction : public ExtensionFunction { public: LanguageSettingsPrivateGetLanguageListFunction(); + + LanguageSettingsPrivateGetLanguageListFunction( + const LanguageSettingsPrivateGetLanguageListFunction&) = delete; + LanguageSettingsPrivateGetLanguageListFunction& operator=( + const LanguageSettingsPrivateGetLanguageListFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.getLanguageList", LANGUAGESETTINGSPRIVATE_GETLANGUAGELIST) @@ -33,14 +39,18 @@ class LanguageSettingsPrivateGetLanguageListFunction private: std::unique_ptr<base::ListValue> language_list_; - - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateGetLanguageListFunction); }; // Implements the languageSettingsPrivate.enableLanguage method. class LanguageSettingsPrivateEnableLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateEnableLanguageFunction(); + + LanguageSettingsPrivateEnableLanguageFunction( + const LanguageSettingsPrivateEnableLanguageFunction&) = delete; + LanguageSettingsPrivateEnableLanguageFunction& operator=( + const LanguageSettingsPrivateEnableLanguageFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.enableLanguage", LANGUAGESETTINGSPRIVATE_ENABLELANGUAGE) @@ -49,9 +59,6 @@ class LanguageSettingsPrivateEnableLanguageFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateEnableLanguageFunction); }; // Implements the languageSettingsPrivate.disableLanguage method. @@ -59,6 +66,12 @@ class LanguageSettingsPrivateDisableLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateDisableLanguageFunction(); + + LanguageSettingsPrivateDisableLanguageFunction( + const LanguageSettingsPrivateDisableLanguageFunction&) = delete; + LanguageSettingsPrivateDisableLanguageFunction& operator=( + const LanguageSettingsPrivateDisableLanguageFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.disableLanguage", LANGUAGESETTINGSPRIVATE_DISABLELANGUAGE) @@ -67,9 +80,6 @@ class LanguageSettingsPrivateDisableLanguageFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateDisableLanguageFunction); }; // Implements the languageSettingsPrivate.setEnableTranslationForLanguage @@ -78,6 +88,14 @@ class LanguageSettingsPrivateSetEnableTranslationForLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateSetEnableTranslationForLanguageFunction(); + + LanguageSettingsPrivateSetEnableTranslationForLanguageFunction( + const LanguageSettingsPrivateSetEnableTranslationForLanguageFunction&) = + delete; + LanguageSettingsPrivateSetEnableTranslationForLanguageFunction& operator=( + const LanguageSettingsPrivateSetEnableTranslationForLanguageFunction&) = + delete; + DECLARE_EXTENSION_FUNCTION( "languageSettingsPrivate.setEnableTranslationForLanguage", LANGUAGESETTINGSPRIVATE_SETENABLETRANSLATIONFORLANGUAGE) @@ -87,16 +105,18 @@ class LanguageSettingsPrivateSetEnableTranslationForLanguageFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateSetEnableTranslationForLanguageFunction); }; // Implements the languageSettingsPrivate.moveLanguage method. class LanguageSettingsPrivateMoveLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateMoveLanguageFunction(); + + LanguageSettingsPrivateMoveLanguageFunction( + const LanguageSettingsPrivateMoveLanguageFunction&) = delete; + LanguageSettingsPrivateMoveLanguageFunction& operator=( + const LanguageSettingsPrivateMoveLanguageFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.moveLanguage", LANGUAGESETTINGSPRIVATE_MOVELANGUAGE) @@ -105,9 +125,6 @@ class LanguageSettingsPrivateMoveLanguageFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateMoveLanguageFunction); }; // Implements the languageSettingsPrivate.getAlwaysTranslateLanguages method. @@ -115,6 +132,14 @@ class LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction : public ExtensionFunction { public: LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction(); + + LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction( + const LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction&) = + delete; + LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction& operator=( + const LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction&) = + delete; + DECLARE_EXTENSION_FUNCTION( "languageSettingsPrivate.getAlwaysTranslateLanguages", LANGUAGESETTINGSPRIVATE_GETALWAYSTRANSLATELANGUAGES) @@ -124,10 +149,6 @@ class LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateGetAlwaysTranslateLanguagesFunction); }; // Implements the languageSettingsPrivate.setLanguageAlwaysTranslateState @@ -136,6 +157,14 @@ class LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction : public ExtensionFunction { public: LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction(); + + LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction( + const LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction&) = + delete; + LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction& operator=( + const LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction&) = + delete; + DECLARE_EXTENSION_FUNCTION( "languageSettingsPrivate.setLanguageAlwaysTranslateState", LANGUAGESETTINGSPRIVATE_SETLANGUAGEALWAYSTRANSLATESTATE) @@ -145,10 +174,6 @@ class LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateSetLanguageAlwaysTranslateStateFunction); }; // Implements the languageSettingsPrivate.getNeverTranslateLanguages method. @@ -156,6 +181,14 @@ class LanguageSettingsPrivateGetNeverTranslateLanguagesFunction : public ExtensionFunction { public: LanguageSettingsPrivateGetNeverTranslateLanguagesFunction(); + + LanguageSettingsPrivateGetNeverTranslateLanguagesFunction( + const LanguageSettingsPrivateGetNeverTranslateLanguagesFunction&) = + delete; + LanguageSettingsPrivateGetNeverTranslateLanguagesFunction& operator=( + const LanguageSettingsPrivateGetNeverTranslateLanguagesFunction&) = + delete; + DECLARE_EXTENSION_FUNCTION( "languageSettingsPrivate.getNeverTranslateLanguages", LANGUAGESETTINGSPRIVATE_GETNEVERTRANSLATELANGUAGES) @@ -165,10 +198,6 @@ class LanguageSettingsPrivateGetNeverTranslateLanguagesFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateGetNeverTranslateLanguagesFunction); }; // Implements the languageSettingsPrivate.getSpellcheckDictionaryStatuses @@ -177,6 +206,14 @@ class LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction : public ExtensionFunction { public: LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction(); + + LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction( + const LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction&) = + delete; + LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction& operator=( + const LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction&) = + delete; + DECLARE_EXTENSION_FUNCTION( "languageSettingsPrivate.getSpellcheckDictionaryStatuses", LANGUAGESETTINGSPRIVATE_GETSPELLCHECKDICTIONARYSTATUS) @@ -186,10 +223,6 @@ class LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction); }; // Implements the languageSettingsPrivate.getSpellcheckWords method. @@ -198,6 +231,12 @@ class LanguageSettingsPrivateGetSpellcheckWordsFunction public SpellcheckCustomDictionary::Observer { public: LanguageSettingsPrivateGetSpellcheckWordsFunction(); + + LanguageSettingsPrivateGetSpellcheckWordsFunction( + const LanguageSettingsPrivateGetSpellcheckWordsFunction&) = delete; + LanguageSettingsPrivateGetSpellcheckWordsFunction& operator=( + const LanguageSettingsPrivateGetSpellcheckWordsFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.getSpellcheckWords", LANGUAGESETTINGSPRIVATE_GETSPELLCHECKWORDS) @@ -214,9 +253,6 @@ class LanguageSettingsPrivateGetSpellcheckWordsFunction // Returns the list of words from the loaded custom dictionary. std::unique_ptr<base::ListValue> GetSpellcheckWords() const; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateGetSpellcheckWordsFunction); }; // Implements the languageSettingsPrivate.addSpellcheckWord method. @@ -224,6 +260,12 @@ class LanguageSettingsPrivateAddSpellcheckWordFunction : public ExtensionFunction { public: LanguageSettingsPrivateAddSpellcheckWordFunction(); + + LanguageSettingsPrivateAddSpellcheckWordFunction( + const LanguageSettingsPrivateAddSpellcheckWordFunction&) = delete; + LanguageSettingsPrivateAddSpellcheckWordFunction& operator=( + const LanguageSettingsPrivateAddSpellcheckWordFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.addSpellcheckWord", LANGUAGESETTINGSPRIVATE_ADDSPELLCHECKWORD) @@ -232,9 +274,6 @@ class LanguageSettingsPrivateAddSpellcheckWordFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateAddSpellcheckWordFunction); }; // Implements the languageSettingsPrivate.removeSpellcheckWord method. @@ -242,6 +281,12 @@ class LanguageSettingsPrivateRemoveSpellcheckWordFunction : public ExtensionFunction { public: LanguageSettingsPrivateRemoveSpellcheckWordFunction(); + + LanguageSettingsPrivateRemoveSpellcheckWordFunction( + const LanguageSettingsPrivateRemoveSpellcheckWordFunction&) = delete; + LanguageSettingsPrivateRemoveSpellcheckWordFunction& operator=( + const LanguageSettingsPrivateRemoveSpellcheckWordFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.removeSpellcheckWord", LANGUAGESETTINGSPRIVATE_REMOVESPELLCHECKWORD) @@ -250,9 +295,6 @@ class LanguageSettingsPrivateRemoveSpellcheckWordFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateRemoveSpellcheckWordFunction); }; // Implements the languageSettingsPrivate.getTranslateTargetLanguage method. @@ -260,6 +302,14 @@ class LanguageSettingsPrivateGetTranslateTargetLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateGetTranslateTargetLanguageFunction(); + + LanguageSettingsPrivateGetTranslateTargetLanguageFunction( + const LanguageSettingsPrivateGetTranslateTargetLanguageFunction&) = + delete; + LanguageSettingsPrivateGetTranslateTargetLanguageFunction& operator=( + const LanguageSettingsPrivateGetTranslateTargetLanguageFunction&) = + delete; + DECLARE_EXTENSION_FUNCTION( "languageSettingsPrivate.getTranslateTargetLanguage", LANGUAGESETTINGSPRIVATE_GETTRANSLATETARGETLANGUAGE) @@ -269,10 +319,6 @@ class LanguageSettingsPrivateGetTranslateTargetLanguageFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateGetTranslateTargetLanguageFunction); }; // Implements the languageSettingsPrivate.setTranslateTargetLanguage method. @@ -280,6 +326,14 @@ class LanguageSettingsPrivateSetTranslateTargetLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateSetTranslateTargetLanguageFunction(); + + LanguageSettingsPrivateSetTranslateTargetLanguageFunction( + const LanguageSettingsPrivateSetTranslateTargetLanguageFunction&) = + delete; + LanguageSettingsPrivateSetTranslateTargetLanguageFunction& operator=( + const LanguageSettingsPrivateSetTranslateTargetLanguageFunction&) = + delete; + DECLARE_EXTENSION_FUNCTION( "languageSettingsPrivate.setTranslateTargetLanguage", LANGUAGESETTINGSPRIVATE_SETTRANSLATETARGETLANGUAGE) @@ -289,10 +343,6 @@ class LanguageSettingsPrivateSetTranslateTargetLanguageFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateSetTranslateTargetLanguageFunction); }; // Implements the languageSettingsPrivate.getInputMethodLists method. @@ -300,6 +350,12 @@ class LanguageSettingsPrivateGetInputMethodListsFunction : public ExtensionFunction { public: LanguageSettingsPrivateGetInputMethodListsFunction(); + + LanguageSettingsPrivateGetInputMethodListsFunction( + const LanguageSettingsPrivateGetInputMethodListsFunction&) = delete; + LanguageSettingsPrivateGetInputMethodListsFunction& operator=( + const LanguageSettingsPrivateGetInputMethodListsFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.getInputMethodLists", LANGUAGESETTINGSPRIVATE_GETINPUTMETHODLISTS) @@ -308,15 +364,18 @@ class LanguageSettingsPrivateGetInputMethodListsFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateGetInputMethodListsFunction); }; // Implements the languageSettingsPrivate.addInputMethod method. class LanguageSettingsPrivateAddInputMethodFunction : public ExtensionFunction { public: LanguageSettingsPrivateAddInputMethodFunction(); + + LanguageSettingsPrivateAddInputMethodFunction( + const LanguageSettingsPrivateAddInputMethodFunction&) = delete; + LanguageSettingsPrivateAddInputMethodFunction& operator=( + const LanguageSettingsPrivateAddInputMethodFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.addInputMethod", LANGUAGESETTINGSPRIVATE_ADDINPUTMETHOD) @@ -325,9 +384,6 @@ class LanguageSettingsPrivateAddInputMethodFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateAddInputMethodFunction); }; // Implements the languageSettingsPrivate.removeInputMethod method. @@ -335,6 +391,12 @@ class LanguageSettingsPrivateRemoveInputMethodFunction : public ExtensionFunction { public: LanguageSettingsPrivateRemoveInputMethodFunction(); + + LanguageSettingsPrivateRemoveInputMethodFunction( + const LanguageSettingsPrivateRemoveInputMethodFunction&) = delete; + LanguageSettingsPrivateRemoveInputMethodFunction& operator=( + const LanguageSettingsPrivateRemoveInputMethodFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.removeInputMethod", LANGUAGESETTINGSPRIVATE_REMOVEINPUTMETHOD) @@ -343,9 +405,6 @@ class LanguageSettingsPrivateRemoveInputMethodFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateRemoveInputMethodFunction); }; // Implements the languageSettingsPrivate.retryDownloadDictionary method. @@ -353,6 +412,12 @@ class LanguageSettingsPrivateRetryDownloadDictionaryFunction : public ExtensionFunction { public: LanguageSettingsPrivateRetryDownloadDictionaryFunction(); + + LanguageSettingsPrivateRetryDownloadDictionaryFunction( + const LanguageSettingsPrivateRetryDownloadDictionaryFunction&) = delete; + LanguageSettingsPrivateRetryDownloadDictionaryFunction& operator=( + const LanguageSettingsPrivateRetryDownloadDictionaryFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.retryDownloadDictionary", LANGUAGESETTINGSPRIVATE_RETRYDOWNLOADDICTIONARY) @@ -361,10 +426,6 @@ class LanguageSettingsPrivateRetryDownloadDictionaryFunction // ExtensionFunction overrides. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN( - LanguageSettingsPrivateRetryDownloadDictionaryFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc index aa7d18a0b9f..a233c135b34 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_api_unittest.cc @@ -34,12 +34,12 @@ #if BUILDFLAG(IS_CHROMEOS_ASH) #include "ash/constants/ash_features.h" -#include "ui/base/ime/chromeos/component_extension_ime_manager.h" -#include "ui/base/ime/chromeos/extension_ime_util.h" -#include "ui/base/ime/chromeos/fake_input_method_delegate.h" -#include "ui/base/ime/chromeos/input_method_util.h" -#include "ui/base/ime/chromeos/mock_component_extension_ime_manager_delegate.h" -#include "ui/base/ime/chromeos/mock_input_method_manager.h" +#include "ui/base/ime/ash/component_extension_ime_manager.h" +#include "ui/base/ime/ash/extension_ime_util.h" +#include "ui/base/ime/ash/fake_input_method_delegate.h" +#include "ui/base/ime/ash/input_method_util.h" +#include "ui/base/ime/ash/mock_component_extension_ime_manager_delegate.h" +#include "ui/base/ime/ash/mock_input_method_manager.h" #include "ui/base/l10n/l10n_util.h" #endif @@ -414,6 +414,15 @@ void LanguageSettingsPrivateApiTest::RunGetLanguageListTest() { break; } } + + // Check that zh and zh-HK aren't shown as supporting UI. + if (language_code == "zh" || language_code == "zh-HK") { + const absl::optional<bool> maybe_supports_ui = + language_val.FindBoolKey("supportsUI"); + const bool supports_ui = + maybe_supports_ui.has_value() ? maybe_supports_ui.value() : false; + EXPECT_FALSE(supports_ui) << language_code << " should not support UI"; + } } EXPECT_EQ(languages_to_test.size(), languages_to_test_found_count); @@ -422,26 +431,26 @@ void LanguageSettingsPrivateApiTest::RunGetLanguageListTest() { #if BUILDFLAG(IS_CHROMEOS_ASH) namespace { -namespace input_method = chromeos::input_method; +namespace input_method = ::ash::input_method; using input_method::InputMethodDescriptor; using input_method::InputMethodManager; using input_method::MockComponentExtensionIMEManagerDelegate; std::string GetExtensionImeId() { - std::string kExtensionImeId = chromeos::extension_ime_util::GetInputMethodID( + std::string kExtensionImeId = ash::extension_ime_util::GetInputMethodID( crx_file::id_util::GenerateId("test.extension.ime"), "us"); return kExtensionImeId; } std::string GetComponentExtensionImeId() { std::string kComponentExtensionImeId = - chromeos::extension_ime_util::GetComponentInputMethodID( + ash::extension_ime_util::GetComponentInputMethodID( crx_file::id_util::GenerateId("test.component.extension.ime"), "us"); return kComponentExtensionImeId; } std::string GetArcImeId() { - std::string kArcImeId = chromeos::extension_ime_util::GetArcInputMethodID( + std::string kArcImeId = ash::extension_ime_util::GetArcInputMethodID( crx_file::id_util::GenerateId("test.arc.ime"), "us"); return kArcImeId; } @@ -459,13 +468,16 @@ class TestInputMethodManager : public input_method::MockInputMethodManager { InputMethodDescriptor component_extension_ime( GetComponentExtensionImeId(), "ComponentExtensionIme", "", layout, {"en-US", "en"}, false /* is_login_keyboard */, GURL(), GURL()); - InputMethodDescriptor arc_ime( - GetArcImeId(), "ArcIme", "", layout, - {chromeos::extension_ime_util::kArcImeLanguage}, - false /* is_login_keyboard */, GURL(), GURL()); + InputMethodDescriptor arc_ime(GetArcImeId(), "ArcIme", "", layout, + {ash::extension_ime_util::kArcImeLanguage}, + false /* is_login_keyboard */, GURL(), + GURL()); input_methods_ = {extension_ime, component_extension_ime, arc_ime}; } + TestState(const TestState&) = delete; + TestState& operator=(const TestState&) = delete; + void GetInputMethodExtensions( input_method::InputMethodDescriptors* descriptors) override { for (const auto& descriptor : input_methods_) @@ -477,17 +489,17 @@ class TestInputMethodManager : public input_method::MockInputMethodManager { protected: friend base::RefCounted<InputMethodManager::State>; ~TestState() override = default; - - DISALLOW_COPY_AND_ASSIGN(TestState); }; TestInputMethodManager() : state_(new TestState), util_(&delegate_) { util_.AppendInputMethods(state_->input_methods_); - component_ext_mgr_ = - std::make_unique<chromeos::ComponentExtensionIMEManager>( - std::make_unique<MockComponentExtensionIMEManagerDelegate>()); + component_ext_mgr_ = std::make_unique<ash::ComponentExtensionIMEManager>( + std::make_unique<MockComponentExtensionIMEManagerDelegate>()); } + TestInputMethodManager(const TestInputMethodManager&) = delete; + TestInputMethodManager& operator=(const TestInputMethodManager&) = delete; + scoped_refptr<InputMethodManager::State> GetActiveIMEState() override { return state_; } @@ -496,7 +508,7 @@ class TestInputMethodManager : public input_method::MockInputMethodManager { return &util_; } - chromeos::ComponentExtensionIMEManager* GetComponentExtensionIMEManager() + ash::ComponentExtensionIMEManager* GetComponentExtensionIMEManager() override { return component_ext_mgr_.get(); } @@ -505,9 +517,7 @@ class TestInputMethodManager : public input_method::MockInputMethodManager { scoped_refptr<TestState> state_; input_method::FakeInputMethodDelegate delegate_; input_method::InputMethodUtil util_; - std::unique_ptr<chromeos::ComponentExtensionIMEManager> component_ext_mgr_; - - DISALLOW_COPY_AND_ASSIGN(TestInputMethodManager); + std::unique_ptr<ash::ComponentExtensionIMEManager> component_ext_mgr_; }; } // namespace diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc index 81f389cee2f..55d8a48745f 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.cc @@ -114,8 +114,7 @@ void LanguageSettingsPrivateDelegate::Shutdown() { #if BUILDFLAG(IS_CHROMEOS_ASH) if (listening_input_method_) { - auto* input_method_manager = - chromeos::input_method::InputMethodManager::Get(); + auto* input_method_manager = ash::input_method::InputMethodManager::Get(); if (input_method_manager) input_method_manager->RemoveObserver(this); listening_input_method_ = false; @@ -163,7 +162,7 @@ void LanguageSettingsPrivateDelegate::Observe( #if BUILDFLAG(IS_CHROMEOS_ASH) void LanguageSettingsPrivateDelegate::InputMethodChanged( - chromeos::input_method::InputMethodManager* manager, + ash::input_method::InputMethodManager* manager, Profile* profile, bool show_message) { // Nothing to do. @@ -302,8 +301,7 @@ void LanguageSettingsPrivateDelegate:: event_router->HasEventListener( language_settings_private::OnInputMethodRemoved::kEventName); - auto* input_method_manager = - chromeos::input_method::InputMethodManager::Get(); + auto* input_method_manager = ash::input_method::InputMethodManager::Get(); if (input_method_manager) { if (should_listen && !listening_input_method_) input_method_manager->AddObserver(this); diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.h b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.h index 81ae4fad301..543d1d8c6fc 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.h +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate.h @@ -21,7 +21,7 @@ #include "extensions/browser/event_router.h" #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "ui/base/ime/chromeos/input_method_manager.h" +#include "ui/base/ime/ash/input_method_manager.h" #endif namespace content { @@ -37,13 +37,19 @@ class LanguageSettingsPrivateDelegate public EventRouter::Observer, public content::NotificationObserver, #if BUILDFLAG(IS_CHROMEOS_ASH) - public chromeos::input_method::InputMethodManager::Observer, + public ash::input_method::InputMethodManager::Observer, #endif // BUILDFLAG(IS_CHROMEOS_ASH) public SpellcheckHunspellDictionary::Observer, public SpellcheckCustomDictionary::Observer { public: static LanguageSettingsPrivateDelegate* Create( content::BrowserContext* browser_context); + + LanguageSettingsPrivateDelegate(const LanguageSettingsPrivateDelegate&) = + delete; + LanguageSettingsPrivateDelegate& operator=( + const LanguageSettingsPrivateDelegate&) = delete; + ~LanguageSettingsPrivateDelegate() override; // Returns the languages and statuses of the enabled spellcheck dictionaries. @@ -70,8 +76,8 @@ class LanguageSettingsPrivateDelegate void OnListenerRemoved(const EventListenerInfo& details) override; #if BUILDFLAG(IS_CHROMEOS_ASH) - // chromeos::input_method::InputMethodManager::Observer implementation. - void InputMethodChanged(chromeos::input_method::InputMethodManager* manager, + // ash::input_method::InputMethodManager::Observer implementation. + void InputMethodChanged(ash::input_method::InputMethodManager* manager, Profile* profile, bool show_message) override; void OnInputMethodExtensionAdded(const std::string& extension_id) override; @@ -144,8 +150,6 @@ class LanguageSettingsPrivateDelegate content::NotificationRegistrar notification_registrar_; PrefChangeRegistrar pref_change_registrar_; - - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateDelegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_factory.h b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_factory.h index f72ab5c46ed..2b63d097d9b 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_factory.h +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_factory.h @@ -20,6 +20,11 @@ class LanguageSettingsPrivateDelegate; class LanguageSettingsPrivateDelegateFactory : public BrowserContextKeyedServiceFactory { public: + LanguageSettingsPrivateDelegateFactory( + const LanguageSettingsPrivateDelegateFactory&) = delete; + LanguageSettingsPrivateDelegateFactory& operator=( + const LanguageSettingsPrivateDelegateFactory&) = delete; + // Returns the LanguageSettingsPrivateDelegate for |context|, creating it // if it is not yet created. static LanguageSettingsPrivateDelegate* GetForBrowserContext( @@ -44,8 +49,6 @@ class LanguageSettingsPrivateDelegateFactory // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; - - DISALLOW_COPY_AND_ASSIGN(LanguageSettingsPrivateDelegateFactory); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc index 5a581df3758..fe8d95176ac 100644 --- a/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc +++ b/chromium/chrome/browser/extensions/api/language_settings_private/language_settings_private_delegate_unittest.cc @@ -55,7 +55,7 @@ class LanguageSettingsPrivateDelegateTest #endif // defined(OS_WIN) base::ListValue language_codes; - language_codes.AppendString("fr"); + language_codes.Append("fr"); profile()->GetPrefs()->Set(spellcheck::prefs::kSpellCheckDictionaries, language_codes); diff --git a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc index b172325913a..c2f13fd6326 100644 --- a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc +++ b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.cc @@ -32,15 +32,16 @@ #include "chrome/browser/ui/tab_helpers.h" #include "chrome/browser/ui/web_applications/web_app_dialog_utils.h" #include "chrome/browser/ui/webui/extensions/extension_icon_source.h" -#include "chrome/browser/web_applications/components/web_app_constants.h" -#include "chrome/browser/web_applications/components/web_app_helpers.h" -#include "chrome/browser/web_applications/components/web_app_install_utils.h" -#include "chrome/browser/web_applications/components/web_app_utils.h" -#include "chrome/browser/web_applications/components/web_application_info.h" +#include "chrome/browser/web_applications/web_app_constants.h" +#include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_install_manager.h" #include "chrome/browser/web_applications/web_app_install_params.h" +#include "chrome/browser/web_applications/web_app_install_utils.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" +#include "chrome/browser/web_applications/web_app_utils.h" +#include "chrome/browser/web_applications/web_application_info.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/extensions/extension_metrics.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "components/favicon/core/favicon_service.h" @@ -142,6 +143,12 @@ class ManagementSetEnabledFunctionInstallPromptDelegate std::make_unique<ExtensionInstallPrompt::Prompt>(type), ExtensionInstallPrompt::GetDefaultShowDialogCallback()); } + + ManagementSetEnabledFunctionInstallPromptDelegate( + const ManagementSetEnabledFunctionInstallPromptDelegate&) = delete; + ManagementSetEnabledFunctionInstallPromptDelegate& operator=( + const ManagementSetEnabledFunctionInstallPromptDelegate&) = delete; + ~ManagementSetEnabledFunctionInstallPromptDelegate() override {} private: @@ -158,8 +165,6 @@ class ManagementSetEnabledFunctionInstallPromptDelegate base::WeakPtrFactory<ManagementSetEnabledFunctionInstallPromptDelegate> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(ManagementSetEnabledFunctionInstallPromptDelegate); }; class ManagementUninstallFunctionUninstallDialogDelegate @@ -202,6 +207,11 @@ class ManagementUninstallFunctionUninstallDialogDelegate } } + ManagementUninstallFunctionUninstallDialogDelegate( + const ManagementUninstallFunctionUninstallDialogDelegate&) = delete; + ManagementUninstallFunctionUninstallDialogDelegate& operator=( + const ManagementUninstallFunctionUninstallDialogDelegate&) = delete; + ~ManagementUninstallFunctionUninstallDialogDelegate() override {} // ExtensionUninstallDialog::Delegate implementation. @@ -214,8 +224,6 @@ class ManagementUninstallFunctionUninstallDialogDelegate extensions::ManagementUninstallFunctionBase* function_; std::unique_ptr<extensions::ExtensionUninstallDialog> extension_uninstall_dialog_; - - DISALLOW_COPY_AND_ASSIGN(ManagementUninstallFunctionUninstallDialogDelegate); }; void OnGenerateAppForLinkCompleted( @@ -230,6 +238,10 @@ void OnGenerateAppForLinkCompleted( class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { public: ChromeAppForLinkDelegate() {} + + ChromeAppForLinkDelegate(const ChromeAppForLinkDelegate&) = delete; + ChromeAppForLinkDelegate& operator=(const ChromeAppForLinkDelegate&) = delete; + ~ChromeAppForLinkDelegate() override {} void OnFaviconForApp( @@ -238,23 +250,33 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { const std::string& title, const GURL& launch_url, const favicon_base::FaviconImageResult& image_result) { +#if BUILDFLAG(IS_CHROMEOS_ASH) + // Avoid accessing the WebAppProvider when web apps are enabled in Lacros + // (and thus disabled in Ash). + if (base::FeatureList::IsEnabled(features::kWebAppsCrosapi)) { + function->FinishCreateWebApp(std::string(), + /*install_success=*/false); + return; + } +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->title = base::UTF8ToUTF16(title); web_app_info->start_url = launch_url; web_app_info->display_mode = web_app::DisplayMode::kBrowser; - web_app_info->open_as_window = false; + web_app_info->user_display_mode = blink::mojom::DisplayMode::kBrowser; if (!image_result.image.IsEmpty()) { web_app_info->icon_bitmaps.any[image_result.image.Width()] = image_result.image.AsBitmap(); } - auto* provider = - web_app::WebAppProvider::Get(Profile::FromBrowserContext(context)); - DCHECK(provider); + auto* provider = web_app::WebAppProvider::GetForWebApps( + Profile::FromBrowserContext(context)); provider->install_manager().InstallWebAppFromInfo( - std::move(web_app_info), web_app::ForInstallableSite::kNo, + std::move(web_app_info), /*overwrite_existing_manifest_fields=*/false, + web_app::ForInstallableSite::kNo, webapps::WebappInstallSource::MANAGEMENT_API, base::BindOnce(OnGenerateAppForLinkCompleted, base::RetainedRef(function))); @@ -263,8 +285,8 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { extensions::api::management::ExtensionInfo CreateExtensionInfoFromWebApp( const std::string& app_id, content::BrowserContext* context) override { - auto* provider = - web_app::WebAppProvider::Get(Profile::FromBrowserContext(context)); + auto* provider = web_app::WebAppProvider::GetForWebApps( + Profile::FromBrowserContext(context)); DCHECK(provider); const web_app::WebAppRegistrar& registrar = provider->registrar(); @@ -281,10 +303,10 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { info.icons = std::make_unique<std::vector<extensions::api::management::IconInfo>>(); - std::vector<WebApplicationIconInfo> icon_infos = + std::vector<apps::IconInfo> manifest_icons = registrar.GetAppIconInfos(app_id); - info.icons->reserve(icon_infos.size()); - for (const WebApplicationIconInfo& web_app_icon_info : icon_infos) { + info.icons->reserve(manifest_icons.size()); + for (const apps::IconInfo& web_app_icon_info : manifest_icons) { extensions::api::management::IconInfo icon_info; if (web_app_icon_info.square_size_px) icon_info.size = *web_app_icon_info.square_size_px; @@ -319,9 +341,6 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { // Used for favicon loading tasks. base::CancelableTaskTracker cancelable_task_tracker_; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeAppForLinkDelegate); }; void LaunchWebApp(const web_app::AppId& app_id, Profile* profile) { @@ -329,7 +348,7 @@ void LaunchWebApp(const web_app::AppId& app_id, Profile* profile) { // preference, the default launch value will be returned. // TODO(crbug.com/1003602): Make AppLaunchParams launch container Optional or // add a "default" launch container enum value. - auto* provider = web_app::WebAppProvider::Get(profile); + auto* provider = web_app::WebAppProvider::GetForWebApps(profile); DCHECK(provider); blink::mojom::DisplayMode display_mode = provider->registrar().GetAppUserDisplayMode(app_id); @@ -531,8 +550,17 @@ void ChromeManagementAPIDelegate::InstallOrLaunchReplacementWebApp( content::BrowserContext* context, const GURL& web_app_url, InstallOrLaunchWebAppCallback callback) const { +#if BUILDFLAG(IS_CHROMEOS_ASH) + // Avoid accessing the WebAppProvider when web apps are enabled in Lacros (and + // thus disabled in Ash). + if (base::FeatureList::IsEnabled(features::kWebAppsCrosapi)) { + std::move(callback).Run(InstallOrLaunchWebAppResult::kUnknownError); + return; + } +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + Profile* profile = Profile::FromBrowserContext(context); - auto* provider = web_app::WebAppProvider::Get(profile); + auto* provider = web_app::WebAppProvider::GetForWebApps(profile); DCHECK(provider); // Launch the app if web_app_url happens to match start_url. If not, the app diff --git a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc index 7cd11d68c5e..e84d3f86d67 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc @@ -27,6 +27,7 @@ #include "extensions/browser/api/management/management_api_constants.h" #include "extensions/browser/extension_dialog_auto_confirm.h" #include "extensions/browser/extension_host.h" +#include "extensions/browser/extension_host_test_helper.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" @@ -44,7 +45,9 @@ namespace extensions { class ExtensionManagementApiBrowserTest : public ExtensionBrowserTest { public: - ExtensionManagementApiBrowserTest() = default; + explicit ExtensionManagementApiBrowserTest( + ContextType context_type = ContextType::kNone) + : ExtensionBrowserTest(context_type) {} ~ExtensionManagementApiBrowserTest() override = default; ExtensionManagementApiBrowserTest(const ExtensionManagementApiBrowserTest&) = delete; @@ -72,18 +75,13 @@ class ExtensionManagementApiTestWithBackgroundType : public ExtensionManagementApiBrowserTest, public testing::WithParamInterface<ContextType> { public: - ExtensionManagementApiTestWithBackgroundType() = default; + ExtensionManagementApiTestWithBackgroundType() + : ExtensionManagementApiBrowserTest(GetParam()) {} ~ExtensionManagementApiTestWithBackgroundType() override = default; ExtensionManagementApiTestWithBackgroundType( const ExtensionManagementApiTestWithBackgroundType&) = delete; ExtensionManagementApiTestWithBackgroundType& operator=( const ExtensionManagementApiTestWithBackgroundType&) = delete; - - protected: - const Extension* LoadExtensionWithParamOptions(const base::FilePath& path) { - return LoadExtension(path, {.load_as_service_worker = - GetParam() == ContextType::kServiceWorker}); - } }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -99,13 +97,14 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, InstallEvent) { ExtensionTestMessageListener listener1("ready", false); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("management/install_event"))); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/install_event"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); ExtensionTestMessageListener listener2("got_event", false); ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("api_test/management/enabled_extension"))); + test_data_dir_.AppendASCII("api_test/management/enabled_extension"), + {.context_type = ContextType::kFromManifest})); ASSERT_TRUE(listener2.WaitUntilSatisfied()); } @@ -113,12 +112,14 @@ IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, LaunchApp) { ExtensionTestMessageListener listener1("app_launched", false); ExtensionTestMessageListener listener2("got_expected_error", false); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("management/simple_extension"))); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("management/packaged_app"))); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("management/launch_app"))); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/simple_extension"), + {.context_type = ContextType::kFromManifest})); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/packaged_app"), + {.context_type = ContextType::kFromManifest})); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/launch_app"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); ASSERT_TRUE(listener2.WaitUntilSatisfied()); } @@ -135,9 +136,10 @@ IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, ExtensionTestMessageListener app_launched_listener("app_launched", false); ASSERT_TRUE( - LoadExtension(test_data_dir_.AppendASCII("management/packaged_app"))); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("management/launch_app"))); + LoadExtension(test_data_dir_.AppendASCII("management/packaged_app"), + {.context_type = ContextType::kFromManifest})); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/launch_app"))); ASSERT_TRUE(app_launched_listener.WaitUntilSatisfied()); // Should still see 0 apps launched from the API in the histogram. @@ -156,9 +158,10 @@ IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, ExtensionTestMessageListener app_launched_listener("app_launched", false); ASSERT_TRUE( - LoadExtension(test_data_dir_.AppendASCII("management/packaged_app"))); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("management/launch_app"))); + LoadExtension(test_data_dir_.AppendASCII("management/packaged_app"), + {.context_type = ContextType::kFromManifest})); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/launch_app"))); ASSERT_TRUE(app_launched_listener.WaitUntilSatisfied()); // Should see 1 app launched from the highlights app in the histogram. @@ -172,9 +175,10 @@ IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, LaunchAppFromBackground) { ExtensionTestMessageListener listener1("success", false); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/packaged_app"), + {.context_type = ContextType::kFromManifest})); ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("management/packaged_app"))); - ASSERT_TRUE(LoadExtensionWithParamOptions( test_data_dir_.AppendASCII("management/launch_app_from_background"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); } @@ -185,12 +189,12 @@ IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, // extension. This ensures that the onUninstall event listener is // added before we proceed to the uninstall step. ExtensionTestMessageListener listener1("ready", false); - ASSERT_TRUE(LoadExtensionWithParamOptions( + ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/self_uninstall_helper"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); ExtensionTestMessageListener listener2("success", false); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("management/self_uninstall"))); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("management/self_uninstall"))); ASSERT_TRUE(listener2.WaitUntilSatisfied()); } @@ -200,11 +204,11 @@ IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, // extension. This ensures that the onUninstall event listener is // added before we proceed to the uninstall step. ExtensionTestMessageListener listener1("ready", false); - ASSERT_TRUE(LoadExtensionWithParamOptions( + ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/self_uninstall_helper"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); ExtensionTestMessageListener listener2("success", false); - ASSERT_TRUE(LoadExtensionWithParamOptions( + ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("management/self_uninstall_noperm"))); ASSERT_TRUE(listener2.WaitUntilSatisfied()); } @@ -212,17 +216,16 @@ IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, Get) { ExtensionTestMessageListener listener("success", false); ASSERT_TRUE( - LoadExtension(test_data_dir_.AppendASCII("management/simple_extension"))); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("management/get"))); + LoadExtension(test_data_dir_.AppendASCII("management/simple_extension"), + {.context_type = ContextType::kFromManifest})); + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("management/get"))); ASSERT_TRUE(listener.WaitUntilSatisfied()); } IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithBackgroundType, GetSelfNoPermissions) { ExtensionTestMessageListener listener1("success", false); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("management/get_self"))); + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("management/get_self"))); ASSERT_TRUE(listener1.WaitUntilSatisfied()); } @@ -268,9 +271,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, std::unique_ptr<base::Value> result( test_utils::RunFunctionAndReturnSingleResult(function.get(), "[]", browser())); - base::ListValue* list; - ASSERT_TRUE(result->GetAsList(&list)); - EXPECT_EQ(1U, list->GetSize()); + ASSERT_TRUE(result->is_list()); + EXPECT_EQ(1U, result->GetList().size()); // And it should continue to do so even after it crashes. ASSERT_TRUE(CrashEnabledExtension(extension->id())); @@ -278,8 +280,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiBrowserTest, function = new ManagementGetAllFunction(); result.reset(test_utils::RunFunctionAndReturnSingleResult(function.get(), "[]", browser())); - ASSERT_TRUE(result->GetAsList(&list)); - EXPECT_EQ(1U, list->GetSize()); + ASSERT_TRUE(result->is_list()); + EXPECT_EQ(1U, result->GetList().size()); } class ExtensionManagementApiEscalationTest : @@ -378,17 +380,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest, } { - // This should succeed when user accepts dialog. We must wait for the - // process to connect *and* for the channel to finish initializing before - // trying to crash it. (NOTIFICATION_RENDERER_PROCESS_CREATED does not wait - // for the latter and can cause KillProcess to fail on Windows.) - content::WindowedNotificationObserver observer( - extensions::NOTIFICATION_EXTENSION_HOST_CREATED, - content::NotificationService::AllSources()); + // The extension should load when the user accepts the dialog, triggering + // a new ExtensionHost creation. + ExtensionHostTestHelper host_helper(profile(), kId); ScopedTestDialogAutoConfirm auto_confirm( ScopedTestDialogAutoConfirm::ACCEPT); SetEnabled(true, true, std::string(), source_extension); - observer.Wait(); + host_helper.WaitForRenderProcessReady(); } { diff --git a/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc index 63470ace29b..5fd87b7be9d 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_non_persistent_apitest.cc @@ -25,19 +25,12 @@ class ManagementApiNonPersistentApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - ManagementApiNonPersistentApiTest() = default; + ManagementApiNonPersistentApiTest() : ExtensionApiTest(GetParam()) {} ~ManagementApiNonPersistentApiTest() override = default; ManagementApiNonPersistentApiTest(const ManagementApiNonPersistentApiTest&) = delete; ManagementApiNonPersistentApiTest& operator=( const ManagementApiNonPersistentApiTest&) = delete; - - protected: - const Extension* LoadNonPersistentExtension(const char* relative_path) { - return LoadExtension( - test_data_dir_.AppendASCII(relative_path), - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; // Tests chrome.management.uninstallSelf API. @@ -81,7 +74,8 @@ IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, UninstallSelf) { // uninstalls itself, so the ExtensionHost never fully finishes loading. Since // we wait for the uninstall explicitly, this isn't racy. scoped_refptr<const Extension> extension = - LoadExtension(path, {.wait_for_renderers = false}); + LoadExtension(path, {.wait_for_renderers = false, + .context_type = ContextType::kFromManifest}); EXPECT_EQ(extension, observer.WaitForExtensionUninstalled()); } @@ -90,8 +84,8 @@ IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, UninstallSelf) { // (i.e. browserAction.onClicked event). IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, UninstallViaBrowserAction) { - const Extension* extension_b = LoadNonPersistentExtension( - "management/uninstall_via_browser_action/extension_b"); + const Extension* extension_b = LoadExtension(test_data_dir_.AppendASCII( + "management/uninstall_via_browser_action/extension_b")); ASSERT_TRUE(extension_b); const ExtensionId extension_b_id = extension_b->id(); @@ -107,8 +101,8 @@ IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, // Load extension_a and wait for browserAction.onClicked listener // registration. ExtensionTestMessageListener listener_added("ready", false); - const Extension* extension_a = LoadNonPersistentExtension( - "management/uninstall_via_browser_action/extension_a"); + const Extension* extension_a = LoadExtension(test_data_dir_.AppendASCII( + "management/uninstall_via_browser_action/extension_a")); ASSERT_TRUE(extension_a); EXPECT_TRUE(listener_added.WaitUntilSatisfied()); diff --git a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc index 5d1e54f8718..33d5f37833b 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc @@ -27,7 +27,6 @@ #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" -#include "extensions/browser/extension_util.h" #include "extensions/browser/management_policy.h" #include "extensions/browser/test_management_policy.h" #include "extensions/common/api/management.h" @@ -73,6 +72,10 @@ namespace constants = extension_management_api_constants; // TODO(devlin): Unittests are awesome. Test more with unittests and less with // heavy api/browser tests. class ManagementApiUnitTest : public ExtensionServiceTestWithInstall { + public: + ManagementApiUnitTest(const ManagementApiUnitTest&) = delete; + ManagementApiUnitTest& operator=(const ManagementApiUnitTest&) = delete; + protected: ManagementApiUnitTest() {} ~ManagementApiUnitTest() override {} @@ -92,19 +95,6 @@ class ManagementApiUnitTest : public ExtensionServiceTestWithInstall { Browser* browser() { return browser_.get(); } - scoped_refptr<const Extension> AddExtension() { - scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); - service()->AddExtension(extension.get()); - // TODO(crbug.com/1182630): Make sure the storage partition is finished - // initializing before uninstall. This can be removed once crbug.com/1182630 - // is fixed. - extensions::util::GetStoragePartitionForExtensionId(extension->id(), - profile(), - /*can_create=*/true); - task_environment()->RunUntilIdle(); - return extension; - } - // Returns the initialization parameters for the extension service. virtual ExtensionServiceInitParams GetExtensionServiceInitParams() { return CreateDefaultInitParams(); @@ -118,8 +108,6 @@ class ManagementApiUnitTest : public ExtensionServiceTestWithInstall { // The browser (and accompanying window). std::unique_ptr<TestBrowserWindow> browser_window_; std::unique_ptr<Browser> browser_; - - DISALLOW_COPY_AND_ASSIGN(ManagementApiUnitTest); }; bool ManagementApiUnitTest::RunFunction( @@ -181,7 +169,8 @@ void ManagementApiUnitTest::TearDown() { // Test the basic parts of management.setEnabled. TEST_F(ManagementApiUnitTest, ManagementSetEnabled) { - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); scoped_refptr<const Extension> source_extension = ExtensionBuilder("Test").Build(); service()->AddExtension(source_extension.get()); @@ -334,7 +323,8 @@ TEST_F(ManagementApiUnitTest, ComponentPolicyEnabling) { // Tests management.uninstall. TEST_F(ManagementApiUnitTest, ManagementUninstall) { - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); std::string extension_id = extension->id(); base::Value uninstall_args(base::Value::Type::LIST); @@ -411,7 +401,8 @@ TEST_F(ManagementApiUnitTest, ManagementUninstall) { TEST_F(ManagementApiUnitTest, ManagementWebStoreUninstall) { scoped_refptr<const Extension> triggering_extension = ExtensionBuilder("Test").SetID(extensions::kWebStoreAppId).Build(); - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); std::string extension_id = extension->id(); base::Value uninstall_args(base::Value::Type::LIST); uninstall_args.Append(extension->id()); @@ -465,7 +456,8 @@ TEST_F(ManagementApiUnitTest, ManagementWebStoreUninstall) { TEST_F(ManagementApiUnitTest, ManagementProgrammaticUninstall) { scoped_refptr<const Extension> triggering_extension = ExtensionBuilder("Triggering Extension").SetID("123").Build(); - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); std::string extension_id = extension->id(); base::Value uninstall_args(base::Value::Type::LIST); uninstall_args.Append(extension->id()); @@ -499,7 +491,8 @@ TEST_F(ManagementApiUnitTest, ManagementProgrammaticUninstall) { } // Tests uninstalling a blocklisted extension via management.uninstall. TEST_F(ManagementApiUnitTest, ManagementUninstallBlocklisted) { - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); std::string id = extension->id(); service()->BlocklistExtensionForTest(id); @@ -516,7 +509,8 @@ TEST_F(ManagementApiUnitTest, ManagementUninstallBlocklisted) { } TEST_F(ManagementApiUnitTest, ManagementEnableOrDisableBlocklisted) { - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); std::string id = extension->id(); service()->BlocklistExtensionForTest(id); @@ -551,7 +545,8 @@ TEST_F(ManagementApiUnitTest, ManagementEnableOrDisableBlocklisted) { TEST_F(ManagementApiUnitTest, ExtensionInfo_MayEnable) { using ExtensionInfo = api::management::ExtensionInfo; - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); const std::string args = base::StringPrintf("[\"%s\"]", extension->id().c_str()); @@ -622,7 +617,8 @@ TEST_F(ManagementApiUnitTest, ExtensionInfo_MayEnable) { TEST_F(ManagementApiUnitTest, ExtensionInfo_MayDisable) { using ExtensionInfo = api::management::ExtensionInfo; - scoped_refptr<const Extension> extension = AddExtension(); + scoped_refptr<const Extension> extension = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension.get()); const std::string args = base::StringPrintf("[\"%s\"]", extension->id().c_str()); @@ -1433,7 +1429,8 @@ class ManagementApiSupervisedUserTestWithSetup management_api_->set_delegate_for_test(base::WrapUnique(delegate_)); // Add a generic extension. - extension_ = AddExtension(); + extension_ = ExtensionBuilder("Test").Build(); + service()->AddExtension(extension_.get()); EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_->id())); } diff --git a/chromium/chrome/browser/extensions/api/management/management_apitest.cc b/chromium/chrome/browser/extensions/api/management/management_apitest.cc index 0f6fc10c564..c26235e65f8 100644 --- a/chromium/chrome/browser/extensions/api/management/management_apitest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_apitest.cc @@ -5,7 +5,9 @@ #include <map> #include "base/strings/stringprintf.h" +#include "base/test/scoped_feature_list.h" #include "build/build_config.h" +#include "build/chromeos_buildflags.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/launch_util.h" @@ -16,11 +18,12 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/web_applications/components/web_app_helpers.h" #include "chrome/browser/web_applications/os_integration_manager.h" -#include "chrome/browser/web_applications/test/test_web_app_ui_manager.h" +#include "chrome/browser/web_applications/test/fake_web_app_ui_manager.h" +#include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/browser/web_applications/web_app_provider.h" #include "chrome/browser/web_applications/web_app_registrar.h" +#include "chrome/common/chrome_features.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_constants.h" #include "content/public/test/browser_test.h" @@ -55,9 +58,20 @@ Browser* FindOtherBrowser(Browser* browser) { } // namespace -class ExtensionManagementApiTest : public extensions::ExtensionApiTest { +using ContextType = extensions::ExtensionBrowserTest::ContextType; + +class ExtensionManagementApiTest + : public extensions::ExtensionApiTest, + public testing::WithParamInterface<ContextType> { public: - virtual void LoadExtensions() { + ExtensionManagementApiTest() : ExtensionApiTest(GetParam()) {} + ~ExtensionManagementApiTest() override = default; + ExtensionManagementApiTest& operator=(const ExtensionManagementApiTest&) = + delete; + ExtensionManagementApiTest(const ExtensionManagementApiTest&) = delete; + + protected: + void LoadExtensions() { base::FilePath basedir = test_data_dir_.AppendASCII("management"); // Load 5 enabled items. @@ -79,7 +93,8 @@ class ExtensionManagementApiTest : public extensions::ExtensionApiTest { void LoadAndWaitForLaunch(const std::string& app_path, std::string* out_app_id) { ExtensionTestMessageListener launched_app("launched app", false); - ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(app_path))); + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(app_path), + {.context_type = ContextType::kFromManifest})); if (out_app_id) *out_app_id = last_loaded_extension_id(); @@ -87,10 +102,10 @@ class ExtensionManagementApiTest : public extensions::ExtensionApiTest { ASSERT_TRUE(launched_app.WaitUntilSatisfied()); } - protected: void LoadNamedExtension(const base::FilePath& path, const std::string& name) { - const Extension* extension = LoadExtension(path.AppendASCII(name)); + const Extension* extension = LoadExtension( + path.AppendASCII(name), {.context_type = ContextType::kFromManifest}); ASSERT_TRUE(extension); extension_ids_[name] = extension->id(); } @@ -104,11 +119,42 @@ class ExtensionManagementApiTest : public extensions::ExtensionApiTest { extension_ids_[name] = extension->id(); } + using ScopedUserGestureForTests = + ExtensionFunction::ScopedUserGestureForTests; + + void MaybeCreateScopedUserGesture() { + // TODO(crbug.com/977629): Support for chrome.test.runWithUserGesture for + // service worker-based extensions is not implemented. For now, work around + // it by simulating a user gesture for the entire test. + if (GetParam() == ContextType::kServiceWorker) + scoped_user_gesture_ = std::make_unique<ScopedUserGestureForTests>(); + } + // Maps installed extension names to their IDs. std::map<std::string, std::string> extension_ids_; + + private: + std::unique_ptr<ScopedUserGestureForTests> scoped_user_gesture_; }; -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, Basics) { +INSTANTIATE_TEST_SUITE_P(PersistentBackground, + ExtensionManagementApiTest, + ::testing::Values(ContextType::kPersistentBackground)); +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + ExtensionManagementApiTest, + ::testing::Values(ContextType::kServiceWorker)); + +// TODO(crbug.com/977629): Support for chrome.test.runWithUserGesture for +// service worker-based extensions is not implemented. For now, don't run +// those tests, since they mix subtests where user gestures are present and +// missing. +using ExtensionManagementApiTestWithUserGesture = ExtensionManagementApiTest; + +INSTANTIATE_TEST_SUITE_P(PersistentBackground, + ExtensionManagementApiTestWithUserGesture, + ::testing::Values(ContextType::kPersistentBackground)); + +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTest, Basics) { LoadExtensions(); base::FilePath basedir = test_data_dir_.AppendASCII("management"); @@ -120,39 +166,63 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, Basics) { ManifestLocation::kExternalPolicyDownload); InstallNamedExtension(basedir, "version_name", ManifestLocation::kInternal); - ASSERT_TRUE(RunExtensionTest("management/test", {.page_url = "basics.html"})); + ASSERT_TRUE(RunExtensionTest("management/basics")); } -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, NoPermission) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTest, NoPermission) { LoadExtensions(); - ASSERT_TRUE( - RunExtensionTest("management/no_permission", {.page_url = "test.html"})); + ASSERT_TRUE(RunExtensionTest("management/no_permission")); } -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, Uninstall) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithUserGesture, Uninstall) { LoadExtensions(); // Confirmation dialog will be shown for uninstallations except for self. extensions::ScopedTestDialogAutoConfirm auto_confirm( extensions::ScopedTestDialogAutoConfirm::ACCEPT); - ASSERT_TRUE( - RunExtensionTest("management/test", {.page_url = "uninstall.html"})); + ASSERT_TRUE(RunExtensionTest("management/uninstall")); } -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, CreateAppShortcut) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithUserGesture, + CreateAppShortcut) { LoadExtensions(); base::FilePath basedir = test_data_dir_.AppendASCII("management"); LoadNamedExtension(basedir, "packaged_app"); extensions::ManagementCreateAppShortcutFunction::SetAutoConfirmForTest(true); - ASSERT_TRUE(RunExtensionTest("management/test", - {.page_url = "createAppShortcut.html"})); + ASSERT_TRUE(RunExtensionTest("management/create_app_shortcut")); } -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, GenerateAppForLink) { - ASSERT_TRUE(RunExtensionTest("management/test", - {.page_url = "generateAppForLink.html"})); +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithUserGesture, + GenerateAppForLink) { + ASSERT_TRUE(RunExtensionTest("management/generate_app_for_link")); } +#if BUILDFLAG(IS_CHROMEOS_ASH) +class GenerateAppForLinkWithLacrosWebAppsApiTest + : public ExtensionManagementApiTest { + public: + GenerateAppForLinkWithLacrosWebAppsApiTest() { + features_.InitAndEnableFeature(features::kWebAppsCrosapi); + } + + private: + base::test::ScopedFeatureList features_; +}; + +INSTANTIATE_TEST_SUITE_P(PersistentBackground, + GenerateAppForLinkWithLacrosWebAppsApiTest, + ::testing::Values(ContextType::kPersistentBackground)); +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + GenerateAppForLinkWithLacrosWebAppsApiTest, + ::testing::Values(ContextType::kServiceWorker)); + +IN_PROC_BROWSER_TEST_P(GenerateAppForLinkWithLacrosWebAppsApiTest, + GenerateAppForLink) { + MaybeCreateScopedUserGesture(); + ASSERT_TRUE(RunExtensionTest("management/generate_app_for_link_lacros")); +} +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + class InstallReplacementWebAppApiTest : public ExtensionManagementApiTest { public: InstallReplacementWebAppApiTest() @@ -209,7 +279,7 @@ class InstallReplacementWebAppApiTest : public ExtensionManagementApiTest { const GURL start_url = https_test_server_.GetURL(web_app_start_url); web_app::AppId web_app_id = web_app::GenerateAppId(/*manifest_id=*/absl::nullopt, start_url); - auto* provider = web_app::WebAppProvider::Get(browser()->profile()); + auto* provider = web_app::WebAppProvider::GetForTest(browser()->profile()); EXPECT_FALSE(provider->registrar().IsLocallyInstalled(start_url)); EXPECT_EQ(0, static_cast<int>( provider->ui_manager().GetNumWindowsForApp(web_app_id))); @@ -233,12 +303,22 @@ class InstallReplacementWebAppApiTest : public ExtensionManagementApiTest { net::EmbeddedTestServer https_test_server_; }; +INSTANTIATE_TEST_SUITE_P(PersistentBackground, + InstallReplacementWebAppApiTest, + ::testing::Values(ContextType::kPersistentBackground)); +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + InstallReplacementWebAppApiTest, + ::testing::Values(ContextType::kServiceWorker)); + const char InstallReplacementWebAppApiTest::kManifest[] = R"({ "name": "Management API Test", "version": "0.1", "manifest_version": 2, - "background": { "scripts": ["background.js"] }, + "background": { + "scripts": ["background.js"], + "persistent": true + }, "replacement_web_app": "%s" })"; @@ -253,7 +333,7 @@ const char InstallReplacementWebAppApiTest::kAppManifest[] = "replacement_web_app": "%s" })"; -IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotWebstore) { +IN_PROC_BROWSER_TEST_P(InstallReplacementWebAppApiTest, NotWebstore) { static constexpr char kBackground[] = R"( chrome.management.installReplacementWebApp(function() { chrome.test.assertLastError( @@ -267,7 +347,7 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotWebstore) { kBackground, false /* from_webstore */); } -IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NoGesture) { +IN_PROC_BROWSER_TEST_P(InstallReplacementWebAppApiTest, NoGesture) { static constexpr char kBackground[] = R"( chrome.management.installReplacementWebApp(function() { chrome.test.assertLastError( @@ -281,7 +361,7 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NoGesture) { kBackground, true /* from_webstore */); } -IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotInstallableWebApp) { +IN_PROC_BROWSER_TEST_P(InstallReplacementWebAppApiTest, NotInstallableWebApp) { static constexpr char kBackground[] = R"(chrome.test.runWithUserGesture(function() { chrome.management.installReplacementWebApp(function() { @@ -296,16 +376,52 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, NotInstallableWebApp) { kBackground, true /* from_webstore */); } -IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, InstallableWebApp) { +IN_PROC_BROWSER_TEST_P(InstallReplacementWebAppApiTest, InstallableWebApp) { static constexpr char kGoodWebAppURL[] = "/management/install_replacement_web_app/acceptable_web_app/index.html"; RunInstallableWebAppTest(kManifest, kGoodWebAppURL, kGoodWebAppURL); } +#if BUILDFLAG(IS_CHROMEOS_ASH) +class InstallReplacementWebAppWithLacrosWebAppsApiTest + : public InstallReplacementWebAppApiTest { + public: + InstallReplacementWebAppWithLacrosWebAppsApiTest() { + features_.InitAndEnableFeature(features::kWebAppsCrosapi); + } + + private: + base::test::ScopedFeatureList features_; +}; + +INSTANTIATE_TEST_SUITE_P(PersistentBackground, + InstallReplacementWebAppWithLacrosWebAppsApiTest, + ::testing::Values(ContextType::kPersistentBackground)); +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + InstallReplacementWebAppWithLacrosWebAppsApiTest, + ::testing::Values(ContextType::kServiceWorker)); + +IN_PROC_BROWSER_TEST_P(InstallReplacementWebAppWithLacrosWebAppsApiTest, + InstallableWebApp) { + static constexpr char kGoodWebAppURL[] = + "/management/install_replacement_web_app/acceptable_web_app/index.html"; + static constexpr char kBackground[] = + R"(chrome.test.runWithUserGesture(function() { + chrome.management.installReplacementWebApp(function() { + chrome.test.assertLastError( + 'Web apps can\'t be installed in the current user profile.'); + chrome.test.notifyPass(); + }); + });)"; + + RunTest(kManifest, kGoodWebAppURL, kBackground, true /* from_webstore */); +} +#endif // BUILDFLAG(IS_CHROMEOS_ASH) + // Check that web app still installs and launches correctly when start_url does // not match replacement_web_app_url. -IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, +IN_PROC_BROWSER_TEST_P(InstallReplacementWebAppApiTest, InstallableWebAppWithStartUrl) { static constexpr char kGoodWebAppUrl[] = "/management/install_replacement_web_app/" @@ -319,7 +435,7 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, RunInstallableWebAppTest(kManifest, kGoodWebAppUrl, kGoodWebAppStartUrl); } -IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, +IN_PROC_BROWSER_TEST_P(InstallReplacementWebAppApiTest, InstallableWebAppInPlatformApp) { static constexpr char kGoodWebAppURL[] = "/management/install_replacement_web_app/acceptable_web_app/index.html"; @@ -328,8 +444,9 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, } // Tests actions on extensions when no management policy is in place. -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, ManagementPolicyAllowed) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTest, ManagementPolicyAllowed) { LoadExtensions(); + MaybeCreateScopedUserGesture(); extensions::ScopedTestDialogAutoConfirm auto_confirm( extensions::ScopedTestDialogAutoConfirm::ACCEPT); extensions::ExtensionRegistry* registry = @@ -342,7 +459,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, ManagementPolicyAllowed) { browser()->profile())->management_policy()->UnregisterAllProviders(); ASSERT_TRUE(RunExtensionTest("management/management_policy", - {.page_url = "allowed.html"})); + {.custom_arg = "runAllowedTests"})); // The last thing the test does is uninstall the "enabled_extension". EXPECT_FALSE( registry->GetExtensionById(extension_ids_["enabled_extension"], @@ -350,7 +467,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, ManagementPolicyAllowed) { } // Tests actions on extensions when management policy prohibits those actions. -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, ManagementPolicyProhibited) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTest, ManagementPolicyProhibited) { LoadExtensions(); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get(browser()->profile()); @@ -367,10 +484,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, ManagementPolicyProhibited) { extensions::TestManagementPolicyProvider::MUST_REMAIN_INSTALLED); policy->RegisterProvider(&provider); ASSERT_TRUE(RunExtensionTest("management/management_policy", - {.page_url = "prohibited.html"})); + {.custom_arg = "runProhibitedTests"})); } -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTest, LaunchPanelApp) { // Load an extension that calls launchApp() on any app that gets // installed. ExtensionTestMessageListener launcher_loaded("launcher loaded", false); @@ -419,7 +536,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { ASSERT_TRUE(app_browser->is_type_app()); } -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchTabApp) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTest, LaunchTabApp) { // Load an extension that calls launchApp() on any app that gets // installed. ExtensionTestMessageListener launcher_loaded("launcher loaded", false); @@ -473,11 +590,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchTabApp) { #else #define MAYBE_LaunchType LaunchType #endif -IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchType) { +IN_PROC_BROWSER_TEST_P(ExtensionManagementApiTestWithUserGesture, + MAYBE_LaunchType) { LoadExtensions(); base::FilePath basedir = test_data_dir_.AppendASCII("management"); LoadNamedExtension(basedir, "packaged_app"); - ASSERT_TRUE( - RunExtensionTest("management/test", {.page_url = "launchType.html"})); + ASSERT_TRUE(RunExtensionTest("management/launch_type")); } diff --git a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc index 5fcf4485899..13e99958cf2 100644 --- a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc @@ -10,7 +10,6 @@ #include "base/files/file_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" -#include "base/scoped_observation.h" #include "base/strings/strcat.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" @@ -38,15 +37,15 @@ #include "content/public/test/test_utils.h" #include "content/public/test/url_loader_interceptor.h" #include "extensions/browser/extension_host.h" -#include "extensions/browser/extension_host_observer.h" +#include "extensions/browser/extension_host_test_helper.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/notification_types.h" #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/browser/updater/extension_downloader.h" +#include "extensions/common/mojom/view_type.mojom.h" #include "extensions/test/extension_test_message_listener.h" -#include "extensions/test/test_background_page_first_load_observer.h" #include "testing/gmock/include/gmock/gmock.h" using content::BrowserThread; @@ -66,50 +65,6 @@ std::string BuildForceInstallPolicyValue(const char* extension_id, return base::StringPrintf("%s;%s", extension_id, update_url); } -// Observes destruction of an extension's ExtensionHost if it is currently -// there. -class ExtensionHostDestructionObserver - : public extensions::ExtensionHostObserver { - public: - ExtensionHostDestructionObserver(Profile* profile, - const extensions::ExtensionId& extension_id) - : profile_(profile), - extension_id_(extension_id), - host_(extensions::ProcessManager::Get(profile) - ->GetBackgroundHostForExtension(extension_id_)) { - DCHECK(host_); - extension_host_observation_.Observe(host_); - } - - void WaitForDestructionThenWaitForFirstLoad() { - run_loop_.Run(); - - extensions::TestBackgroundPageFirstLoadObserver first_load_observer( - profile_, extension_id_); - first_load_observer.Wait(); - } - - // ExtensionHostObserver: - void OnExtensionHostDestroyed(extensions::ExtensionHost* host) override { - if (host == host_) { - DCHECK(extension_host_observation_.IsObservingSource(host_)); - extension_host_observation_.Reset(); - run_loop_.Quit(); - } - } - - private: - Profile* const profile_ = nullptr; - const extensions::ExtensionId extension_id_; - extensions::ExtensionHost* const host_ = nullptr; - base::RunLoop run_loop_; - base::ScopedObservation<extensions::ExtensionHost, - extensions::ExtensionHostObserver> - extension_host_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(ExtensionHostDestructionObserver); -}; - } // namespace class ExtensionManagementTest : public extensions::ExtensionBrowserTest { @@ -250,8 +205,19 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { const extensions::ExtensionId extension_id = extension->id(); { - ExtensionHostDestructionObserver host_destruction_observer(profile(), - extension_id); + // Set up two observers: One to wait for the existing background page to be + // destroyed, and a second to wait for a new one to load. + extensions::ExtensionHost* background_host = + extensions::ProcessManager::Get(profile()) + ->GetBackgroundHostForExtension(extension_id); + ASSERT_TRUE(background_host); + extensions::ExtensionHostTestHelper destruction_observer(profile()); + destruction_observer.RestrictToHost(background_host); + + extensions::ExtensionHostTestHelper first_load_observer(profile(), + extension_id); + first_load_observer.RestrictToType( + extensions::mojom::ViewType::kExtensionBackgroundPage); // Install an extension with the same version. The previous install should // be overwritten. @@ -262,7 +228,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { // new one to load. // Note that this is needed to ensure that |IsExtensionAtVersion| below can // successfully execute JS, otherwise this test becomes flaky. - host_destruction_observer.WaitForDestructionThenWaitForFirstLoad(); + destruction_observer.WaitForHostDestroyed(); + first_load_observer.WaitForHostCompletedFirstLoad(); } base::FilePath new_path = extension->path(); diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_api.h b/chromium/chrome/browser/extensions/api/mdns/mdns_api.h index dbfe3b46e41..ce06e9bb8b1 100644 --- a/chromium/chrome/browser/extensions/api/mdns/mdns_api.h +++ b/chromium/chrome/browser/extensions/api/mdns/mdns_api.h @@ -34,6 +34,10 @@ class MDnsAPI : public BrowserContextKeyedAPI, public media_router::DnsSdRegistry::DnsSdObserver { public: explicit MDnsAPI(content::BrowserContext* context); + + MDnsAPI(const MDnsAPI&) = delete; + MDnsAPI& operator=(const MDnsAPI&) = delete; + ~MDnsAPI() override; static MDnsAPI* Get(content::BrowserContext* context); @@ -114,13 +118,14 @@ class MDnsAPI : public BrowserContextKeyedAPI, // Count of active listeners per service type, saved from the previous // invocation of UpdateMDnsListeners(). ServiceTypeCounts prev_service_counts_; - - DISALLOW_COPY_AND_ASSIGN(MDnsAPI); }; class MdnsForceDiscoveryFunction : public ExtensionFunction { public: MdnsForceDiscoveryFunction(); + MdnsForceDiscoveryFunction(const MdnsForceDiscoveryFunction&) = delete; + MdnsForceDiscoveryFunction& operator=(const MdnsForceDiscoveryFunction&) = + delete; protected: ~MdnsForceDiscoveryFunction() override; @@ -130,7 +135,6 @@ class MdnsForceDiscoveryFunction : public ExtensionFunction { ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("mdns.forceDiscovery", MDNS_FORCEDISCOVERY) - DISALLOW_COPY_AND_ASSIGN(MdnsForceDiscoveryFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc b/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc index e884e0786f2..d071b3b026b 100644 --- a/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/mdns/mdns_api_unittest.cc @@ -125,9 +125,9 @@ class EventServiceListSizeMatcher *listener << "event.event_arg is null when it shouldn't be"; return false; } - if (e.event_args->GetSize() != 1) { + if (e.event_args->GetList().size() != 1) { *listener << "event.event_arg.GetSize() should be 1 but is " - << e.event_args->GetSize(); + << e.event_args->GetList().size(); return false; } const base::ListValue* services = nullptr; @@ -140,9 +140,9 @@ class EventServiceListSizeMatcher *listener << "event's service list argument is not a ListValue"; return false; } - *listener << "number of services is " << services->GetSize(); + *listener << "number of services is " << services->GetList().size(); return static_cast<testing::Matcher<size_t>>(testing::Eq(expected_size_)) - .MatchAndExplain(services->GetSize(), listener); + .MatchAndExplain(services->GetList().size(), listener); } virtual void DescribeTo(::std::ostream* os) const { diff --git a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h index 9d00f311e49..30003a54563 100644 --- a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h +++ b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h @@ -15,6 +15,12 @@ class MediaPerceptionAPIDelegateChromeOS : public extensions::MediaPerceptionAPIDelegate { public: MediaPerceptionAPIDelegateChromeOS(); + + MediaPerceptionAPIDelegateChromeOS( + const MediaPerceptionAPIDelegateChromeOS&) = delete; + MediaPerceptionAPIDelegateChromeOS& operator=( + const MediaPerceptionAPIDelegateChromeOS&) = delete; + ~MediaPerceptionAPIDelegateChromeOS() override; // extensions::MediaPerceptionAPIDelegate: @@ -33,8 +39,6 @@ class MediaPerceptionAPIDelegateChromeOS private: MediaPerceptionRequestHandler handler_; - - DISALLOW_COPY_AND_ASSIGN(MediaPerceptionAPIDelegateChromeOS); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h index 83108e87d8e..b5942acb5ea 100644 --- a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h +++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.h @@ -13,6 +13,10 @@ namespace extensions { class ChromeMessagingDelegate : public MessagingDelegate { public: ChromeMessagingDelegate(); + + ChromeMessagingDelegate(const ChromeMessagingDelegate&) = delete; + ChromeMessagingDelegate& operator=(const ChromeMessagingDelegate&) = delete; + ~ChromeMessagingDelegate() override; // MessagingDelegate: @@ -45,9 +49,6 @@ class ChromeMessagingDelegate : public MessagingDelegate { content::WebContents* web_contents, const GURL& url, base::OnceCallback<void(bool)> callback) override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeMessagingDelegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h index 1fb358fb70b..3588f94ddcc 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.h @@ -42,6 +42,9 @@ namespace extensions { // thread. class NativeMessageProcessHost : public NativeMessageHost { public: + NativeMessageProcessHost(const NativeMessageProcessHost&) = delete; + NativeMessageProcessHost& operator=(const NativeMessageProcessHost&) = delete; + ~NativeMessageProcessHost() override; // Create using specified |launcher|. Used in tests. @@ -135,8 +138,6 @@ class NativeMessageProcessHost : public NativeMessageHost { scoped_refptr<base::SingleThreadTaskRunner> task_runner_; base::WeakPtrFactory<NativeMessageProcessHost> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(NativeMessageProcessHost); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc index da955a82d91..f8e6344e354 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host_unittest.cc @@ -353,7 +353,7 @@ TEST_F(NativeMessagingTest, MAYBE_ReconnectArgs) { const base::ListValue* args_value = nullptr; ASSERT_TRUE(last_message_parsed_->GetList("args", &args_value)); std::vector<base::CommandLine::StringType> args; - args.reserve(args_value->GetSize()); + args.reserve(args_value->GetList().size()); for (auto& arg : args_value->GetList()) { ASSERT_TRUE(arg.is_string()); #if defined(OS_WIN) diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc index 8ba63326f8e..1bc6c312299 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc @@ -26,6 +26,7 @@ #include "components/keep_alive_registry/keep_alive_types.h" #include "content/public/test/browser_test.h" #include "extensions/browser/process_manager.h" +#include "extensions/test/extension_background_page_waiter.h" #include "extensions/test/result_catcher.h" namespace extensions { @@ -35,7 +36,9 @@ using ContextType = ExtensionApiTest::ContextType; class NativeMessagingApiTestBase : public ExtensionApiTest { public: - NativeMessagingApiTestBase() = default; + explicit NativeMessagingApiTestBase( + ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) {} ~NativeMessagingApiTestBase() override = default; NativeMessagingApiTestBase(const NativeMessagingApiTestBase&) = delete; NativeMessagingApiTestBase& operator=(const NativeMessagingApiTestBase&) = @@ -48,7 +51,7 @@ class NativeMessagingApiTestBase : public ExtensionApiTest { class NativeMessagingApiTest : public NativeMessagingApiTestBase, public testing::WithParamInterface<ContextType> { public: - NativeMessagingApiTest() = default; + NativeMessagingApiTest() : NativeMessagingApiTestBase(GetParam()) {} ~NativeMessagingApiTest() override = default; NativeMessagingApiTest(const NativeMessagingApiTest&) = delete; NativeMessagingApiTest& operator=(const NativeMessagingApiTest&) = delete; @@ -58,9 +61,7 @@ class NativeMessagingApiTest : public NativeMessagingApiTestBase, if (GetParam() == ContextType::kPersistentBackground) return RunExtensionTest(extension_name); std::string lazy_exension_name = base::StrCat({extension_name, "/lazy"}); - return RunExtensionTest( - lazy_exension_name.c_str(), {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); + return RunExtensionTest(lazy_exension_name.c_str()); } }; @@ -99,40 +100,6 @@ IN_PROC_BROWSER_TEST_P(NativeMessagingApiTest, #if !BUILDFLAG(IS_CHROMEOS_ASH) && !BUILDFLAG(IS_CHROMEOS_LACROS) -class TestProcessManagerObserver : public ProcessManagerObserver { - public: - TestProcessManagerObserver() = default; - ~TestProcessManagerObserver() override = default; - - void WaitForProcessShutdown(ProcessManager* process_manager, - const std::string& extension_id) { - DCHECK(!quit_); - extension_id_ = extension_id; - base::RunLoop run_loop; - quit_ = run_loop.QuitClosure(); - - observation_.Observe(process_manager); - run_loop.Run(); - } - - private: - void OnBackgroundHostClose(const std::string& extension_id) override { - if (extension_id != extension_id_) { - return; - } - observation_.Reset(); - extension_id_.clear(); - std::move(quit_).Run(); - } - - std::string extension_id_; - base::ScopedObservation<ProcessManager, ProcessManagerObserver> observation_{ - this}; - base::OnceClosure quit_; - - DISALLOW_COPY_AND_ASSIGN(TestProcessManagerObserver); -}; - base::CommandLine CreateNativeMessagingConnectCommandLine( const std::string& connect_id, const std::string& extension_id = @@ -173,9 +140,8 @@ IN_PROC_BROWSER_TEST_F(NativeMessagingLaunchApiTest, MAYBE_Success) { auto* extension = LoadExtension(test_data_dir_.AppendASCII("native_messaging_launch")); - TestProcessManagerObserver observer; - observer.WaitForProcessShutdown(ProcessManager::Get(profile()), - extension->id()); + ExtensionBackgroundPageWaiter(profile(), *extension) + .WaitForBackgroundClosed(); ResultCatcher catcher; @@ -210,9 +176,8 @@ IN_PROC_BROWSER_TEST_F(NativeMessagingLaunchApiTest, UnsupportedByNativeHost) { auto* extension = LoadExtension( test_data_dir_.AppendASCII("native_messaging_launch_unsupported")); - TestProcessManagerObserver observer; - observer.WaitForProcessShutdown(ProcessManager::Get(profile()), - extension->id()); + ExtensionBackgroundPageWaiter(profile(), *extension) + .WaitForBackgroundClosed(); ResultCatcher catcher; @@ -240,6 +205,10 @@ class TestKeepAliveStateObserver : public KeepAliveStateObserver { public: TestKeepAliveStateObserver() = default; + TestKeepAliveStateObserver(const TestKeepAliveStateObserver&) = delete; + TestKeepAliveStateObserver& operator=(const TestKeepAliveStateObserver&) = + delete; + void WaitForNoKeepAlive() { ASSERT_TRUE(KeepAliveRegistry::GetInstance()->IsKeepingAlive()); base::ScopedObservation<KeepAliveRegistry, KeepAliveStateObserver> observer( @@ -251,7 +220,7 @@ class TestKeepAliveStateObserver : public KeepAliveStateObserver { // has been released; poll for changes instead. #if defined(OS_MAC) polling_timer_.Start( - FROM_HERE, base::TimeDelta::FromMilliseconds(100), + FROM_HERE, base::Milliseconds(100), base::BindRepeating(&TestKeepAliveStateObserver::PollKeepAlive, base::Unretained(this))); #endif @@ -281,14 +250,12 @@ class TestKeepAliveStateObserver : public KeepAliveStateObserver { #endif base::OnceClosure quit_; - - DISALLOW_COPY_AND_ASSIGN(TestKeepAliveStateObserver); }; IN_PROC_BROWSER_TEST_F(NativeMessagingLaunchApiTest, Error) { ASSERT_NO_FATAL_FAILURE(test_host_.RegisterTestHost(false)); ScopedNativeMessagingErrorTimeoutOverrideForTest error_timeout_override( - base::TimeDelta::FromSeconds(2)); + base::Seconds(2)); StartupBrowserCreator::ProcessCommandLineAlreadyRunning( CreateNativeMessagingConnectCommandLine("test-connect-id"), {}, profile()->GetPath()); diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h index d31c3db1f26..b8a73217071 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h @@ -24,6 +24,10 @@ class NativeMessagingHostManifest { HOST_INTERFACE_STDIO, }; + NativeMessagingHostManifest(const NativeMessagingHostManifest&) = delete; + NativeMessagingHostManifest& operator=(const NativeMessagingHostManifest&) = + delete; + ~NativeMessagingHostManifest(); // Verifies that the name is valid. Valid names must match regular expression @@ -57,8 +61,6 @@ class NativeMessagingHostManifest { base::FilePath path_; URLPatternSet allowed_origins_; bool supports_native_initiated_connections_ = false; - - DISALLOW_COPY_AND_ASSIGN(NativeMessagingHostManifest); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc index 342a7bfe44e..46d4cc91ab8 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_host_manifest_unittest.cc @@ -101,7 +101,7 @@ TEST_F(NativeMessagingHostManifestTest, LoadValid) { EXPECT_EQ(manifest->description(), "Native Messaging Test"); EXPECT_EQ(manifest->host_interface(), NativeMessagingHostManifest::HOST_INTERFACE_STDIO); - EXPECT_EQ(manifest->path(), base::FilePath::FromUTF8Unsafe(kTestHostPath)); + EXPECT_EQ(manifest->path(), base::FilePath::FromASCII(kTestHostPath)); EXPECT_TRUE(manifest->allowed_origins().MatchesSecurityOrigin( GURL("chrome-extension://knldjmfmopnpolahpmmgbagdohdnhkik/"))); EXPECT_FALSE(manifest->allowed_origins().MatchesSecurityOrigin( diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc index f735f58b6f1..1c0249b9453 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.cc @@ -38,8 +38,7 @@ namespace { ScopedAllowNativeAppConnectionForTest* g_allow_native_app_connection_for_test = nullptr; -constexpr base::TimeDelta kNativeMessagingHostErrorTimeout = - base::TimeDelta::FromSeconds(10); +constexpr base::TimeDelta kNativeMessagingHostErrorTimeout = base::Seconds(10); ScopedNativeMessagingErrorTimeoutOverrideForTest* g_native_messaging_host_timeout_override = nullptr; @@ -56,6 +55,11 @@ class NativeMessagingHostErrorReporter : public NativeMessageHost::Client { std::unique_ptr<ScopedKeepAlive, content::BrowserThread::DeleteOnUIThread>; + NativeMessagingHostErrorReporter(const NativeMessagingHostErrorReporter&) = + delete; + NativeMessagingHostErrorReporter& operator=( + const NativeMessagingHostErrorReporter&) = delete; + static void Report(const std::string& extension_id, const std::string& host_id, const std::string& connection_id, @@ -116,8 +120,6 @@ class NativeMessagingHostErrorReporter : public NativeMessageHost::Client { MovableScopedKeepAlive keep_alive_; std::unique_ptr<NativeMessageHost> process_; base::OneShotTimer timeout_; - - DISALLOW_COPY_AND_ASSIGN(NativeMessagingHostErrorReporter); }; } // namespace diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h index af341c8d352..423e863f68a 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native.h @@ -31,28 +31,36 @@ void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id, class ScopedAllowNativeAppConnectionForTest { public: explicit ScopedAllowNativeAppConnectionForTest(bool allow); + + ScopedAllowNativeAppConnectionForTest( + const ScopedAllowNativeAppConnectionForTest&) = delete; + ScopedAllowNativeAppConnectionForTest& operator=( + const ScopedAllowNativeAppConnectionForTest&) = delete; + ~ScopedAllowNativeAppConnectionForTest(); bool allow() const { return allow_; } private: const bool allow_; - - DISALLOW_COPY_AND_ASSIGN(ScopedAllowNativeAppConnectionForTest); }; class ScopedNativeMessagingErrorTimeoutOverrideForTest { public: explicit ScopedNativeMessagingErrorTimeoutOverrideForTest( base::TimeDelta timeout); + + ScopedNativeMessagingErrorTimeoutOverrideForTest( + const ScopedNativeMessagingErrorTimeoutOverrideForTest&) = delete; + ScopedNativeMessagingErrorTimeoutOverrideForTest& operator=( + const ScopedNativeMessagingErrorTimeoutOverrideForTest&) = delete; + ~ScopedNativeMessagingErrorTimeoutOverrideForTest(); base::TimeDelta timeout() const { return timeout_; } private: const base::TimeDelta timeout_; - - DISALLOW_COPY_AND_ASSIGN(ScopedNativeMessagingErrorTimeoutOverrideForTest); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h index e4b0fbf28e8..373404acdfb 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler.h @@ -18,6 +18,12 @@ class NativeMessagingHostListPolicyHandler : public policy::ListPolicyHandler { NativeMessagingHostListPolicyHandler(const char* policy_name, const char* pref_path, bool allow_wildcards); + + NativeMessagingHostListPolicyHandler( + const NativeMessagingHostListPolicyHandler&) = delete; + NativeMessagingHostListPolicyHandler& operator=( + const NativeMessagingHostListPolicyHandler&) = delete; + ~NativeMessagingHostListPolicyHandler() override; protected: @@ -32,8 +38,6 @@ class NativeMessagingHostListPolicyHandler : public policy::ListPolicyHandler { private: const char* pref_path_; bool allow_wildcards_; - - DISALLOW_COPY_AND_ASSIGN(NativeMessagingHostListPolicyHandler); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc index 0e9c22c39d9..04969e05bfe 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_policy_handler_unittest.cc @@ -31,7 +31,7 @@ TEST(NativeMessagingHostListPolicyHandlerTest, CheckPolicySettings) { EXPECT_TRUE(errors.empty()); } - list.AppendString("test.a.b"); + list.Append("test.a.b"); policy_map.Set(policy::key::kNativeMessagingBlocklist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, list.Clone(), nullptr); @@ -41,7 +41,7 @@ TEST(NativeMessagingHostListPolicyHandlerTest, CheckPolicySettings) { EXPECT_TRUE(errors.empty()); } - list.AppendString("*"); + list.Append("*"); policy_map.Set(policy::key::kNativeMessagingBlocklist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, list.Clone(), nullptr); @@ -51,7 +51,7 @@ TEST(NativeMessagingHostListPolicyHandlerTest, CheckPolicySettings) { EXPECT_TRUE(errors.empty()); } - list.AppendString("invalid Name"); + list.Append("invalid Name"); policy_map.Set(policy::key::kNativeMessagingBlocklist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, list.Clone(), nullptr); @@ -73,8 +73,8 @@ TEST(NativeMessagingHostListPolicyHandlerTest, ApplyPolicySettings) { NativeMessagingHostListPolicyHandler handler( policy::key::kNativeMessagingBlocklist, kTestPref, true); - policy.AppendString("com.example.test"); - expected.AppendString("com.example.test"); + policy.Append("com.example.test"); + expected.Append("com.example.test"); policy_map.Set(policy::key::kNativeMessagingBlocklist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, @@ -83,8 +83,8 @@ TEST(NativeMessagingHostListPolicyHandlerTest, ApplyPolicySettings) { EXPECT_TRUE(prefs.GetValue(kTestPref, &value)); EXPECT_EQ(expected, *value); - policy.AppendString("*"); - expected.AppendString("*"); + policy.Append("*"); + expected.Append("*"); policy_map.Set(policy::key::kNativeMessagingBlocklist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, @@ -93,7 +93,7 @@ TEST(NativeMessagingHostListPolicyHandlerTest, ApplyPolicySettings) { EXPECT_TRUE(prefs.GetValue(kTestPref, &value)); EXPECT_EQ(expected, *value); - policy.AppendString("invalid Name"); + policy.Append("invalid Name"); policy_map.Set(policy::key::kNativeMessagingBlocklist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, policy.Clone(), nullptr); diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h index d854ace4c33..662a8e4cc3a 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_test_util.h @@ -34,6 +34,11 @@ class ScopedTestNativeMessagingHost { static const char kExtensionId[]; ScopedTestNativeMessagingHost(); + + ScopedTestNativeMessagingHost(const ScopedTestNativeMessagingHost&) = delete; + ScopedTestNativeMessagingHost& operator=( + const ScopedTestNativeMessagingHost&) = delete; + ~ScopedTestNativeMessagingHost(); void RegisterTestHost(bool user_level); @@ -48,8 +53,6 @@ class ScopedTestNativeMessagingHost { #else std::unique_ptr<base::ScopedPathOverride> path_override_; #endif - - DISALLOW_COPY_AND_ASSIGN(ScopedTestNativeMessagingHost); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc index 2a1d664775f..d7973e72bcf 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc @@ -52,6 +52,11 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { bool require_native_initiated_connections, const std::string& connect_id, const std::string& error_arg); + + NativeProcessLauncherImpl(const NativeProcessLauncherImpl&) = delete; + NativeProcessLauncherImpl& operator=(const NativeProcessLauncherImpl&) = + delete; + ~NativeProcessLauncherImpl() override; void Launch(const GURL& origin, @@ -67,6 +72,10 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { bool require_native_initiated_connections, const std::string& connect_id, const std::string& error_arg); + + Core(const Core&) = delete; + Core& operator=(const Core&) = delete; + void Launch(const GURL& origin, const std::string& native_host_name, LaunchedCallback callback); @@ -105,13 +114,9 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { // Handle of the native window corresponding to the extension. intptr_t window_handle_; #endif // OS_WIN - - DISALLOW_COPY_AND_ASSIGN(Core); }; scoped_refptr<Core> core_; - - DISALLOW_COPY_AND_ASSIGN(NativeProcessLauncherImpl); }; NativeProcessLauncherImpl::Core::Core(bool allow_user_level_hosts, diff --git a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h index b8bfbd2a210..c40bc6343b5 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h @@ -58,6 +58,10 @@ class NativeProcessLauncher { const std::string& error_arg); NativeProcessLauncher() = default; + + NativeProcessLauncher(const NativeProcessLauncher&) = delete; + NativeProcessLauncher& operator=(const NativeProcessLauncher&) = delete; + virtual ~NativeProcessLauncher() = default; // Finds native messaging host with the specified name and launches it @@ -86,9 +90,6 @@ class NativeProcessLauncher { base::Process* process, base::File* read_file, base::File* write_file); - - private: - DISALLOW_COPY_AND_ASSIGN(NativeProcessLauncher); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h b/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h index eb2c605383b..868400eeaf7 100644 --- a/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h +++ b/chromium/chrome/browser/extensions/api/metrics_private/chrome_metrics_private_delegate.h @@ -13,13 +13,15 @@ namespace extensions { class ChromeMetricsPrivateDelegate : public MetricsPrivateDelegate { public: ChromeMetricsPrivateDelegate() {} + + ChromeMetricsPrivateDelegate(const ChromeMetricsPrivateDelegate&) = delete; + ChromeMetricsPrivateDelegate& operator=(const ChromeMetricsPrivateDelegate&) = + delete; + ~ChromeMetricsPrivateDelegate() override {} // MetricsPrivateDelegate: bool IsCrashReportingEnabled() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeMetricsPrivateDelegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc b/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc index 65b0dc73e6b..9937f4fafb5 100644 --- a/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc +++ b/chromium/chrome/browser/extensions/api/metrics_private/metrics_apitest.cc @@ -137,17 +137,10 @@ class ExtensionMetricsApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - ExtensionMetricsApiTest() = default; + ExtensionMetricsApiTest() : ExtensionApiTest(GetParam()) {} ~ExtensionMetricsApiTest() override = default; ExtensionMetricsApiTest(const ExtensionMetricsApiTest&) = delete; ExtensionMetricsApiTest& operator=(const ExtensionMetricsApiTest&) = delete; - - bool RunComponentTest(const char* extension_name) { - return RunExtensionTest( - extension_name, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker, - .load_as_component = true}); - } }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -166,7 +159,8 @@ IN_PROC_BROWSER_TEST_P(ExtensionMetricsApiTest, Metrics) { ASSERT_TRUE(variations::AssociateVariationParams( "apitestfieldtrial2", "group1", {{"a", "aa"}, {"b", "bb"}})); - ASSERT_TRUE(RunComponentTest("metrics")) << message_; + ASSERT_TRUE(RunExtensionTest("metrics", {}, {.load_as_component = true})) + << message_; ValidateUserActions(user_action_tester, g_user_actions, base::size(g_user_actions)); diff --git a/chromium/chrome/browser/extensions/api/module/module.cc b/chromium/chrome/browser/extensions/api/module/module.cc index e1773597839..fc826715d71 100644 --- a/chromium/chrome/browser/extensions/api/module/module.cc +++ b/chromium/chrome/browser/extensions/api/module/module.cc @@ -14,33 +14,15 @@ #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extension_util.h" +#include "extensions/common/constants.h" #include "extensions/common/manifest_url_handlers.h" namespace extensions { -namespace extension { - -namespace { - -// A preference for storing the extension's update URL data. If not empty, the -// the ExtensionUpdater will append a ap= parameter to the URL when checking if -// a new version of the extension is available. -const char kUpdateURLData[] = "update_url_data"; - -} // namespace - -std::string GetUpdateURLData(const ExtensionPrefs* prefs, - const std::string& extension_id) { - std::string data; - prefs->ReadPrefAsString(extension_id, kUpdateURLData, &data); - return data; -} - -} // namespace extension - ExtensionFunction::ResponseAction ExtensionSetUpdateUrlDataFunction::Run() { - std::string data; - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &data)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 1); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); + const std::string& data = args()[0].GetString(); ExtensionManagement* extension_management = ExtensionManagementFactory::GetForBrowserContext(browser_context()); @@ -49,7 +31,7 @@ ExtensionFunction::ResponseAction ExtensionSetUpdateUrlDataFunction::Run() { } ExtensionPrefs::Get(browser_context()) - ->UpdateExtensionPref(extension_id(), extension::kUpdateURLData, + ->UpdateExtensionPref(extension_id(), kUpdateURLData, std::make_unique<base::Value>(data)); return RespondNow(NoArguments()); } diff --git a/chromium/chrome/browser/extensions/api/module/module_apitest.cc b/chromium/chrome/browser/extensions/api/module/module_apitest.cc index 73bdee84533..7d5809fa331 100644 --- a/chromium/chrome/browser/extensions/api/module/module_apitest.cc +++ b/chromium/chrome/browser/extensions/api/module/module_apitest.cc @@ -14,18 +14,10 @@ using ContextType = ExtensionBrowserTest::ContextType; class ExtensionModuleApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - ExtensionModuleApiTest() = default; + ExtensionModuleApiTest() : ExtensionApiTest(GetParam()) {} ~ExtensionModuleApiTest() override = default; ExtensionModuleApiTest(const ExtensionModuleApiTest&) = delete; ExtensionModuleApiTest& operator=(const ExtensionModuleApiTest&) = delete; - - protected: - bool RunTest(const char* name, - LoadOptions load_options = {}) WARN_UNUSED_RESULT { - load_options.load_as_service_worker = - GetParam() == ContextType::kServiceWorker; - return RunExtensionTest(name, {}, load_options); - } }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -38,24 +30,25 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, } // namespace IN_PROC_BROWSER_TEST_P(ExtensionModuleApiTest, CognitoFile) { - ASSERT_TRUE( - RunTest("extension_module/cognito_file", {.allow_file_access = true})) + ASSERT_TRUE(RunExtensionTest("extension_module/cognito_file", {}, + {.allow_file_access = true})) << message_; } IN_PROC_BROWSER_TEST_P(ExtensionModuleApiTest, IncognitoFile) { - ASSERT_TRUE(RunTest("extension_module/incognito_file", - {.allow_in_incognito = true, .allow_file_access = true})) + ASSERT_TRUE( + RunExtensionTest("extension_module/incognito_file", {}, + {.allow_in_incognito = true, .allow_file_access = true})) << message_; } IN_PROC_BROWSER_TEST_P(ExtensionModuleApiTest, CognitoNoFile) { - ASSERT_TRUE(RunTest("extension_module/cognito_nofile")) << message_; + ASSERT_TRUE(RunExtensionTest("extension_module/cognito_nofile")) << message_; } IN_PROC_BROWSER_TEST_P(ExtensionModuleApiTest, IncognitoNoFile) { - ASSERT_TRUE(RunTest("extension_module/incognito_nofile", - {.allow_in_incognito = true})) + ASSERT_TRUE(RunExtensionTest("extension_module/incognito_nofile", {}, + {.allow_in_incognito = true})) << message_; } diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc index 235370d75ea..1f2ae798a79 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_apitest.cc @@ -45,6 +45,10 @@ class TestNetworkingPrivateDelegate : public NetworkingPrivateDelegate { explicit TestNetworkingPrivateDelegate(bool test_failure) : fail_(test_failure) {} + TestNetworkingPrivateDelegate(const TestNetworkingPrivateDelegate&) = delete; + TestNetworkingPrivateDelegate& operator=( + const TestNetworkingPrivateDelegate&) = delete; + ~TestNetworkingPrivateDelegate() override {} // Asynchronous methods @@ -266,13 +270,15 @@ class TestNetworkingPrivateDelegate : public NetworkingPrivateDelegate { std::map<std::string, bool> enabled_; std::map<std::string, bool> disabled_; std::vector<std::string> scan_requested_; - - DISALLOW_COPY_AND_ASSIGN(TestNetworkingPrivateDelegate); }; class NetworkingPrivateApiTest : public ExtensionApiTest { public: NetworkingPrivateApiTest() = default; + + NetworkingPrivateApiTest(const NetworkingPrivateApiTest&) = delete; + NetworkingPrivateApiTest& operator=(const NetworkingPrivateApiTest&) = delete; + ~NetworkingPrivateApiTest() override = default; void SetUpCommandLine(base::CommandLine* command_line) override { @@ -329,8 +335,6 @@ class NetworkingPrivateApiTest : public ExtensionApiTest { protected: bool test_failure_ = false; - - DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateApiTest); }; } // namespace @@ -437,10 +441,13 @@ class NetworkingPrivateApiTestFail : public NetworkingPrivateApiTest { public: NetworkingPrivateApiTestFail() { test_failure_ = true; } + NetworkingPrivateApiTestFail(const NetworkingPrivateApiTestFail&) = delete; + NetworkingPrivateApiTestFail& operator=(const NetworkingPrivateApiTestFail&) = + delete; + ~NetworkingPrivateApiTestFail() override = default; protected: - DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateApiTestFail); }; } // namespace diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc index 5c0b338e794..4852d101f0f 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_chromeos_apitest.cc @@ -117,6 +117,11 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { public: NetworkingPrivateChromeOSApiTest() {} + NetworkingPrivateChromeOSApiTest(const NetworkingPrivateChromeOSApiTest&) = + delete; + NetworkingPrivateChromeOSApiTest& operator=( + const NetworkingPrivateChromeOSApiTest&) = delete; + bool RunNetworkingSubtest(const std::string& test) { const std::string arg = base::StringPrintf("{\"test\": \"%s\"}", test.c_str()); @@ -300,7 +305,7 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { device_test()->AddDevice(kWifiDevicePath, shill::kTypeWifi, "stub_wifi_device1"); base::ListValue wifi_ip_configs; - wifi_ip_configs.AppendString(kIPConfigPath); + wifi_ip_configs.Append(kIPConfigPath); SetDeviceProperty(kWifiDevicePath, shill::kIPConfigsProperty, wifi_ip_configs); SetDeviceProperty(kWifiDevicePath, shill::kAddressProperty, @@ -342,7 +347,7 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { service_test()->SetServiceProperty( kWifi1ServicePath, shill::kStaticIPConfigProperty, static_ipconfig); base::ListValue frequencies1; - frequencies1.AppendInteger(2400); + frequencies1.Append(2400); service_test()->SetServiceProperty( kWifi1ServicePath, shill::kWifiFrequencyListProperty, frequencies1); service_test()->SetServiceProperty(kWifi1ServicePath, shill::kWifiFrequency, @@ -363,8 +368,8 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { base::Value(shill::kTetheringNotDetectedState)); base::ListValue frequencies2; - frequencies2.AppendInteger(2400); - frequencies2.AppendInteger(5000); + frequencies2.Append(2400); + frequencies2.Append(5000); service_test()->SetServiceProperty( kWifi2ServicePath, shill::kWifiFrequencyListProperty, frequencies2); service_test()->SetServiceProperty(kWifi2ServicePath, shill::kWifiFrequency, @@ -425,9 +430,6 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { sync_preferences::TestingPrefServiceSyncable user_prefs_; TestingPrefServiceSimple local_state_; std::string userhash_; - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateChromeOSApiTest); }; // Place each subtest into a separate browser test so that the stub networking diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_service_client_apitest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_service_client_apitest.cc index e0320df61da..e8e482d0b60 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_service_client_apitest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_service_client_apitest.cc @@ -46,6 +46,11 @@ class NetworkingPrivateServiceClientApiTest public: NetworkingPrivateServiceClientApiTest() {} + NetworkingPrivateServiceClientApiTest( + const NetworkingPrivateServiceClientApiTest&) = delete; + NetworkingPrivateServiceClientApiTest& operator=( + const NetworkingPrivateServiceClientApiTest&) = delete; + bool RunNetworkingSubtest(const std::string& subtest) { const std::string page_url = "main.html?" + subtest; return RunExtensionTest("networking_private/service_client", @@ -80,9 +85,6 @@ class NetworkingPrivateServiceClientApiTest content::RunAllPendingInMessageLoop(); extensions::ExtensionApiTest::TearDownOnMainThread(); } - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateServiceClientApiTest); }; // Place each subtest into a separate browser test so that the stub networking diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h b/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h index 941fd241ed4..ebb2f88bf73 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_chromeos.h @@ -16,13 +16,16 @@ class NetworkingPrivateUIDelegateChromeOS : public ::extensions::NetworkingPrivateDelegate::UIDelegate { public: NetworkingPrivateUIDelegateChromeOS(); + + NetworkingPrivateUIDelegateChromeOS( + const NetworkingPrivateUIDelegateChromeOS&) = delete; + NetworkingPrivateUIDelegateChromeOS& operator=( + const NetworkingPrivateUIDelegateChromeOS&) = delete; + ~NetworkingPrivateUIDelegateChromeOS() override; // NetworkingPrivateDelegate::UIDelegate void ShowAccountDetails(const std::string& guid) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateUIDelegateChromeOS); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.h b/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.h index d2b04c56e69..55424dad971 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.h +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_ui_delegate_factory_impl.h @@ -14,13 +14,16 @@ class NetworkingPrivateUIDelegateFactoryImpl : public NetworkingPrivateDelegateFactory::UIDelegateFactory { public: NetworkingPrivateUIDelegateFactoryImpl(); + + NetworkingPrivateUIDelegateFactoryImpl( + const NetworkingPrivateUIDelegateFactoryImpl&) = delete; + NetworkingPrivateUIDelegateFactoryImpl& operator=( + const NetworkingPrivateUIDelegateFactoryImpl&) = delete; + ~NetworkingPrivateUIDelegateFactoryImpl() override; std::unique_ptr<NetworkingPrivateDelegate::UIDelegate> CreateDelegate() override; - - private: - DISALLOW_COPY_AND_ASSIGN(NetworkingPrivateUIDelegateFactoryImpl); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.h b/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.h index a256184956d..1ed985ea05a 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.h +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.h @@ -30,6 +30,12 @@ namespace extensions { class ExtensionNotificationDisplayHelper : public KeyedService { public: explicit ExtensionNotificationDisplayHelper(Profile* profile); + + ExtensionNotificationDisplayHelper( + const ExtensionNotificationDisplayHelper&) = delete; + ExtensionNotificationDisplayHelper& operator=( + const ExtensionNotificationDisplayHelper&) = delete; + ~ExtensionNotificationDisplayHelper() override; // Displays the |notification| using the notification display service. @@ -68,8 +74,6 @@ class ExtensionNotificationDisplayHelper : public KeyedService { // Vector of notifications that are being shown for extensions. NotificationVector notifications_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionNotificationDisplayHelper); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper_factory.h b/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper_factory.h index 85911583db0..cf633162339 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper_factory.h +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper_factory.h @@ -18,6 +18,11 @@ class ExtensionNotificationDisplayHelper; class ExtensionNotificationDisplayHelperFactory : public BrowserContextKeyedServiceFactory { public: + ExtensionNotificationDisplayHelperFactory( + const ExtensionNotificationDisplayHelperFactory&) = delete; + ExtensionNotificationDisplayHelperFactory& operator=( + const ExtensionNotificationDisplayHelperFactory&) = delete; + // Get the singleton instance of the factory. static ExtensionNotificationDisplayHelperFactory* GetInstance(); @@ -37,8 +42,6 @@ class ExtensionNotificationDisplayHelperFactory ExtensionNotificationDisplayHelperFactory(); ~ExtensionNotificationDisplayHelperFactory() override; - - DISALLOW_COPY_AND_ASSIGN(ExtensionNotificationDisplayHelperFactory); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc index 6fd8bfc5f6a..6813818d1c3 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc @@ -38,7 +38,7 @@ std::unique_ptr<base::ListValue> CreateBaseEventArgs( scoped_notification_id.substr(index_of_separator); std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->AppendString(unscoped_notification_id); + args->Append(unscoped_notification_id); return args; } @@ -69,7 +69,7 @@ void ExtensionNotificationHandler::OnClose( std::unique_ptr<base::ListValue> args( CreateBaseEventArgs(extension_id, notification_id)); - args->AppendBoolean(by_user); + args->Append(by_user); SendEvent(profile, extension_id, events::NOTIFICATIONS_ON_CLOSED, api::notifications::OnClosed::kEventName, gesture, std::move(args)); @@ -94,7 +94,7 @@ void ExtensionNotificationHandler::OnClick( std::unique_ptr<base::ListValue> args( CreateBaseEventArgs(extension_id, notification_id)); if (action_index.has_value()) - args->AppendInteger(action_index.value()); + args->Append(action_index.value()); events::HistogramValue histogram_value = action_index.has_value() ? events::NOTIFICATIONS_ON_BUTTON_CLICKED : events::NOTIFICATIONS_ON_CLICKED; diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h index 2f0a8bc844c..5e9a4322f87 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h @@ -18,6 +18,11 @@ namespace extensions { class ExtensionNotificationHandler : public NotificationHandler { public: ExtensionNotificationHandler(); + + ExtensionNotificationHandler(const ExtensionNotificationHandler&) = delete; + ExtensionNotificationHandler& operator=(const ExtensionNotificationHandler&) = + delete; + ~ExtensionNotificationHandler() override; // Extracts an extension ID from the URL for an app window, or an empty string @@ -46,8 +51,6 @@ class ExtensionNotificationHandler : public NotificationHandler { const std::string& name, EventRouter::UserGestureState user_gesture, std::unique_ptr<base::ListValue> args); - - DISALLOW_COPY_AND_ASSIGN(ExtensionNotificationHandler); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc index 9c6d2507ca8..45f36fe6018 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler_unittest.cc @@ -44,7 +44,7 @@ class TestExtensionNotificationHandler : public ExtensionNotificationHandler { std::unique_ptr<base::ListValue> args) final { EXPECT_EQ(event_name_, event_name); EXPECT_EQ(extension_id_, extension_id); - EXPECT_EQ(param_count_, args->GetSize()); + EXPECT_EQ(param_count_, args->GetList().size()); } private: diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc index 7822dc7241f..7e2a256dcd5 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc @@ -43,11 +43,11 @@ #include "extensions/common/extension.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/base/layout.h" +#include "ui/gfx/geometry/skia_conversions.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/image/image_skia_rep.h" -#include "ui/gfx/skia_util.h" #include "ui/message_center/public/cpp/message_center_constants.h" #include "ui/message_center/public/cpp/notification.h" #include "ui/message_center/public/cpp/notification_delegate.h" @@ -556,7 +556,7 @@ NotificationsCreateFunction::~NotificationsCreateFunction() { ExtensionFunction::ResponseAction NotificationsCreateFunction::RunNotificationsApi() { - params_ = api::notifications::Create::Params::Create(*args_); + params_ = api::notifications::Create::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_.get()); const std::string extension_id(extension_->id()); @@ -590,7 +590,7 @@ NotificationsUpdateFunction::~NotificationsUpdateFunction() { ExtensionFunction::ResponseAction NotificationsUpdateFunction::RunNotificationsApi() { - params_ = api::notifications::Update::Params::Create(*args_); + params_ = api::notifications::Update::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_.get()); // We are in update. If the ID doesn't exist, succeed but call the callback @@ -631,7 +631,7 @@ NotificationsClearFunction::~NotificationsClearFunction() { ExtensionFunction::ResponseAction NotificationsClearFunction::RunNotificationsApi() { - params_ = api::notifications::Clear::Params::Create(*args_); + params_ = api::notifications::Clear::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_.get()); bool cancel_result = GetDisplayHelper()->Close( diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc index 56e3129ba59..c38f8ff9677 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc @@ -27,16 +27,15 @@ #include "chrome/browser/notifications/notifier_state_tracker_factory.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/test/base/interactive_test_utils.h" -#include "content/public/browser/notification_service.h" #include "content/public/test/browser_test.h" -#include "content/public/test/test_utils.h" #include "extensions/browser/api/test/test_api.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/app_window/native_app_window.h" -#include "extensions/browser/notification_types.h" +#include "extensions/browser/extension_host_test_helper.h" #include "extensions/common/extension_builder.h" #include "extensions/common/features/feature.h" +#include "extensions/common/mojom/view_type.mojom.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" #include "ui/message_center/public/cpp/notification.h" @@ -65,7 +64,8 @@ enum class WindowState { class NotificationsApiTest : public extensions::ExtensionApiTest { public: - NotificationsApiTest() = default; + explicit NotificationsApiTest(ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) {} ~NotificationsApiTest() override = default; NotificationsApiTest(const NotificationsApiTest&) = delete; NotificationsApiTest& operator=(const NotificationsApiTest&) = delete; @@ -73,12 +73,12 @@ class NotificationsApiTest : public extensions::ExtensionApiTest { const Extension* LoadExtensionAndWait( const std::string& test_name) { base::FilePath extdir = test_data_dir_.AppendASCII(test_name); - content::WindowedNotificationObserver page_created( - extensions::NOTIFICATION_EXTENSION_BACKGROUND_PAGE_READY, - content::NotificationService::AllSources()); + extensions::ExtensionHostTestHelper host_helper(profile()); + host_helper.RestrictToType( + extensions::mojom::ViewType::kExtensionBackgroundPage); const extensions::Extension* extension = LoadExtension(extdir); if (extension) { - page_created.Wait(); + host_helper.WaitForDocumentElementAvailable(); } return extension; } @@ -179,19 +179,12 @@ class NotificationsApiTestWithBackgroundType : public NotificationsApiTest, public testing::WithParamInterface<ContextType> { public: - NotificationsApiTestWithBackgroundType() = default; + NotificationsApiTestWithBackgroundType() : NotificationsApiTest(GetParam()) {} ~NotificationsApiTestWithBackgroundType() override = default; NotificationsApiTestWithBackgroundType( const NotificationsApiTestWithBackgroundType&) = delete; NotificationsApiTestWithBackgroundType& operator=( const NotificationsApiTestWithBackgroundType&) = delete; - - protected: - bool RunTest(const char* name) { - return RunExtensionTest( - name, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; } // namespace @@ -204,15 +197,15 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, testing::Values(ContextType::kServiceWorker)); IN_PROC_BROWSER_TEST_P(NotificationsApiTestWithBackgroundType, TestBasicUsage) { - ASSERT_TRUE(RunTest("notifications/api/basic_usage")) << message_; + ASSERT_TRUE(RunExtensionTest("notifications/api/basic_usage")) << message_; } IN_PROC_BROWSER_TEST_P(NotificationsApiTestWithBackgroundType, TestEvents) { - ASSERT_TRUE(RunTest("notifications/api/events")) << message_; + ASSERT_TRUE(RunExtensionTest("notifications/api/events")) << message_; } IN_PROC_BROWSER_TEST_P(NotificationsApiTestWithBackgroundType, TestCSP) { - ASSERT_TRUE(RunTest("notifications/api/csp")) << message_; + ASSERT_TRUE(RunExtensionTest("notifications/api/csp")) << message_; } // Native notifications don't support (or use) observers. @@ -259,7 +252,7 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestByUser) { IN_PROC_BROWSER_TEST_P(NotificationsApiTestWithBackgroundType, TestPartialUpdate) { - ASSERT_TRUE(RunTest("notifications/api/partial_update")) << message_; + ASSERT_TRUE(RunExtensionTest("notifications/api/partial_update")) << message_; const extensions::Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension) << message_; diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc index 6810c11bb8f..b73737e5988 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.cc @@ -276,7 +276,7 @@ void BrowserContextKeyedAPIFactory<OmniboxAPI>::DeclareFactoryDependencies() { ExtensionFunction::ResponseAction OmniboxSendSuggestionsFunction::Run() { std::unique_ptr<SendSuggestions::Params> params( - SendSuggestions::Params::Create(*args_)); + SendSuggestions::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); content::NotificationService::current()->Notify( @@ -290,7 +290,7 @@ ExtensionFunction::ResponseAction OmniboxSendSuggestionsFunction::Run() { ExtensionFunction::ResponseAction OmniboxSetDefaultSuggestionFunction::Run() { std::unique_ptr<SetDefaultSuggestion::Params> params( - SetDefaultSuggestion::Params::Create(*args_)); + SetDefaultSuggestion::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); Profile* profile = Profile::FromBrowserContext(browser_context()); diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h index 11722fcc760..6b7ec9eeb53 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h @@ -39,6 +39,10 @@ namespace extensions { // Event router class for events related to the omnibox API. class ExtensionOmniboxEventRouter { public: + ExtensionOmniboxEventRouter(const ExtensionOmniboxEventRouter&) = delete; + ExtensionOmniboxEventRouter& operator=(const ExtensionOmniboxEventRouter&) = + delete; + // The user has just typed the omnibox keyword. This is sent exactly once in // a given input session, before any OnInputChanged events. static void OnInputStarted( @@ -68,9 +72,6 @@ class ExtensionOmniboxEventRouter { static void OnDeleteSuggestion(Profile* profile, const std::string& extension_id, const std::string& suggestion_text); - - private: - DISALLOW_COPY_AND_ASSIGN(ExtensionOmniboxEventRouter); }; class OmniboxSendSuggestionsFunction : public ExtensionFunction { @@ -88,6 +89,10 @@ class OmniboxAPI : public BrowserContextKeyedAPI, public ExtensionRegistryObserver { public: explicit OmniboxAPI(content::BrowserContext* context); + + OmniboxAPI(const OmniboxAPI&) = delete; + OmniboxAPI& operator=(const OmniboxAPI&) = delete; + ~OmniboxAPI() override; // BrowserContextKeyedAPI implementation. @@ -139,8 +144,6 @@ class OmniboxAPI : public BrowserContextKeyedAPI, ExtensionIconManager omnibox_icon_manager_; base::CallbackListSubscription template_url_subscription_; - - DISALLOW_COPY_AND_ASSIGN(OmniboxAPI); }; template <> diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc index 1305648569e..480291cd8e6 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api_interactive_test.cc @@ -27,7 +27,7 @@ #include "components/omnibox/browser/autocomplete_match.h" #include "components/omnibox/browser/autocomplete_result.h" #include "components/omnibox/browser/omnibox_controller_emitter.h" -#include "components/omnibox/browser/omnibox_popup_model.h" +#include "components/omnibox/browser/omnibox_edit_model.h" #include "components/omnibox/browser/omnibox_view.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" @@ -327,7 +327,6 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_PopupStaysClosed) { OmniboxView* omnibox_view = location_bar->GetOmniboxView(); AutocompleteController* autocomplete_controller = GetAutocompleteController(browser()); - OmniboxPopupModel* popup_model = omnibox_view->model()->popup_model(); // Input a keyword query and wait for suggestions from the extension. omnibox_view->OnBeforePossibleChange(); @@ -335,7 +334,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_PopupStaysClosed) { omnibox_view->OnAfterPossibleChange(true); WaitForAutocompleteDone(browser()); EXPECT_TRUE(autocomplete_controller->done()); - EXPECT_TRUE(popup_model->IsOpen()); + EXPECT_TRUE(omnibox_view->model()->PopupIsOpen()); // Quickly type another query and accept it before getting suggestions back // for the query. The popup will close after accepting input - ensure that it @@ -354,7 +353,7 @@ IN_PROC_BROWSER_TEST_F(OmniboxApiTest, MAYBE_PopupStaysClosed) { // This checks that the keyword provider (via javascript) // gets told to navigate to the string "command". EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); - EXPECT_FALSE(popup_model->IsOpen()); + EXPECT_FALSE(omnibox_view->model()->PopupIsOpen()); } // Tests deleting a deletable omnibox extension suggestion result. diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_unittest.cc b/chromium/chrome/browser/extensions/api/omnibox/omnibox_unittest.cc index c4cf4d1f58e..b239bf215b7 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_unittest.cc +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_unittest.cc @@ -77,7 +77,7 @@ TEST(ExtensionOmniboxTest, DescriptionStylesSimple) { styles_expected.push_back(ACMatchClassification(9, kNone)); std::unique_ptr<SendSuggestions::Params> params( - SendSuggestions::Params::Create(*list)); + SendSuggestions::Params::Create(list->GetList())); EXPECT_TRUE(params); ASSERT_FALSE(params->suggest_results.empty()); CompareClassification(styles_expected, StyleTypesToACMatchClassifications( @@ -109,7 +109,7 @@ TEST(ExtensionOmniboxTest, DescriptionStylesSimple) { .Build(); std::unique_ptr<SendSuggestions::Params> swapped_params( - SendSuggestions::Params::Create(*swap_list)); + SendSuggestions::Params::Create(swap_list->GetList())); EXPECT_TRUE(swapped_params); ASSERT_FALSE(swapped_params->suggest_results.empty()); CompareClassification( @@ -173,7 +173,7 @@ TEST(ExtensionOmniboxTest, DescriptionStylesCombine) { styles_expected.push_back(ACMatchClassification(9, kMatch | kDim)); std::unique_ptr<SendSuggestions::Params> params( - SendSuggestions::Params::Create(*list)); + SendSuggestions::Params::Create(list->GetList())); EXPECT_TRUE(params); ASSERT_FALSE(params->suggest_results.empty()); CompareClassification(styles_expected, StyleTypesToACMatchClassifications( @@ -221,7 +221,7 @@ TEST(ExtensionOmniboxTest, DescriptionStylesCombine) { .Build(); std::unique_ptr<SendSuggestions::Params> moved_params( - SendSuggestions::Params::Create(*moved_list)); + SendSuggestions::Params::Create(moved_list->GetList())); EXPECT_TRUE(moved_params); ASSERT_FALSE(moved_params->suggest_results.empty()); CompareClassification(styles_expected, StyleTypesToACMatchClassifications( @@ -280,7 +280,7 @@ TEST(ExtensionOmniboxTest, DescriptionStylesCombine2) { styles_expected.push_back(ACMatchClassification(5, kNone)); std::unique_ptr<SendSuggestions::Params> params( - SendSuggestions::Params::Create(*list)); + SendSuggestions::Params::Create(list->GetList())); EXPECT_TRUE(params); ASSERT_FALSE(params->suggest_results.empty()); CompareClassification(styles_expected, StyleTypesToACMatchClassifications( @@ -332,7 +332,7 @@ TEST(ExtensionOmniboxTest, DefaultSuggestResult) { .Build(); std::unique_ptr<SetDefaultSuggestion::Params> params( - SetDefaultSuggestion::Params::Create(*list)); + SetDefaultSuggestion::Params::Create(list->GetList())); EXPECT_TRUE(params); } diff --git a/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc b/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc index 7045765b6b3..492f62fe3e3 100644 --- a/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc +++ b/chromium/chrome/browser/extensions/api/page_capture/page_capture_api.cc @@ -88,7 +88,7 @@ void PageCaptureSaveAsMHTMLFunction::SetTestDelegate(TestDelegate* delegate) { } ExtensionFunction::ResponseAction PageCaptureSaveAsMHTMLFunction::Run() { - params_ = SaveAsMHTML::Params::Create(*args_); + params_ = SaveAsMHTML::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_.get()); // Add a reference, extending the lifespan of this extension function until diff --git a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc index 21d7afa6e56..cc005d42328 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate.cc @@ -171,7 +171,7 @@ api::passwords_private::PasswordCheckState ConvertPasswordCheckState( std::string FormatElapsedTime(base::Time time) { const base::TimeDelta elapsed_time = base::Time::Now() - time; - if (elapsed_time < base::TimeDelta::FromMinutes(1)) + if (elapsed_time < base::Minutes(1)) return l10n_util::GetStringUTF8(IDS_SETTINGS_PASSWORDS_JUST_NOW); return base::UTF16ToUTF8(TimeFormat::SimpleWithMonthAndYear( @@ -521,7 +521,7 @@ void PasswordCheckDelegate:: FROM_HERE, base::BindOnce(&PasswordCheckDelegate::NotifyPasswordCheckStatusChanged, weak_ptr_factory_.GetWeakPtr()), - base::TimeDelta::FromSeconds(1)); + base::Seconds(1)); } void PasswordCheckDelegate::RecordAndNotifyAboutCompletedWeakPasswordCheck() { diff --git a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc index 8e2da832094..bbd4952d2a4 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/password_check_delegate_unittest.cc @@ -352,50 +352,45 @@ TEST_F(PasswordCheckDelegateTest, WeakCheckWhenUserSignedOut) { // credentials are ordered by recency. TEST_F(PasswordCheckDelegateTest, GetCompromisedCredentialsOrders) { PasswordForm form_com_username1 = MakeSavedPassword(kExampleCom, kUsername1); - AddIssueToForm(&form_com_username1, InsecureType::kLeaked, - base::TimeDelta::FromMinutes(1)); + AddIssueToForm(&form_com_username1, InsecureType::kLeaked, base::Minutes(1)); store().AddLogin(form_com_username1); PasswordForm form_com_username2 = MakeSavedPassword(kExampleCom, kUsername2); - AddIssueToForm(&form_com_username2, InsecureType::kPhished, - base::TimeDelta::FromMinutes(2)); + AddIssueToForm(&form_com_username2, InsecureType::kPhished, base::Minutes(2)); store().AddLogin(form_com_username2); PasswordForm form_org_username1 = MakeSavedPassword(kExampleOrg, kUsername1); - AddIssueToForm(&form_org_username1, InsecureType::kPhished, - base::TimeDelta::FromMinutes(4)); + AddIssueToForm(&form_org_username1, InsecureType::kPhished, base::Minutes(4)); store().AddLogin(form_org_username1); PasswordForm form_org_username2 = MakeSavedPassword(kExampleOrg, kUsername2); - AddIssueToForm(&form_org_username2, InsecureType::kLeaked, - base::TimeDelta::FromMinutes(3)); + AddIssueToForm(&form_org_username2, InsecureType::kLeaked, base::Minutes(3)); store().AddLogin(form_org_username2); RunUntilIdle(); EXPECT_THAT( delegate().GetCompromisedCredentials(), - ElementsAre( - ExpectCompromisedCredential( - "example.com", "https://example.com", - "https://example.com/.well-known/change-password", kUsername2, - base::TimeDelta::FromMinutes(2), "2 minutes ago", - api::passwords_private::COMPROMISE_TYPE_PHISHED), - ExpectCompromisedCredential( - "example.org", "http://www.example.org", - "http://www.example.org/.well-known/change-password", kUsername1, - base::TimeDelta::FromMinutes(4), "4 minutes ago", - api::passwords_private::COMPROMISE_TYPE_PHISHED), - ExpectCompromisedCredential( - "example.com", "https://example.com", - "https://example.com/.well-known/change-password", kUsername1, - base::TimeDelta::FromMinutes(1), "1 minute ago", - api::passwords_private::COMPROMISE_TYPE_LEAKED), - ExpectCompromisedCredential( - "example.org", "http://www.example.org", - "http://www.example.org/.well-known/change-password", kUsername2, - base::TimeDelta::FromMinutes(3), "3 minutes ago", - api::passwords_private::COMPROMISE_TYPE_LEAKED))); + ElementsAre(ExpectCompromisedCredential( + "example.com", "https://example.com", + "https://example.com/.well-known/change-password", + kUsername2, base::Minutes(2), "2 minutes ago", + api::passwords_private::COMPROMISE_TYPE_PHISHED), + ExpectCompromisedCredential( + "example.org", "http://www.example.org", + "http://www.example.org/.well-known/change-password", + kUsername1, base::Minutes(4), "4 minutes ago", + api::passwords_private::COMPROMISE_TYPE_PHISHED), + ExpectCompromisedCredential( + "example.com", "https://example.com", + "https://example.com/.well-known/change-password", + kUsername1, base::Minutes(1), "1 minute ago", + api::passwords_private::COMPROMISE_TYPE_LEAKED), + ExpectCompromisedCredential( + "example.org", "http://www.example.org", + "http://www.example.org/.well-known/change-password", + kUsername2, base::Minutes(3), "3 minutes ago", + api::passwords_private::COMPROMISE_TYPE_LEAKED))); } // Verifies that the formatted timestamp associated with a compromised @@ -403,50 +398,45 @@ TEST_F(PasswordCheckDelegateTest, GetCompromisedCredentialsOrders) { // months and years. TEST_F(PasswordCheckDelegateTest, GetCompromisedCredentialsHandlesTimes) { PasswordForm form_com_username1 = MakeSavedPassword(kExampleCom, kUsername1); - AddIssueToForm(&form_com_username1, InsecureType::kLeaked, - base::TimeDelta::FromSeconds(59)); + AddIssueToForm(&form_com_username1, InsecureType::kLeaked, base::Seconds(59)); store().AddLogin(form_com_username1); PasswordForm form_com_username2 = MakeSavedPassword(kExampleCom, kUsername2); - AddIssueToForm(&form_com_username2, InsecureType::kLeaked, - base::TimeDelta::FromSeconds(60)); + AddIssueToForm(&form_com_username2, InsecureType::kLeaked, base::Seconds(60)); store().AddLogin(form_com_username2); PasswordForm form_org_username1 = MakeSavedPassword(kExampleOrg, kUsername1); - AddIssueToForm(&form_org_username1, InsecureType::kLeaked, - base::TimeDelta::FromDays(100)); + AddIssueToForm(&form_org_username1, InsecureType::kLeaked, base::Days(100)); store().AddLogin(form_org_username1); PasswordForm form_org_username2 = MakeSavedPassword(kExampleOrg, kUsername2); - AddIssueToForm(&form_org_username2, InsecureType::kLeaked, - base::TimeDelta::FromDays(800)); + AddIssueToForm(&form_org_username2, InsecureType::kLeaked, base::Days(800)); store().AddLogin(form_org_username2); RunUntilIdle(); EXPECT_THAT( delegate().GetCompromisedCredentials(), - ElementsAre( - ExpectCompromisedCredential( - "example.com", "https://example.com", - "https://example.com/.well-known/change-password", kUsername1, - base::TimeDelta::FromSeconds(59), "Just now", - api::passwords_private::COMPROMISE_TYPE_LEAKED), - ExpectCompromisedCredential( - "example.com", "https://example.com", - "https://example.com/.well-known/change-password", kUsername2, - base::TimeDelta::FromSeconds(60), "1 minute ago", - api::passwords_private::COMPROMISE_TYPE_LEAKED), - ExpectCompromisedCredential( - "example.org", "http://www.example.org", - "http://www.example.org/.well-known/change-password", kUsername1, - base::TimeDelta::FromDays(100), "3 months ago", - api::passwords_private::COMPROMISE_TYPE_LEAKED), - ExpectCompromisedCredential( - "example.org", "http://www.example.org", - "http://www.example.org/.well-known/change-password", kUsername2, - base::TimeDelta::FromDays(800), "2 years ago", - api::passwords_private::COMPROMISE_TYPE_LEAKED))); + ElementsAre(ExpectCompromisedCredential( + "example.com", "https://example.com", + "https://example.com/.well-known/change-password", + kUsername1, base::Seconds(59), "Just now", + api::passwords_private::COMPROMISE_TYPE_LEAKED), + ExpectCompromisedCredential( + "example.com", "https://example.com", + "https://example.com/.well-known/change-password", + kUsername2, base::Seconds(60), "1 minute ago", + api::passwords_private::COMPROMISE_TYPE_LEAKED), + ExpectCompromisedCredential( + "example.org", "http://www.example.org", + "http://www.example.org/.well-known/change-password", + kUsername1, base::Days(100), "3 months ago", + api::passwords_private::COMPROMISE_TYPE_LEAKED), + ExpectCompromisedCredential( + "example.org", "http://www.example.org", + "http://www.example.org/.well-known/change-password", + kUsername2, base::Days(800), "2 years ago", + api::passwords_private::COMPROMISE_TYPE_LEAKED))); } // Verifies that both leaked and phished credentials are ordered correctly @@ -456,27 +446,21 @@ TEST_F(PasswordCheckDelegateTest, GetCompromisedCredentialsHandlesTimes) { TEST_F(PasswordCheckDelegateTest, GetCompromisedCredentialsDedupesLeakedAndCompromised) { PasswordForm form_com_username1 = MakeSavedPassword(kExampleCom, kUsername1); - AddIssueToForm(&form_com_username1, InsecureType::kLeaked, - base::TimeDelta::FromMinutes(1)); - AddIssueToForm(&form_com_username1, InsecureType::kPhished, - base::TimeDelta::FromMinutes(5)); + AddIssueToForm(&form_com_username1, InsecureType::kLeaked, base::Minutes(1)); + AddIssueToForm(&form_com_username1, InsecureType::kPhished, base::Minutes(5)); store().AddLogin(form_com_username1); PasswordForm form_com_username2 = MakeSavedPassword(kExampleCom, kUsername2); - AddIssueToForm(&form_com_username2, InsecureType::kLeaked, - base::TimeDelta::FromMinutes(2)); + AddIssueToForm(&form_com_username2, InsecureType::kLeaked, base::Minutes(2)); store().AddLogin(form_com_username2); PasswordForm form_org_username1 = MakeSavedPassword(kExampleOrg, kUsername1); - AddIssueToForm(&form_org_username1, InsecureType::kPhished, - base::TimeDelta::FromMinutes(3)); + AddIssueToForm(&form_org_username1, InsecureType::kPhished, base::Minutes(3)); store().AddLogin(form_org_username1); PasswordForm form_org_username2 = MakeSavedPassword(kExampleOrg, kUsername2); - AddIssueToForm(&form_org_username2, InsecureType::kPhished, - base::TimeDelta::FromMinutes(4)); - AddIssueToForm(&form_org_username2, InsecureType::kLeaked, - base::TimeDelta::FromMinutes(6)); + AddIssueToForm(&form_org_username2, InsecureType::kPhished, base::Minutes(4)); + AddIssueToForm(&form_org_username2, InsecureType::kLeaked, base::Minutes(6)); store().AddLogin(form_org_username2); RunUntilIdle(); @@ -487,40 +471,38 @@ TEST_F(PasswordCheckDelegateTest, ExpectCompromisedCredential( "example.com", "https://example.com", "https://example.com/.well-known/change-password", kUsername1, - base::TimeDelta::FromMinutes(1), "1 minute ago", + base::Minutes(1), "1 minute ago", api::passwords_private::COMPROMISE_TYPE_PHISHED_AND_LEAKED), ExpectCompromisedCredential( "example.org", "http://www.example.org", "http://www.example.org/.well-known/change-password", kUsername1, - base::TimeDelta::FromMinutes(3), "3 minutes ago", + base::Minutes(3), "3 minutes ago", api::passwords_private::COMPROMISE_TYPE_PHISHED), ExpectCompromisedCredential( "example.org", "http://www.example.org", "http://www.example.org/.well-known/change-password", kUsername2, - base::TimeDelta::FromMinutes(4), "4 minutes ago", + base::Minutes(4), "4 minutes ago", api::passwords_private::COMPROMISE_TYPE_PHISHED_AND_LEAKED), ExpectCompromisedCredential( "example.com", "https://example.com", "https://example.com/.well-known/change-password", kUsername2, - base::TimeDelta::FromMinutes(2), "2 minutes ago", + base::Minutes(2), "2 minutes ago", api::passwords_private::COMPROMISE_TYPE_LEAKED))); } TEST_F(PasswordCheckDelegateTest, GetCompromisedCredentialsInjectsAndroid) { PasswordForm form = MakeSavedPassword(kExampleCom, kUsername1); - AddIssueToForm(&form, InsecureType::kLeaked, base::TimeDelta::FromMinutes(5)); + AddIssueToForm(&form, InsecureType::kLeaked, base::Minutes(5)); store().AddLogin(form); PasswordForm android_form1 = MakeSavedAndroidPassword(kExampleApp, kUsername1); - AddIssueToForm(&android_form1, InsecureType::kPhished, - base::TimeDelta::FromDays(4)); + AddIssueToForm(&android_form1, InsecureType::kPhished, base::Days(4)); store().AddLogin(android_form1); PasswordForm android_form2 = MakeSavedAndroidPassword( kExampleApp, kUsername2, "Example App", kExampleCom); - AddIssueToForm(&android_form2, InsecureType::kPhished, - base::TimeDelta::FromDays(3)); + AddIssueToForm(&android_form2, InsecureType::kPhished, base::Days(3)); store().AddLogin(android_form2); RunUntilIdle(); @@ -529,21 +511,20 @@ TEST_F(PasswordCheckDelegateTest, GetCompromisedCredentialsInjectsAndroid) { // password store. EXPECT_THAT( delegate().GetCompromisedCredentials(), - ElementsAre( - ExpectCompromisedCredential( - "Example App", "Example App", - "https://example.com/.well-known/change-password", kUsername2, - base::TimeDelta::FromDays(3), "3 days ago", - api::passwords_private::COMPROMISE_TYPE_PHISHED), - ExpectCompromisedCredential( - "App (com.example.app)", "com.example.app", absl::nullopt, - kUsername1, base::TimeDelta::FromDays(4), "4 days ago", - api::passwords_private::COMPROMISE_TYPE_PHISHED), - ExpectCompromisedCredential( - "example.com", "https://example.com", - "https://example.com/.well-known/change-password", kUsername1, - base::TimeDelta::FromMinutes(5), "5 minutes ago", - api::passwords_private::COMPROMISE_TYPE_LEAKED))); + ElementsAre(ExpectCompromisedCredential( + "Example App", "Example App", + "https://example.com/.well-known/change-password", + kUsername2, base::Days(3), "3 days ago", + api::passwords_private::COMPROMISE_TYPE_PHISHED), + ExpectCompromisedCredential( + "App (com.example.app)", "com.example.app", absl::nullopt, + kUsername1, base::Days(4), "4 days ago", + api::passwords_private::COMPROMISE_TYPE_PHISHED), + ExpectCompromisedCredential( + "example.com", "https://example.com", + "https://example.com/.well-known/change-password", + kUsername1, base::Minutes(5), "5 minutes ago", + api::passwords_private::COMPROMISE_TYPE_LEAKED))); } // Test that a change to compromised credential notifies observers. @@ -1038,7 +1019,7 @@ TEST_F(PasswordCheckDelegateTest, LastTimePasswordCheckCompletedNotSet) { TEST_F(PasswordCheckDelegateTest, LastTimePasswordCheckCompletedIsSet) { profile().GetPrefs()->SetDouble( kLastTimePasswordCheckCompleted, - (base::Time::Now() - base::TimeDelta::FromMinutes(5)).ToDoubleT()); + (base::Time::Now() - base::Minutes(5)).ToDoubleT()); PasswordCheckStatus status = delegate().GetPasswordCheckStatus(); EXPECT_THAT(status.elapsed_time_since_last_check, diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc index 292b700c38e..90199b77ca9 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc @@ -49,7 +49,7 @@ PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction::Run() { // PasswordsPrivateChangeSavedPasswordFunction ResponseAction PasswordsPrivateChangeSavedPasswordFunction::Run() { auto parameters = - api::passwords_private::ChangeSavedPassword::Params::Create(*args_); + api::passwords_private::ChangeSavedPassword::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); if (!GetDelegate(browser_context()) @@ -68,7 +68,7 @@ ResponseAction PasswordsPrivateChangeSavedPasswordFunction::Run() { // PasswordsPrivateRemoveSavedPasswordFunction ResponseAction PasswordsPrivateRemoveSavedPasswordFunction::Run() { auto parameters = - api::passwords_private::RemoveSavedPassword::Params::Create(*args_); + api::passwords_private::RemoveSavedPassword::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); GetDelegate(browser_context())->RemoveSavedPasswords({parameters->id}); return RespondNow(NoArguments()); @@ -77,7 +77,7 @@ ResponseAction PasswordsPrivateRemoveSavedPasswordFunction::Run() { // PasswordsPrivateRemoveSavedPasswordsFunction ResponseAction PasswordsPrivateRemoveSavedPasswordsFunction::Run() { auto parameters = - api::passwords_private::RemoveSavedPasswords::Params::Create(*args_); + api::passwords_private::RemoveSavedPasswords::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); GetDelegate(browser_context())->RemoveSavedPasswords(parameters->ids); return RespondNow(NoArguments()); @@ -86,7 +86,7 @@ ResponseAction PasswordsPrivateRemoveSavedPasswordsFunction::Run() { // PasswordsPrivateRemovePasswordExceptionFunction ResponseAction PasswordsPrivateRemovePasswordExceptionFunction::Run() { auto parameters = - api::passwords_private::RemovePasswordException::Params::Create(*args_); + api::passwords_private::RemovePasswordException::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); GetDelegate(browser_context())->RemovePasswordExceptions({parameters->id}); return RespondNow(NoArguments()); @@ -95,7 +95,7 @@ ResponseAction PasswordsPrivateRemovePasswordExceptionFunction::Run() { // PasswordsPrivateRemovePasswordExceptionsFunction ResponseAction PasswordsPrivateRemovePasswordExceptionsFunction::Run() { auto parameters = - api::passwords_private::RemovePasswordExceptions::Params::Create(*args_); + api::passwords_private::RemovePasswordExceptions::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); GetDelegate(browser_context())->RemovePasswordExceptions(parameters->ids); return RespondNow(NoArguments()); @@ -111,7 +111,7 @@ PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction::Run() { // PasswordsPrivateRequestPlaintextPasswordFunction ResponseAction PasswordsPrivateRequestPlaintextPasswordFunction::Run() { auto parameters = - api::passwords_private::RequestPlaintextPassword::Params::Create(*args_); + api::passwords_private::RequestPlaintextPassword::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); GetDelegate(browser_context()) @@ -136,7 +136,7 @@ void PasswordsPrivateRequestPlaintextPasswordFunction::GotPassword( Respond(Error(base::StringPrintf( "Could not obtain plaintext password. Either the user is not " "authenticated or no password with id = %d could be found.", - api::passwords_private::RequestPlaintextPassword::Params::Create(*args_) + api::passwords_private::RequestPlaintextPassword::Params::Create(args()) ->id))); } @@ -190,7 +190,7 @@ void PasswordsPrivateGetPasswordExceptionListFunction::GotList( // PasswordsPrivateMovePasswordToAccountFunction ResponseAction PasswordsPrivateMovePasswordsToAccountFunction::Run() { auto parameters = - api::passwords_private::MovePasswordsToAccount::Params::Create(*args_); + api::passwords_private::MovePasswordsToAccount::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); GetDelegate(browser_context()) ->MovePasswordsToAccount(parameters->ids, GetSenderWebContents()); @@ -244,7 +244,7 @@ ResponseAction PasswordsPrivateIsOptedInForAccountStorageFunction::Run() { // PasswordsPrivateOptInForAccountStorageFunction ResponseAction PasswordsPrivateOptInForAccountStorageFunction::Run() { auto parameters = - api::passwords_private::OptInForAccountStorage::Params::Create(*args_); + api::passwords_private::OptInForAccountStorage::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); GetDelegate(browser_context()) @@ -279,7 +279,7 @@ PasswordsPrivateGetPlaintextInsecurePasswordFunction:: ResponseAction PasswordsPrivateGetPlaintextInsecurePasswordFunction::Run() { auto parameters = api::passwords_private::GetPlaintextInsecurePassword::Params::Create( - *args_); + args()); EXTENSION_FUNCTION_VALIDATE(parameters); GetDelegate(browser_context()) @@ -314,7 +314,7 @@ PasswordsPrivateChangeInsecureCredentialFunction:: ResponseAction PasswordsPrivateChangeInsecureCredentialFunction::Run() { auto parameters = - api::passwords_private::ChangeInsecureCredential::Params::Create(*args_); + api::passwords_private::ChangeInsecureCredential::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); if (parameters->new_password.empty()) { @@ -340,7 +340,7 @@ PasswordsPrivateRemoveInsecureCredentialFunction:: ResponseAction PasswordsPrivateRemoveInsecureCredentialFunction::Run() { auto parameters = - api::passwords_private::RemoveInsecureCredential::Params::Create(*args_); + api::passwords_private::RemoveInsecureCredential::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters); if (!GetDelegate(browser_context()) diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc index 7faacc37ace..c29bc2af8c4 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_apitest.cc @@ -41,6 +41,10 @@ namespace { class PasswordsPrivateApiTest : public ExtensionApiTest { public: PasswordsPrivateApiTest() = default; + + PasswordsPrivateApiTest(const PasswordsPrivateApiTest&) = delete; + PasswordsPrivateApiTest& operator=(const PasswordsPrivateApiTest&) = delete; + ~PasswordsPrivateApiTest() override = default; void SetUpOnMainThread() override { @@ -108,8 +112,6 @@ class PasswordsPrivateApiTest : public ExtensionApiTest { private: TestPasswordsPrivateDelegate* s_test_delegate_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateApiTest); }; } // namespace diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc index b03e48ac34c..de42cba59f5 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc @@ -65,8 +65,7 @@ const char kReauthenticationFailed[] = "reauth-failed"; #if BUILDFLAG(IS_CHROMEOS_ASH) constexpr base::TimeDelta kShowPasswordAuthTokenLifetime = password_manager::PasswordAccessAuthenticator::kAuthValidityPeriod; -constexpr base::TimeDelta kExportPasswordsAuthTokenLifetime = - base::TimeDelta::FromSeconds(5); +constexpr base::TimeDelta kExportPasswordsAuthTokenLifetime = base::Seconds(5); #endif // Map password_manager::ExportProgressStatus to @@ -289,72 +288,50 @@ void PasswordsPrivateDelegateImpl::RequestPlaintextPassword( // TODO(crbug.com/495290): Pass the native window directly to the // reauth-handling code. web_contents_ = web_contents; - if (!password_access_authenticator_.EnsureUserIsAuthenticated( - GetReauthPurpose(reason))) { - std::move(callback).Run(absl::nullopt); - return; - } - - // Request the password. When it is retrieved, ShowPassword() will be called. - const std::string* sort_key = password_id_generator_.TryGetKey(id); - if (!sort_key) { - std::move(callback).Run(absl::nullopt); - return; - } - - if (reason == api::passwords_private::PLAINTEXT_REASON_COPY) { - // In case of copy we don't need to give password back to UI. callback - // will receive either empty string in case of success or null otherwise. - // Copying occurs here so javascript doesn't need plaintext password. - callback = base::BindOnce( - [](PlaintextPasswordCallback callback, - absl::optional<std::u16string> password) { - if (!password) { - std::move(callback).Run(absl::nullopt); - return; - } - ui::ScopedClipboardWriter clipboard_writer( - ui::ClipboardBuffer::kCopyPaste); - clipboard_writer.WriteText(*password); - clipboard_writer.MarkAsConfidential(); - std::move(callback).Run(std::u16string()); - }, - std::move(callback)); - } - - password_manager_presenter_->RequestPlaintextPassword( - *sort_key, ConvertPlaintextReason(reason), std::move(callback)); + password_access_authenticator_.EnsureUserIsAuthenticated( + GetReauthPurpose(reason), + base::BindOnce( + &PasswordsPrivateDelegateImpl::OnRequestPlaintextPasswordAuthResult, + weak_ptr_factory_.GetWeakPtr(), id, reason, std::move(callback))); } -bool PasswordsPrivateDelegateImpl::OsReauthCall( - password_manager::ReauthPurpose purpose) { +void PasswordsPrivateDelegateImpl::OsReauthCall( + password_manager::ReauthPurpose purpose, + password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { #if defined(OS_WIN) DCHECK(web_contents_); - return password_manager_util_win::AuthenticateUser( + bool result = password_manager_util_win::AuthenticateUser( web_contents_->GetTopLevelNativeWindow(), purpose); + std::move(callback).Run(result); #elif defined(OS_MAC) - return password_manager_util_mac::AuthenticateUser(purpose); + bool result = password_manager_util_mac::AuthenticateUser(purpose); + std::move(callback).Run(result); #elif BUILDFLAG(IS_CHROMEOS_ASH) const bool user_cannot_manually_enter_password = !chromeos::password_visibility::AccountHasUserFacingPassword( chromeos::ProfileHelper::Get() ->GetUserByProfile(profile_) ->GetAccountId()); - if (user_cannot_manually_enter_password) - return true; + if (user_cannot_manually_enter_password) { + std::move(callback).Run(true); + return; + } ash::quick_unlock::QuickUnlockStorage* quick_unlock_storage = ash::quick_unlock::QuickUnlockFactory::GetForProfile(profile_); const ash::quick_unlock::AuthToken* auth_token = quick_unlock_storage->GetAuthToken(); - if (!auth_token || !auth_token->GetAge()) - return false; + if (!auth_token || !auth_token->GetAge()) { + std::move(callback).Run(false); + return; + } const base::TimeDelta auth_token_lifespan = (purpose == password_manager::ReauthPurpose::EXPORT) ? kExportPasswordsAuthTokenLifetime : kShowPasswordAuthTokenLifetime; - return auth_token->GetAge() <= auth_token_lifespan; + std::move(callback).Run(auth_token->GetAge() <= auth_token_lifespan); #else - return true; + std::move(callback).Run(true); #endif } @@ -455,7 +432,7 @@ void PasswordsPrivateDelegateImpl::ImportPasswords( } void PasswordsPrivateDelegateImpl::ExportPasswords( - base::OnceCallback<void(const std::string&)> callback, + base::OnceCallback<void(const std::string&)> accepted_callback, content::WebContents* web_contents) { // Save |web_contents| so that it can be used later when OsReauthCall() is // called. Note: This is safe because the |web_contents| is used before @@ -463,15 +440,11 @@ void PasswordsPrivateDelegateImpl::ExportPasswords( // TODO(crbug.com/495290): Pass the native window directly to the // reauth-handling code. web_contents_ = web_contents; - if (!password_access_authenticator_.ForceUserReauthentication( - password_manager::ReauthPurpose::EXPORT)) { - std::move(callback).Run(kReauthenticationFailed); - return; - } - - password_manager_porter_->set_web_contents(web_contents); - bool accepted = password_manager_porter_->Store(); - std::move(callback).Run(accepted ? std::string() : kExportInProgress); + password_access_authenticator_.ForceUserReauthentication( + password_manager::ReauthPurpose::EXPORT, + base::BindOnce(&PasswordsPrivateDelegateImpl::OnExportPasswordsAuthResult, + weak_ptr_factory_.GetWeakPtr(), + std::move(accepted_callback), web_contents)); } void PasswordsPrivateDelegateImpl::CancelExportPasswords() { @@ -525,14 +498,12 @@ void PasswordsPrivateDelegateImpl::GetPlaintextInsecurePassword( // TODO(crbug.com/495290): Pass the native window directly to the // reauth-handling code. web_contents_ = web_contents; - if (!password_access_authenticator_.EnsureUserIsAuthenticated( - GetReauthPurpose(reason))) { - std::move(callback).Run(absl::nullopt); - return; - } - - std::move(callback).Run(password_check_delegate_.GetPlaintextInsecurePassword( - std::move(credential))); + password_access_authenticator_.EnsureUserIsAuthenticated( + GetReauthPurpose(reason), + base::BindOnce(&PasswordsPrivateDelegateImpl:: + OnGetPlaintextInsecurePasswordAuthResult, + weak_ptr_factory_.GetWeakPtr(), std::move(credential), + reason, std::move(callback))); } bool PasswordsPrivateDelegateImpl::ChangeInsecureCredential( @@ -576,6 +547,76 @@ void PasswordsPrivateDelegateImpl::OnPasswordsExportProgress( } } +void PasswordsPrivateDelegateImpl::OnRequestPlaintextPasswordAuthResult( + int id, + api::passwords_private::PlaintextReason reason, + PlaintextPasswordCallback callback, + bool authenticated) { + if (!authenticated) { + std::move(callback).Run(absl::nullopt); + return; + } + + // Request the password. When it is retrieved, ShowPassword() will be called. + const std::string* sort_key = password_id_generator_.TryGetKey(id); + if (!sort_key) { + std::move(callback).Run(absl::nullopt); + return; + } + + if (reason == api::passwords_private::PLAINTEXT_REASON_COPY) { + // In case of copy we don't need to give password back to UI. callback + // will receive either empty string in case of success or null otherwise. + // Copying occurs here so javascript doesn't need plaintext password. + callback = base::BindOnce( + [](PlaintextPasswordCallback callback, + absl::optional<std::u16string> password) { + if (!password) { + std::move(callback).Run(absl::nullopt); + return; + } + ui::ScopedClipboardWriter clipboard_writer( + ui::ClipboardBuffer::kCopyPaste); + clipboard_writer.WriteText(*password); + clipboard_writer.MarkAsConfidential(); + std::move(callback).Run(std::u16string()); + }, + std::move(callback)); + } + + password_manager_presenter_->RequestPlaintextPassword( + *sort_key, ConvertPlaintextReason(reason), std::move(callback)); +} + +void PasswordsPrivateDelegateImpl::OnExportPasswordsAuthResult( + base::OnceCallback<void(const std::string&)> accepted_callback, + content::WebContents* web_contents, + bool authenticated) { + if (!authenticated) { + std::move(accepted_callback).Run(kReauthenticationFailed); + return; + } + + password_manager_porter_->set_web_contents(web_contents); + bool accepted = password_manager_porter_->Store(); + std::move(accepted_callback) + .Run(accepted ? std::string() : kExportInProgress); +} + +void PasswordsPrivateDelegateImpl::OnGetPlaintextInsecurePasswordAuthResult( + api::passwords_private::InsecureCredential credential, + api::passwords_private::PlaintextReason reason, + PlaintextInsecurePasswordCallback callback, + bool authenticated) { + if (!authenticated) { + std::move(callback).Run(absl::nullopt); + return; + } + + std::move(callback).Run(password_check_delegate_.GetPlaintextInsecurePassword( + std::move(credential))); +} + void PasswordsPrivateDelegateImpl::OnAccountStorageOptInStateChanged() { PasswordsPrivateEventRouter* router = PasswordsPrivateEventRouterFactory::GetForProfile(profile_); diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h index 76fa8b34935..55bb2352b64 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h @@ -43,6 +43,11 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, public PasswordUIView { public: explicit PasswordsPrivateDelegateImpl(Profile* profile); + + PasswordsPrivateDelegateImpl(const PasswordsPrivateDelegateImpl&) = delete; + PasswordsPrivateDelegateImpl& operator=(const PasswordsPrivateDelegateImpl&) = + delete; + ~PasswordsPrivateDelegateImpl() override; // PasswordsPrivateDelegate implementation. @@ -61,8 +66,9 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, void MovePasswordsToAccount(const std::vector<int>& ids, content::WebContents* web_contents) override; void ImportPasswords(content::WebContents* web_contents) override; - void ExportPasswords(base::OnceCallback<void(const std::string&)> accepted, - content::WebContents* web_contents) override; + void ExportPasswords( + base::OnceCallback<void(const std::string&)> accepted_callback, + content::WebContents* web_contents) override; void CancelExportPasswords() override; api::passwords_private::ExportProgressStatus GetExportProgressStatus() override; @@ -135,11 +141,36 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, void OnPasswordsExportProgress(password_manager::ExportProgressStatus status, const std::string& folder_name); + // Callback for RequestPlaintextPassword() after authentication check. + void OnRequestPlaintextPasswordAuthResult( + int id, + api::passwords_private::PlaintextReason reason, + PlaintextPasswordCallback callback, + bool authenticated); + + // Callback for ExportPasswords() after authentication check. + void OnExportPasswordsAuthResult( + base::OnceCallback<void(const std::string&)> accepted_callback, + content::WebContents* web_contents, + bool authenticated); + + // Callback for GetPlaintextInsecurePassword() after authentication check. + void OnGetPlaintextInsecurePasswordAuthResult( + api::passwords_private::InsecureCredential credential, + api::passwords_private::PlaintextReason reason, + PlaintextInsecurePasswordCallback callback, + bool authenticated); + void OnAccountStorageOptInStateChanged(); - // Triggers an OS-dependent UI to present OS account login challenge and - // returns true if the user passed that challenge. - bool OsReauthCall(password_manager::ReauthPurpose purpose); + // Decides whether an authentication check is successful. Passes the result + // to |callback|. True indicates that no extra work is needed. False + // indicates that OS-dependent UI to present OS account login challenge + // should be shown. + void OsReauthCall( + password_manager::ReauthPurpose purpose, + password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback); // Not owned by this class. Profile* profile_; @@ -192,8 +223,6 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, content::WebContents* web_contents_; base::WeakPtrFactory<PasswordsPrivateDelegateImpl> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateDelegateImpl); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc index 85e4a9e92bb..35773977d6d 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl_unittest.cc @@ -120,6 +120,9 @@ class PasswordEventObserver // The observer will only listen to events with the |event_name|. explicit PasswordEventObserver(const std::string& event_name); + PasswordEventObserver(const PasswordEventObserver&) = delete; + PasswordEventObserver& operator=(const PasswordEventObserver&) = delete; + ~PasswordEventObserver() override; // Removes |event_args_| from |*this| and returns them. @@ -134,8 +137,6 @@ class PasswordEventObserver // The arguments passed for the last observed event. base::Value event_args_; - - DISALLOW_COPY_AND_ASSIGN(PasswordEventObserver); }; PasswordEventObserver::PasswordEventObserver(const std::string& event_name) @@ -174,6 +175,12 @@ password_manager::PasswordForm CreateSampleForm() { class PasswordsPrivateDelegateImplTest : public testing::Test { public: PasswordsPrivateDelegateImplTest(); + + PasswordsPrivateDelegateImplTest(const PasswordsPrivateDelegateImplTest&) = + delete; + PasswordsPrivateDelegateImplTest& operator=( + const PasswordsPrivateDelegateImplTest&) = delete; + ~PasswordsPrivateDelegateImplTest() override; // Sets up a testing password store and fills it with |forms|. @@ -198,7 +205,6 @@ class PasswordsPrivateDelegateImplTest : public testing::Test { private: base::HistogramTester histogram_tester_; - DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateDelegateImplTest); }; PasswordsPrivateDelegateImplTest::PasswordsPrivateDelegateImplTest() { @@ -379,8 +385,10 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestCopyPasswordCallbackResult) { MockReauthCallback callback; delegate.set_os_reauth_call(callback.Get()); - EXPECT_CALL(callback, Run(ReauthPurpose::COPY_PASSWORD)) - .WillOnce(Return(true)); + EXPECT_CALL(callback, Run(ReauthPurpose::COPY_PASSWORD, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(true); })); MockPlaintextPasswordCallback password_callback; EXPECT_CALL(password_callback, Run(Eq(std::u16string()))); @@ -450,8 +458,10 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestCopyPasswordCallbackResultFail) { MockReauthCallback callback; delegate.set_os_reauth_call(callback.Get()); - EXPECT_CALL(callback, Run(ReauthPurpose::COPY_PASSWORD)) - .WillOnce(Return(false)); + EXPECT_CALL(callback, Run(ReauthPurpose::COPY_PASSWORD, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(false); })); base::Time before_call = test_clipboard_->GetLastModifiedTime(); @@ -482,8 +492,10 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestPassedReauthOnView) { MockReauthCallback callback; delegate.set_os_reauth_call(callback.Get()); - EXPECT_CALL(callback, Run(ReauthPurpose::VIEW_PASSWORD)) - .WillOnce(Return(true)); + EXPECT_CALL(callback, Run(ReauthPurpose::VIEW_PASSWORD, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(true); })); MockPlaintextPasswordCallback password_callback; EXPECT_CALL(password_callback, Run(Eq(u"test"))); @@ -507,8 +519,10 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestFailedReauthOnView) { MockReauthCallback callback; delegate.set_os_reauth_call(callback.Get()); - EXPECT_CALL(callback, Run(ReauthPurpose::VIEW_PASSWORD)) - .WillOnce(Return(false)); + EXPECT_CALL(callback, Run(ReauthPurpose::VIEW_PASSWORD, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(false); })); MockPlaintextPasswordCallback password_callback; EXPECT_CALL(password_callback, Run(Eq(absl::nullopt))); @@ -535,11 +549,17 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestReauthOnExport) { EXPECT_CALL(mock_accepted, Run(std::string())).Times(2); - EXPECT_CALL(callback, Run(ReauthPurpose::EXPORT)).WillOnce(Return(true)); + EXPECT_CALL(callback, Run(ReauthPurpose::EXPORT, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(true); })); delegate.ExportPasswords(mock_accepted.Get(), nullptr); // Export should ignore previous reauthentication results. - EXPECT_CALL(callback, Run(ReauthPurpose::EXPORT)).WillOnce(Return(true)); + EXPECT_CALL(callback, Run(ReauthPurpose::EXPORT, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(true); })); delegate.ExportPasswords(mock_accepted.Get(), nullptr); } @@ -558,7 +578,10 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestReauthFailedOnExport) { MockReauthCallback callback; delegate.set_os_reauth_call(callback.Get()); - EXPECT_CALL(callback, Run(ReauthPurpose::EXPORT)).WillOnce(Return(false)); + EXPECT_CALL(callback, Run(ReauthPurpose::EXPORT, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(false); })); delegate.ExportPasswords(mock_accepted.Get(), nullptr); } @@ -575,8 +598,11 @@ TEST_F(PasswordsPrivateDelegateImplTest, PasswordsPrivateDelegate::PlaintextInsecurePasswordCallback> credential_callback; - EXPECT_CALL(reauth_callback, Run(ReauthPurpose::VIEW_PASSWORD)) - .WillOnce(Return(false)); + EXPECT_CALL(reauth_callback, Run(ReauthPurpose::VIEW_PASSWORD, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(false); })); + EXPECT_CALL(credential_callback, Run(Eq(absl::nullopt))); delegate.GetPlaintextInsecurePassword( @@ -610,8 +636,10 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestReauthOnGetPlaintextCompPassword) { credential_callback; absl::optional<api::passwords_private::InsecureCredential> opt_credential; - EXPECT_CALL(reauth_callback, Run(ReauthPurpose::VIEW_PASSWORD)) - .WillOnce(Return(true)); + EXPECT_CALL(reauth_callback, Run(ReauthPurpose::VIEW_PASSWORD, _)) + .WillOnce(testing::WithArg<1>( + [&](password_manager::PasswordAccessAuthenticator::AuthResultCallback + callback) { std::move(callback).Run(true); })); EXPECT_CALL(credential_callback, Run).WillOnce(MoveArg(&opt_credential)); delegate.GetPlaintextInsecurePassword( diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h index af834e87ef6..125af76f2a6 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h @@ -28,6 +28,11 @@ class PasswordsPrivateEventRouter : public KeyedService { public: static PasswordsPrivateEventRouter* Create( content::BrowserContext* browser_context); + + PasswordsPrivateEventRouter(const PasswordsPrivateEventRouter&) = delete; + PasswordsPrivateEventRouter& operator=(const PasswordsPrivateEventRouter&) = + delete; + ~PasswordsPrivateEventRouter() override; // Notifies listeners of updated passwords. @@ -89,8 +94,6 @@ class PasswordsPrivateEventRouter : public KeyedService { absl::optional<std::vector<base::Value>> cached_saved_password_parameters_; absl::optional<std::vector<base::Value>> cached_password_exception_parameters_; - - DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router_factory.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router_factory.h index 3e1c70a1a2c..87ec6359dbf 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router_factory.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router_factory.h @@ -19,6 +19,11 @@ class PasswordsPrivateEventRouter; class PasswordsPrivateEventRouterFactory : public BrowserContextKeyedServiceFactory { public: + PasswordsPrivateEventRouterFactory( + const PasswordsPrivateEventRouterFactory&) = delete; + PasswordsPrivateEventRouterFactory& operator=( + const PasswordsPrivateEventRouterFactory&) = delete; + // Returns the PasswordsPrivateEventRouter for |profile|, creating it if // it is not yet created. static PasswordsPrivateEventRouter* GetForProfile( @@ -44,8 +49,6 @@ class PasswordsPrivateEventRouterFactory // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; - - DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateEventRouterFactory); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc b/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc index 243fbd01020..e75c3527c47 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/test_passwords_private_delegate.cc @@ -195,9 +195,8 @@ TestPasswordsPrivateDelegate::GetCompromisedCredentials() { // Mar 03 2020 12:00:00 UTC credential.compromised_info->compromise_time = 1583236800000; credential.compromised_info->elapsed_time_since_compromise = - base::UTF16ToUTF8(TimeFormat::Simple(TimeFormat::FORMAT_ELAPSED, - TimeFormat::LENGTH_LONG, - base::TimeDelta::FromDays(3))); + base::UTF16ToUTF8(TimeFormat::Simple( + TimeFormat::FORMAT_ELAPSED, TimeFormat::LENGTH_LONG, base::Days(3))); credential.compromised_info->compromise_type = api::passwords_private::COMPROMISE_TYPE_LEAKED; std::vector<api::passwords_private::InsecureCredential> credentials; @@ -273,9 +272,9 @@ TestPasswordsPrivateDelegate::GetPasswordCheckStatus() { status.already_processed = std::make_unique<int>(5); status.remaining_in_queue = std::make_unique<int>(10); status.elapsed_time_since_last_check = - std::make_unique<std::string>(base::UTF16ToUTF8(TimeFormat::Simple( - TimeFormat::FORMAT_ELAPSED, TimeFormat::LENGTH_SHORT, - base::TimeDelta::FromMinutes(5)))); + std::make_unique<std::string>(base::UTF16ToUTF8( + TimeFormat::Simple(TimeFormat::FORMAT_ELAPSED, + TimeFormat::LENGTH_SHORT, base::Minutes(5)))); return status; } diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc index 08cc1394bd0..33d64f7b98c 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api.cc @@ -51,7 +51,7 @@ bool ignore_user_gesture_for_tests = false; ExtensionFunction::ResponseAction PermissionsContainsFunction::Run() { std::unique_ptr<api::permissions::Contains::Params> params( - api::permissions::Contains::Params::Create(*args_)); + api::permissions::Contains::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::string error; @@ -110,7 +110,7 @@ ExtensionFunction::ResponseAction PermissionsGetAllFunction::Run() { ExtensionFunction::ResponseAction PermissionsRemoveFunction::Run() { std::unique_ptr<api::permissions::Remove::Params> params( - api::permissions::Remove::Params::Create(*args_)); + api::permissions::Remove::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::string error; @@ -202,7 +202,7 @@ ExtensionFunction::ResponseAction PermissionsRequestFunction::Run() { return RespondNow(Error("Could not find an active window.")); std::unique_ptr<api::permissions::Request::Params> params( - api::permissions::Request::Params::Create(*args_)); + api::permissions::Request::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::string error; diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api.h b/chromium/chrome/browser/extensions/api/permissions/permissions_api.h index 551c20ad0ef..6a1bda6cf3b 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api.h +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api.h @@ -56,6 +56,10 @@ class PermissionsRequestFunction : public ExtensionFunction { PermissionsRequestFunction(); + PermissionsRequestFunction(const PermissionsRequestFunction&) = delete; + PermissionsRequestFunction& operator=(const PermissionsRequestFunction&) = + delete; + // FOR TESTS ONLY to bypass the confirmation UI. static void SetAutoConfirmForTests(bool should_proceed); static void ResetAutoConfirmForTests(); @@ -90,8 +94,6 @@ class PermissionsRequestFunction : public ExtensionFunction { // be recorded if and only if the prompt is being bypassed for a test (see // also SetAutoConfirmForTests()). std::unique_ptr<const PermissionSet> prompted_permissions_for_testing_; - - DISALLOW_COPY_AND_ASSIGN(PermissionsRequestFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc index 204dd32362a..cf951eb1787 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_helpers_unittest.cc @@ -67,9 +67,9 @@ TEST(ExtensionPermissionsAPIHelpers, Pack) { // into PermissionSets. TEST(ExtensionPermissionsAPIHelpers, Unpack_Basic) { std::unique_ptr<base::ListValue> apis(new base::ListValue()); - apis->AppendString("tabs"); + apis->Append("tabs"); std::unique_ptr<base::ListValue> origins(new base::ListValue()); - origins->AppendString("http://a.com/*"); + origins->Append("http://a.com/*"); std::unique_ptr<base::DictionaryValue> value(new base::DictionaryValue()); std::unique_ptr<const PermissionSet> permissions; diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc index e2c9ad1ad9c..cc470592c62 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc @@ -99,6 +99,10 @@ bool RunRequestFunction( class PermissionsAPIUnitTest : public ExtensionServiceTestWithInstall { public: PermissionsAPIUnitTest() {} + + PermissionsAPIUnitTest(const PermissionsAPIUnitTest&) = delete; + PermissionsAPIUnitTest& operator=(const PermissionsAPIUnitTest&) = delete; + ~PermissionsAPIUnitTest() override {} Browser* browser() { return browser_.get(); } @@ -156,8 +160,6 @@ class PermissionsAPIUnitTest : public ExtensionServiceTestWithInstall { std::unique_ptr<TestBrowserWindow> browser_window_; std::unique_ptr<Browser> browser_; - - DISALLOW_COPY_AND_ASSIGN(PermissionsAPIUnitTest); }; TEST_F(PermissionsAPIUnitTest, Contains) { diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc b/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc index 1e9e120c057..61e14dea734 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_apitest.cc @@ -48,7 +48,9 @@ class ExperimentalApiTest : public ExtensionApiTest { class PermissionsApiTest : public ExtensionApiTest { public: - PermissionsApiTest() = default; + public: + explicit PermissionsApiTest(ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) {} ~PermissionsApiTest() override = default; PermissionsApiTest(const PermissionsApiTest&) = delete; PermissionsApiTest& operator=(const PermissionsApiTest&) = delete; @@ -63,23 +65,16 @@ class PermissionsApiTestWithContextType : public PermissionsApiTest, public testing::WithParamInterface<ContextType> { public: - PermissionsApiTestWithContextType() = default; + PermissionsApiTestWithContextType() : PermissionsApiTest(GetParam()) {} ~PermissionsApiTestWithContextType() override = default; PermissionsApiTestWithContextType(const PermissionsApiTestWithContextType&) = delete; PermissionsApiTestWithContextType& operator=( const PermissionsApiTestWithContextType&) = delete; - - protected: - bool RunTest(const char* extension_name) { - return RunExtensionTest( - extension_name, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; IN_PROC_BROWSER_TEST_P(PermissionsApiTestWithContextType, PermissionsFail) { - ASSERT_TRUE(RunTest("permissions/disabled")) << message_; + ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_; // Since the experimental APIs require a flag, this will fail even though // it's enabled. @@ -100,7 +95,8 @@ IN_PROC_BROWSER_TEST_P(PermissionsApiTestWithContextType, // function that will not be graduating soon, and does not require a // tab id as an argument. So, we need the tab permission to get // a tab id. - ASSERT_TRUE(RunTest("permissions/experimental_disabled")) << message_; + ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled")) + << message_; } // TODO(crbug/1065399): Flaky on ChromeOS and Linux non-dbg builds. @@ -147,7 +143,7 @@ IN_PROC_BROWSER_TEST_P(PermissionsApiTestWithContextType, PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); ASSERT_TRUE(StartEmbeddedTestServer()); - EXPECT_TRUE(RunTest("permissions/optional")) << message_; + EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_; } // Tests that the optional permissions API works correctly. @@ -158,7 +154,7 @@ IN_PROC_BROWSER_TEST_P(PermissionsApiTestWithContextType, PermissionsRequestFunction::SetAutoConfirmForTests(true); PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); ASSERT_TRUE(StartEmbeddedTestServer()); - EXPECT_TRUE(RunTest("permissions/optional")) << message_; + EXPECT_TRUE(RunExtensionTest("permissions/optional")) << message_; } // Test that denying the optional permissions confirmation dialog works. @@ -186,7 +182,7 @@ IN_PROC_BROWSER_TEST_P(PermissionsApiTestWithContextType, OptionalPermissionsGesture) { PermissionsRequestFunction::SetIgnoreUserGestureForTests(false); ASSERT_TRUE(StartEmbeddedTestServer()); - EXPECT_TRUE(RunTest("permissions/optional_gesture")) << message_; + EXPECT_TRUE(RunExtensionTest("permissions/optional_gesture")) << message_; } // Tests that the user gesture is retained in the permissions.request function @@ -262,7 +258,7 @@ IN_PROC_BROWSER_TEST_F(PermissionsApiTest, FileLoad) { IN_PROC_BROWSER_TEST_P(PermissionsApiTestWithContextType, HostSubsets) { PermissionsRequestFunction::SetAutoConfirmForTests(true); PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); - EXPECT_TRUE(RunTest("permissions/host_subsets")) << message_; + EXPECT_TRUE(RunExtensionTest("permissions/host_subsets")) << message_; } // Tests that requesting an optional permission from a background page, with diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc index c17a62677b5..4d9cd07c724 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc +++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.cc @@ -149,7 +149,7 @@ PlatformKeysInternalSelectClientCertificatesFunction::Run() { #endif // BUILDFLAG(IS_CHROMEOS_LACROS) std::unique_ptr<api_pki::SelectClientCertificates::Params> params( - api_pki::SelectClientCertificates::Params::Create(*args_)); + api_pki::SelectClientCertificates::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); chromeos::ExtensionPlatformKeysService* service = @@ -274,7 +274,7 @@ PlatformKeysInternalGetPublicKeyFunction:: ExtensionFunction::ResponseAction PlatformKeysInternalGetPublicKeyFunction::Run() { std::unique_ptr<api_pki::GetPublicKey::Params> params( - api_pki::GetPublicKey::Params::Create(*args_)); + api_pki::GetPublicKey::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::string error = ValidateCrosapi( @@ -332,7 +332,7 @@ PlatformKeysInternalGetPublicKeyBySpkiFunction::Run() { #endif // BUILDFLAG(IS_CHROMEOS_LACROS) std::unique_ptr<api_pki::GetPublicKeyBySpki::Params> params( - api_pki::GetPublicKeyBySpki::Params::Create(*args_)); + api_pki::GetPublicKeyBySpki::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const auto& public_key_spki_der = params->public_key_spki_der; @@ -379,7 +379,7 @@ ExtensionFunction::ResponseAction PlatformKeysInternalSignFunction::Run() { #endif // BUILDFLAG(IS_CHROMEOS_LACROS) std::unique_ptr<api_pki::Sign::Params> params( - api_pki::Sign::Params::Create(*args_)); + api_pki::Sign::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); absl::optional<chromeos::platform_keys::TokenId> platform_keys_token_id; @@ -471,7 +471,7 @@ PlatformKeysVerifyTLSServerCertificateFunction::Run() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::unique_ptr<api_pk::VerifyTLSServerCertificate::Params> params( - api_pk::VerifyTLSServerCertificate::Params::Create(*args_)); + api_pk::VerifyTLSServerCertificate::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); VerifyTrustAPI::GetFactoryInstance() diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc index 296a1dacd73..dc2fbeccadc 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc +++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_apitest_nss.cc @@ -51,6 +51,9 @@ class PlatformKeysTest : public PlatformKeysTestBase { key_permission_policy_(key_permission_policy), user_client_cert_slot_(user_client_cert_slot) {} + PlatformKeysTest(const PlatformKeysTest&) = delete; + PlatformKeysTest& operator=(const PlatformKeysTest&) = delete; + void SetUpOnMainThread() override { if (!IsPreTest()) { // Set up the private slot before @@ -234,8 +237,6 @@ class PlatformKeysTest : public PlatformKeysTestBase { const bool key_permission_policy_; const UserClientCertSlot user_client_cert_slot_; crypto::ScopedTestNSSDB user_private_slot_db_; - - DISALLOW_COPY_AND_ASSIGN(PlatformKeysTest); }; class TestSelectDelegate diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc index db413fbb8e1..2d853685a69 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc +++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.cc @@ -59,22 +59,24 @@ void PlatformKeysTestBase::SetUp() { base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir); embedded_test_server()->ServeFilesFromDirectory(test_data_dir); - embedded_test_server()->RegisterRequestHandler(base::BindRepeating( + net::EmbeddedTestServer::ServerCertificateConfig gaia_cert_config; + gaia_cert_config.dns_names = {GaiaUrls::GetInstance()->gaia_url().host()}; + gaia_server_.SetSSLConfig(gaia_cert_config); + gaia_server_.RegisterRequestHandler(base::BindRepeating( &FakeGaia::HandleRequest, base::Unretained(&fake_gaia_))); - // Don't spin up the IO thread yet since no threads are allowed while - // spawning sandbox host process. See crbug.com/322732. - ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); - - // Start https wrapper here so that the URLs can be pointed at it in - // SetUpCommandLine(). - ASSERT_TRUE(gaia_https_forwarder_.Initialize( - GaiaUrls::GetInstance()->gaia_url().host(), - embedded_test_server()->base_url())); + // Initialize the server to allocate a port, so that URLs can be pointed at it + // in SetUpCommandLine(). Don't spin up the IO thread yet since no threads are + // allowed while spawning sandbox host process. See crbug.com/322732. + ASSERT_TRUE(gaia_server_.InitializeAndListen()); chromeos::platform_keys::PlatformKeysServiceFactory::GetInstance() ->SetTestingMode(true); + if (system_token_status() == SystemTokenStatus::EXISTS) { + CreateTestSystemSlot(); + } + extensions::MixinBasedExtensionApiTest::SetUp(); } @@ -84,7 +86,8 @@ void PlatformKeysTestBase::SetUpCommandLine(base::CommandLine* command_line) { policy::AffiliationTestHelper::AppendCommandLineSwitchesForLoginManager( command_line); - const GURL gaia_url = gaia_https_forwarder_.GetURLForSSLHost(std::string()); + const GURL gaia_url = + gaia_server_.GetURL(GaiaUrls::GetInstance()->gaia_url().host(), "/"); command_line->AppendSwitchASCII(::switches::kGaiaUrl, gaia_url.spec()); command_line->AppendSwitchASCII(::switches::kLsoUrl, gaia_url.spec()); command_line->AppendSwitchASCII(::switches::kGoogleApisUrl, gaia_url.spec()); @@ -133,7 +136,8 @@ void PlatformKeysTestBase::SetUpOnMainThread() { host_resolver()->AddRule("*", "127.0.0.1"); // Start the accept thread as the sandbox host process has already been // spawned. - embedded_test_server()->StartAcceptingConnections(); + ASSERT_TRUE(embedded_test_server()->Start()); + gaia_server_.StartAcceptingConnections(); FakeGaia::AccessTokenInfo token_info; token_info.scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth); @@ -160,10 +164,14 @@ void PlatformKeysTestBase::SetUpOnMainThread() { if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - content::GetIOThreadTaskRunner({})->PostTask( + // Call specializations of the virtual method that configures the created + // system slot. + content::GetIOThreadTaskRunner({})->PostTaskAndReply( FROM_HERE, - base::BindOnce(&PlatformKeysTestBase::SetUpTestSystemSlotOnIO, - base::Unretained(this), loop.QuitClosure())); + base::BindOnce(&PlatformKeysTestBase::PrepareTestSystemSlotOnIO, + base::Unretained(this), + base::Unretained(test_system_slot_.get())), + loop.QuitClosure()); loop.Run(); } @@ -178,10 +186,11 @@ void PlatformKeysTestBase::TearDownOnMainThread() { if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - content::GetIOThreadTaskRunner({})->PostTask( + content::GetIOThreadTaskRunner({})->PostTaskAndReply( FROM_HERE, base::BindOnce(&PlatformKeysTestBase::TearDownTestSystemSlotOnIO, - base::Unretained(this), loop.QuitClosure())); + base::Unretained(this)), + loop.QuitClosure()); loop.Run(); } EXPECT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete()); @@ -199,7 +208,7 @@ bool PlatformKeysTestBase::TestExtension(const std::string& page_url) { Browser* const browser = CreateBrowser(profile()); extensions::ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser, GURL(page_url)); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser, GURL(page_url))); if (!catcher.GetNextResult()) { message_ = catcher.message(); @@ -212,21 +221,12 @@ bool PlatformKeysTestBase::IsPreTest() { return content::IsPreTest(); } -void PlatformKeysTestBase::SetUpTestSystemSlotOnIO( - base::OnceClosure done_callback) { - test_system_slot_ = std::make_unique<crypto::ScopedTestSystemNSSKeySlot>(); +void PlatformKeysTestBase::CreateTestSystemSlot() { + test_system_slot_ = std::make_unique<crypto::ScopedTestSystemNSSKeySlot>( + /*simulate_token_loader=*/false); ASSERT_TRUE(test_system_slot_->ConstructedSuccessfully()); - - PrepareTestSystemSlotOnIO(test_system_slot_.get()); - - content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, - std::move(done_callback)); } -void PlatformKeysTestBase::TearDownTestSystemSlotOnIO( - base::OnceClosure done_callback) { +void PlatformKeysTestBase::TearDownTestSystemSlotOnIO() { test_system_slot_.reset(); - - content::GetUIThreadTaskRunner({})->PostTask(FROM_HERE, - std::move(done_callback)); } diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.h b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.h index 8882bcc1fbd..e68437f47bf 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.h +++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_test_base.h @@ -8,13 +8,13 @@ #include <memory> #include "base/macros.h" -#include "chrome/browser/ash/login/test/https_forwarder.h" #include "chrome/browser/ash/policy/core/device_policy_cros_browser_test.h" #include "chrome/browser/extensions/mixin_based_extension_apitest.h" #include "chromeos/tpm/stub_install_attributes.h" #include "components/account_id/account_id.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "google_apis/gaia/fake_gaia.h" +#include "net/test/embedded_test_server/embedded_test_server.h" namespace crypto { class ScopedTestSystemNSSKeySlot; @@ -39,6 +39,10 @@ class PlatformKeysTestBase : public extensions::MixinBasedExtensionApiTest { PlatformKeysTestBase(SystemTokenStatus system_token_status, EnrollmentStatus enrollment_status, UserStatus user_status); + + PlatformKeysTestBase(const PlatformKeysTestBase&) = delete; + PlatformKeysTestBase& operator=(const PlatformKeysTestBase&) = delete; + ~PlatformKeysTestBase() override; protected: @@ -86,8 +90,11 @@ class PlatformKeysTestBase : public extensions::MixinBasedExtensionApiTest { bool IsPreTest(); private: - void SetUpTestSystemSlotOnIO(base::OnceClosure done_callback); - void TearDownTestSystemSlotOnIO(base::OnceClosure done_callback); + // Create test system slot and prepare crypto:: methods to use it when the + // initialization starts. + void CreateTestSystemSlot(); + // Destroy test system slot. + void TearDownTestSystemSlotOnIO(); const SystemTokenStatus system_token_status_; const EnrollmentStatus enrollment_status_; @@ -100,10 +107,8 @@ class PlatformKeysTestBase : public extensions::MixinBasedExtensionApiTest { testing::NiceMock<policy::MockConfigurationPolicyProvider> mock_policy_provider_; FakeGaia fake_gaia_; - chromeos::HTTPSForwarder gaia_https_forwarder_; + net::EmbeddedTestServer gaia_server_{net::EmbeddedTestServer::TYPE_HTTPS}; chromeos::ScopedStubInstallAttributes install_attributes_; - - DISALLOW_COPY_AND_ASSIGN(PlatformKeysTestBase); }; #endif // CHROME_BROWSER_EXTENSIONS_API_PLATFORM_KEYS_PLATFORM_KEYS_TEST_BASE_H_ diff --git a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc index 7e36409277f..e58a291fae3 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc +++ b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.cc @@ -60,10 +60,10 @@ class VerifyTrustAPI::IOPart { struct RequestState { RequestState() {} - std::unique_ptr<net::CertVerifier::Request> request; + RequestState(const RequestState&) = delete; + RequestState& operator=(const RequestState&) = delete; - private: - DISALLOW_COPY_AND_ASSIGN(RequestState); + std::unique_ptr<net::CertVerifier::Request> request; }; // Calls back |callback| with the result and no error. diff --git a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h index 00f46a288db..8d726579aaa 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h +++ b/chromium/chrome/browser/extensions/api/platform_keys/verify_trust_api.h @@ -48,6 +48,10 @@ class VerifyTrustAPI : public BrowserContextKeyedAPI, // Consumers should use the factory instead of this constructor. explicit VerifyTrustAPI(content::BrowserContext* context); + + VerifyTrustAPI(const VerifyTrustAPI&) = delete; + VerifyTrustAPI& operator=(const VerifyTrustAPI&) = delete; + ~VerifyTrustAPI() override; // Verifies the server certificate as described by |params| for the @@ -101,8 +105,6 @@ class VerifyTrustAPI : public BrowserContextKeyedAPI, registry_observation_{this}; base::WeakPtrFactory<VerifyTrustAPI> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(VerifyTrustAPI); }; template <> diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.cc b/chromium/chrome/browser/extensions/api/preference/preference_api.cc index 5e6b27539d2..99dcf92b560 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api.cc +++ b/chromium/chrome/browser/extensions/api/preference/preference_api.cc @@ -282,6 +282,9 @@ class ProtectedContentEnabledTransformer : public PrefTransformerInterface { class PrefMapping { public: + PrefMapping(const PrefMapping&) = delete; + PrefMapping& operator=(const PrefMapping&) = delete; + static PrefMapping* GetInstance() { return base::Singleton<PrefMapping>::get(); } @@ -392,8 +395,6 @@ class PrefMapping { transformers_; std::unique_ptr<PrefTransformerInterface> identity_transformer_; - - DISALLOW_COPY_AND_ASSIGN(PrefMapping); }; } // namespace @@ -663,15 +664,18 @@ PreferenceFunction::~PreferenceFunction() = default; GetPreferenceFunction::~GetPreferenceFunction() = default; ExtensionFunction::ResponseAction GetPreferenceFunction::Run() { - std::string pref_key; - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key)); - base::DictionaryValue* details = nullptr; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &details)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 2); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); + EXTENSION_FUNCTION_VALIDATE(args()[1].is_dict()); + + const std::string& pref_key = args()[0].GetString(); + const base::Value& details = args()[1]; bool incognito = false; - if (details->HasKey(extensions::preference_api_constants::kIncognitoKey)) - EXTENSION_FUNCTION_VALIDATE(details->GetBoolean( - extensions::preference_api_constants::kIncognitoKey, &incognito)); + if (absl::optional<bool> result = details.FindBoolKey( + extensions::preference_api_constants::kIncognitoKey)) { + incognito = *result; + } // Check incognito access. if (incognito) { @@ -706,14 +710,14 @@ ExtensionFunction::ResponseAction GetPreferenceFunction::Run() { const PrefService::Preference* pref = prefs->FindPreference(browser_pref); CHECK(pref); - auto result = std::make_unique<base::DictionaryValue>(); + base::Value result(base::Value::Type::DICTIONARY); // Retrieve level of control. std::string level_of_control = extensions::preference_helpers::GetLevelOfControl( profile, extension_id(), browser_pref, incognito); - result->SetString(extensions::preference_api_constants::kLevelOfControl, - level_of_control); + result.SetStringKey(extensions::preference_api_constants::kLevelOfControl, + level_of_control); // Retrieve pref value. PrefTransformerInterface* transformer = @@ -727,40 +731,38 @@ ExtensionFunction::ResponseAction GetPreferenceFunction::Run() { pref->name()); return RespondNow(Error(kUnknownErrorDoNotUse)); } - result->Set(extensions::preference_api_constants::kValue, - std::move(transformed_value)); + result.SetKey(extensions::preference_api_constants::kValue, + base::Value::FromUniquePtrValue(std::move(transformed_value))); // Retrieve incognito status. if (incognito) { ExtensionPrefs* ep = ExtensionPrefs::Get(browser_context()); - result->SetBoolean(extensions::preference_api_constants::kIncognitoSpecific, - ep->HasIncognitoPrefValue(browser_pref)); + result.SetBoolKey(extensions::preference_api_constants::kIncognitoSpecific, + ep->HasIncognitoPrefValue(browser_pref)); } - return RespondNow( - OneArgument(base::Value::FromUniquePtrValue(std::move(result)))); + return RespondNow(OneArgument(std::move(result))); } SetPreferenceFunction::~SetPreferenceFunction() = default; ExtensionFunction::ResponseAction SetPreferenceFunction::Run() { - std::string pref_key; - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key)); - base::DictionaryValue* details = nullptr; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &details)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 2); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); + EXTENSION_FUNCTION_VALIDATE(args()[1].is_dict()); - base::Value* value = nullptr; - EXTENSION_FUNCTION_VALIDATE( - details->Get(extensions::preference_api_constants::kValue, &value)); + std::string pref_key = args()[0].GetString(); + const base::Value& details = args()[1]; - ExtensionPrefsScope scope = kExtensionPrefsScopeRegular; - if (details->HasKey(extensions::preference_api_constants::kScopeKey)) { - std::string scope_str; - EXTENSION_FUNCTION_VALIDATE(details->GetString( - extensions::preference_api_constants::kScopeKey, &scope_str)); + const base::Value* value = + details.FindKey(extensions::preference_api_constants::kValue); + EXTENSION_FUNCTION_VALIDATE(value); + ExtensionPrefsScope scope = kExtensionPrefsScopeRegular; + if (const std::string* scope_str = details.FindStringKey( + extensions::preference_api_constants::kScopeKey)) { EXTENSION_FUNCTION_VALIDATE( - extensions::preference_helpers::StringToScope(scope_str, &scope)); + extensions::preference_helpers::StringToScope(*scope_str, &scope)); } // Check incognito scope. @@ -864,19 +866,18 @@ ExtensionFunction::ResponseAction SetPreferenceFunction::Run() { ClearPreferenceFunction::~ClearPreferenceFunction() = default; ExtensionFunction::ResponseAction ClearPreferenceFunction::Run() { - std::string pref_key; - EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &pref_key)); - base::DictionaryValue* details = nullptr; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &details)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 2); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_string()); + EXTENSION_FUNCTION_VALIDATE(args()[1].is_dict()); - ExtensionPrefsScope scope = kExtensionPrefsScopeRegular; - if (details->HasKey(extensions::preference_api_constants::kScopeKey)) { - std::string scope_str; - EXTENSION_FUNCTION_VALIDATE(details->GetString( - extensions::preference_api_constants::kScopeKey, &scope_str)); + std::string pref_key = args()[0].GetString(); + const base::Value& details = args()[1]; + ExtensionPrefsScope scope = kExtensionPrefsScopeRegular; + if (const std::string* scope_str = details.FindStringKey( + extensions::preference_api_constants::kScopeKey)) { EXTENSION_FUNCTION_VALIDATE( - extensions::preference_helpers::StringToScope(scope_str, &scope)); + extensions::preference_helpers::StringToScope(*scope_str, &scope)); } // Check incognito scope. diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.h b/chromium/chrome/browser/extensions/api/preference/preference_api.h index 404df5ece07..33651a1ed4f 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api.h +++ b/chromium/chrome/browser/extensions/api/preference/preference_api.h @@ -33,6 +33,10 @@ class ExtensionPrefs; class PreferenceEventRouter : public ProfileObserver { public: explicit PreferenceEventRouter(Profile* profile); + + PreferenceEventRouter(const PreferenceEventRouter&) = delete; + PreferenceEventRouter& operator=(const PreferenceEventRouter&) = delete; + ~PreferenceEventRouter() override; private: @@ -53,8 +57,6 @@ class PreferenceEventRouter : public ProfileObserver { base::ScopedMultiSourceObservation<Profile, ProfileObserver> observed_profiles_{this}; - - DISALLOW_COPY_AND_ASSIGN(PreferenceEventRouter); }; // The class containing the implementation for extension-controlled preference @@ -108,6 +110,10 @@ class PreferenceAPI : public PreferenceAPIBase, public ContentSettingsStore::Observer { public: explicit PreferenceAPI(content::BrowserContext* context); + + PreferenceAPI(const PreferenceAPI&) = delete; + PreferenceAPI& operator=(const PreferenceAPI&) = delete; + ~PreferenceAPI() override; // KeyedService implementation. @@ -148,8 +154,6 @@ class PreferenceAPI : public PreferenceAPIBase, // Created lazily upon OnListenerAdded. std::unique_ptr<PreferenceEventRouter> preference_event_router_; - - DISALLOW_COPY_AND_ASSIGN(PreferenceAPI); }; class PrefTransformerInterface { diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc b/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc index 43d821baf49..ec79d5806ff 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc +++ b/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc @@ -47,6 +47,10 @@ class TestPreferenceAPI : public PreferenceAPIBase { ContentSettingsService* content_settings) : test_extension_prefs_(test_extension_prefs), content_settings_(content_settings) {} + + TestPreferenceAPI(const TestPreferenceAPI&) = delete; + TestPreferenceAPI& operator=(const TestPreferenceAPI&) = delete; + ~TestPreferenceAPI() {} private: @@ -63,8 +67,6 @@ class TestPreferenceAPI : public PreferenceAPIBase { TestExtensionPrefs* test_extension_prefs_; ContentSettingsService* content_settings_; - - DISALLOW_COPY_AND_ASSIGN(TestPreferenceAPI); }; class ExtensionControlledPrefsTest : public PrefsPrepopulatedTestBase { diff --git a/chromium/chrome/browser/extensions/api/preference/preference_helpers.cc b/chromium/chrome/browser/extensions/api/preference/preference_helpers.cc index e60c6e0ce50..e8bb7da3a55 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_helpers.cc +++ b/chromium/chrome/browser/extensions/api/preference/preference_helpers.cc @@ -112,12 +112,13 @@ void DispatchEventToExtensions(Profile* profile, extension->permissions_data()->HasAPIPermission(permission) && (!incognito || util::IsIncognitoEnabled(extension->id(), profile))) { // Inject level of control key-value. - base::DictionaryValue* dict; - bool rv = args->GetDictionary(0, &dict); - DCHECK(rv); + base::Value::ListView args_list = args->GetList(); + DCHECK(!args_list.empty()); + DCHECK(args_list[0].is_dict()); + std::string level_of_control = GetLevelOfControl(profile, extension->id(), browser_pref, incognito); - dict->SetString(kLevelOfControlKey, level_of_control); + args_list[0].SetStringKey(kLevelOfControlKey, level_of_control); // If the extension is in incognito split mode, // a) incognito pref changes are visible only to the incognito tabs @@ -147,9 +148,9 @@ void DispatchEventToExtensions(Profile* profile, } } - std::unique_ptr<base::ListValue> args_copy = args->CreateDeepCopy(); + base::Value args_copy = args->Clone(); auto event = std::make_unique<Event>(histogram_value, event_name, - std::move(*args_copy).TakeList(), + std::move(args_copy).TakeList(), restrict_to_profile); router->DispatchEventToExtension(extension->id(), std::move(event)); } diff --git a/chromium/chrome/browser/extensions/api/printing/print_job_submitter.cc b/chromium/chrome/browser/extensions/api/printing/print_job_submitter.cc index f266659bb47..63ad34c5c7c 100644 --- a/chromium/chrome/browser/extensions/api/printing/print_job_submitter.cc +++ b/chromium/chrome/browser/extensions/api/printing/print_job_submitter.cc @@ -12,7 +12,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/values.h" -#include "build/chromeos_buildflags.h" #include "chrome/browser/chromeos/printing/cups_printers_manager.h" #include "chrome/browser/extensions/api/printing/print_job_controller.h" #include "chrome/browser/extensions/api/printing/printing_api_utils.h" @@ -22,6 +21,7 @@ #include "chrome/browser/ui/native_window_tracker.h" #include "chrome/common/pref_names.h" #include "chrome/services/printing/public/mojom/pdf_flattener.mojom.h" +#include "chrome/services/printing/public/mojom/printing_service.mojom.h" #include "chromeos/crosapi/mojom/local_printer.mojom.h" #include "chromeos/printing/printer_configuration.h" #include "components/prefs/pref_service.h" diff --git a/chromium/chrome/browser/extensions/api/printing/print_job_submitter.h b/chromium/chrome/browser/extensions/api/printing/print_job_submitter.h index 7bc32163b7c..e9d2157cdf2 100644 --- a/chromium/chrome/browser/extensions/api/printing/print_job_submitter.h +++ b/chromium/chrome/browser/extensions/api/printing/print_job_submitter.h @@ -12,6 +12,7 @@ #include "base/callback.h" #include "base/memory/read_only_shared_memory_region.h" #include "base/memory/weak_ptr.h" +#include "build/chromeos_buildflags.h" #include "chrome/common/extensions/api/printing.h" #include "chromeos/crosapi/mojom/local_printer.mojom-forward.h" #include "mojo/public/cpp/bindings/remote.h" diff --git a/chromium/chrome/browser/extensions/api/printing/printing_api.cc b/chromium/chrome/browser/extensions/api/printing/printing_api.cc index 8dd951ffba0..19d8faf3d76 100644 --- a/chromium/chrome/browser/extensions/api/printing/printing_api.cc +++ b/chromium/chrome/browser/extensions/api/printing/printing_api.cc @@ -20,8 +20,7 @@ PrintingSubmitJobFunction::~PrintingSubmitJobFunction() = default; void PrintingSubmitJobFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { QuotaLimitHeuristic::Config config = { - api::printing::MAX_SUBMIT_JOB_CALLS_PER_MINUTE, - base::TimeDelta::FromMinutes(1)}; + api::printing::MAX_SUBMIT_JOB_CALLS_PER_MINUTE, base::Minutes(1)}; heuristics->push_back(std::make_unique<QuotaService::TimedLimit>( config, std::make_unique<QuotaLimitHeuristic::SingletonBucketMapper>(), "MAX_SUBMIT_JOB_CALLS_PER_MINUTE")); @@ -29,7 +28,7 @@ void PrintingSubmitJobFunction::GetQuotaLimitHeuristics( ExtensionFunction::ResponseAction PrintingSubmitJobFunction::Run() { std::unique_ptr<api::printing::SubmitJob::Params> params( - api::printing::SubmitJob::Params::Create(*args_)); + api::printing::SubmitJob::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); PrintingAPIHandler::Get(browser_context()) ->SubmitJob(ChromeExtensionFunctionDetails(this).GetNativeWindowForUI(), @@ -59,7 +58,7 @@ PrintingCancelJobFunction::~PrintingCancelJobFunction() = default; ExtensionFunction::ResponseAction PrintingCancelJobFunction::Run() { std::unique_ptr<api::printing::CancelJob::Params> params( - api::printing::CancelJob::Params::Create(*args_)); + api::printing::CancelJob::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); absl::optional<std::string> error = PrintingAPIHandler::Get(browser_context()) @@ -90,8 +89,7 @@ PrintingGetPrinterInfoFunction::~PrintingGetPrinterInfoFunction() = default; void PrintingGetPrinterInfoFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { QuotaLimitHeuristic::Config config = { - api::printing::MAX_GET_PRINTER_INFO_CALLS_PER_MINUTE, - base::TimeDelta::FromMinutes(1)}; + api::printing::MAX_GET_PRINTER_INFO_CALLS_PER_MINUTE, base::Minutes(1)}; heuristics->push_back(std::make_unique<QuotaService::TimedLimit>( config, std::make_unique<QuotaLimitHeuristic::SingletonBucketMapper>(), "MAX_GET_PRINTER_INFO_CALLS_PER_MINUTE")); @@ -99,7 +97,7 @@ void PrintingGetPrinterInfoFunction::GetQuotaLimitHeuristics( ExtensionFunction::ResponseAction PrintingGetPrinterInfoFunction::Run() { std::unique_ptr<api::printing::GetPrinterInfo::Params> params( - api::printing::GetPrinterInfo::Params::Create(*args_)); + api::printing::GetPrinterInfo::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); PrintingAPIHandler::Get(browser_context()) ->GetPrinterInfo( diff --git a/chromium/chrome/browser/extensions/api/printing/printing_api_handler_unittest.cc b/chromium/chrome/browser/extensions/api/printing/printing_api_handler_unittest.cc index 9c3169e9f54..d88af50c00d 100644 --- a/chromium/chrome/browser/extensions/api/printing/printing_api_handler_unittest.cc +++ b/chromium/chrome/browser/extensions/api/printing/printing_api_handler_unittest.cc @@ -7,6 +7,7 @@ #include <memory> #include <string> #include <utility> +#include <vector> #include "base/containers/span.h" #include "base/json/json_reader.h" @@ -52,6 +53,9 @@ class PrintingEventObserver : public TestEventRouter::EventObserver { event_router_->AddEventObserver(this); } + PrintingEventObserver(const PrintingEventObserver&) = delete; + PrintingEventObserver& operator=(const PrintingEventObserver&) = delete; + ~PrintingEventObserver() override { event_router_->RemoveEventObserver(this); } @@ -81,8 +85,6 @@ class PrintingEventObserver : public TestEventRouter::EventObserver { // The arguments passed for the last observed event. base::Value event_args_; - - DISALLOW_COPY_AND_ASSIGN(PrintingEventObserver); }; constexpr char kExtensionId[] = "abcdefghijklmnopqrstuvwxyzabcdef"; @@ -172,8 +174,8 @@ std::unique_ptr<api::printing::SubmitJob::Params> ConstructSubmitJobParams( request.job.content_type = content_type; request.document_blob_uuid = std::move(document_blob_uuid); - base::ListValue args; - args.Set(0, request.ToValue()); + std::vector<base::Value> args; + args.emplace_back(base::Value::FromUniquePtrValue(request.ToValue())); return api::printing::SubmitJob::Params::Create(args); } diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.cc b/chromium/chrome/browser/extensions/api/processes/processes_api.cc index 5465a7c346b..608227bf9c7 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.cc @@ -188,11 +188,10 @@ void FillProcessData( //////////////////////////////////////////////////////////////////////////////// ProcessesEventRouter::ProcessesEventRouter(content::BrowserContext* context) - : task_manager::TaskManagerObserver(base::TimeDelta::FromSeconds(1), + : task_manager::TaskManagerObserver(base::Seconds(1), task_manager::REFRESH_TYPE_NONE), browser_context_(context), - listeners_(0) { -} + listeners_(0) {} ProcessesEventRouter::~ProcessesEventRouter() { } @@ -462,7 +461,7 @@ ProcessesEventRouter* ProcessesAPI::processes_event_router() { ExtensionFunction::ResponseAction ProcessesGetProcessIdForTabFunction::Run() { // For this function, the task manager doesn't even need to be running. std::unique_ptr<api::processes::GetProcessIdForTab::Params> params( - api::processes::GetProcessIdForTab::Params::Create(*args_)); + api::processes::GetProcessIdForTab::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); const int tab_id = params->tab_id; @@ -492,7 +491,7 @@ ExtensionFunction::ResponseAction ProcessesTerminateFunction::Run() { // For this function, the task manager doesn't even need to be running. std::unique_ptr<api::processes::Terminate::Params> params( - api::processes::Terminate::Params::Create(*args_)); + api::processes::Terminate::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); child_process_host_id_ = params->process_id; @@ -577,13 +576,12 @@ ProcessesTerminateFunction::TerminateIfAllowed(base::ProcessHandle handle) { ProcessesGetProcessInfoFunction::ProcessesGetProcessInfoFunction() : task_manager::TaskManagerObserver( - base::TimeDelta::FromSeconds(1), - GetRefreshTypesFlagOnlyEssentialData()) { -} + base::Seconds(1), + GetRefreshTypesFlagOnlyEssentialData()) {} ExtensionFunction::ResponseAction ProcessesGetProcessInfoFunction::Run() { std::unique_ptr<api::processes::GetProcessInfo::Params> params( - api::processes::GetProcessInfo::Params::Create(*args_)); + api::processes::GetProcessInfo::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (params->process_ids.as_integer) process_host_ids_.push_back(*params->process_ids.as_integer); diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.h b/chromium/chrome/browser/extensions/api/processes/processes_api.h index 0f389faa2d2..c5e855bae10 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.h +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.h @@ -24,6 +24,10 @@ namespace extensions { class ProcessesEventRouter : public task_manager::TaskManagerObserver { public: explicit ProcessesEventRouter(content::BrowserContext* context); + + ProcessesEventRouter(const ProcessesEventRouter&) = delete; + ProcessesEventRouter& operator=(const ProcessesEventRouter&) = delete; + ~ProcessesEventRouter() override; // Called when an extension process wants to listen to process events. @@ -65,8 +69,6 @@ class ProcessesEventRouter : public task_manager::TaskManagerObserver { // Count of listeners, so we avoid sending updates if no one is interested. int listeners_; - - DISALLOW_COPY_AND_ASSIGN(ProcessesEventRouter); }; //////////////////////////////////////////////////////////////////////////////// @@ -75,6 +77,10 @@ class ProcessesAPI : public BrowserContextKeyedAPI, public EventRouter::Observer { public: explicit ProcessesAPI(content::BrowserContext* context); + + ProcessesAPI(const ProcessesAPI&) = delete; + ProcessesAPI& operator=(const ProcessesAPI&) = delete; + ~ProcessesAPI() override; // BrowserContextKeyedAPI: @@ -104,8 +110,6 @@ class ProcessesAPI : public BrowserContextKeyedAPI, // Created lazily on first access. std::unique_ptr<ProcessesEventRouter> processes_event_router_; - - DISALLOW_COPY_AND_ASSIGN(ProcessesAPI); }; //////////////////////////////////////////////////////////////////////////////// diff --git a/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc b/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc index 745c8c1eca9..7e529269019 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc @@ -18,15 +18,16 @@ class ProcessesApiTest : public extensions::ExtensionApiTest { public: ProcessesApiTest() {} + + ProcessesApiTest(const ProcessesApiTest&) = delete; + ProcessesApiTest& operator=(const ProcessesApiTest&) = delete; + ~ProcessesApiTest() override {} int GetListenersCount() { return extensions::ProcessesAPI::Get(profile())-> processes_event_router()->listeners_; } - - private: - DISALLOW_COPY_AND_ASSIGN(ProcessesApiTest); }; diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api.h b/chromium/chrome/browser/extensions/api/proxy/proxy_api.h index 4cb1d1a302a..53d735ebcb7 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api.h +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api.h @@ -28,6 +28,10 @@ class EventRouterForwarder; class ProxyPrefTransformer : public PrefTransformerInterface { public: ProxyPrefTransformer(); + + ProxyPrefTransformer(const ProxyPrefTransformer&) = delete; + ProxyPrefTransformer& operator=(const ProxyPrefTransformer&) = delete; + ~ProxyPrefTransformer() override; // Implementation of PrefTransformerInterface. @@ -38,9 +42,6 @@ class ProxyPrefTransformer : public PrefTransformerInterface { std::unique_ptr<base::Value> BrowserToExtensionPref( const base::Value* browser_pref, bool is_incognito_profile) override; - - private: - DISALLOW_COPY_AND_ASSIGN(ProxyPrefTransformer); }; // This class observes proxy error events and routes them to the appropriate @@ -48,6 +49,9 @@ class ProxyPrefTransformer : public PrefTransformerInterface { // thread unless otherwise specified. class ProxyEventRouter { public: + ProxyEventRouter(const ProxyEventRouter&) = delete; + ProxyEventRouter& operator=(const ProxyEventRouter&) = delete; + static ProxyEventRouter* GetInstance(); void OnProxyError(EventRouterForwarder* event_router, @@ -64,8 +68,6 @@ class ProxyEventRouter { ProxyEventRouter(); ~ProxyEventRouter(); - - DISALLOW_COPY_AND_ASSIGN(ProxyEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc index c305ecb4f79..bfaaaa620e6 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc @@ -27,6 +27,8 @@ #include "components/proxy_config/proxy_config_dictionary.h" #include "extensions/common/error_utils.h" #include "net/base/data_url.h" +#include "net/base/proxy_server.h" +#include "net/base/proxy_string_util.h" #include "net/proxy_resolution/proxy_config.h" namespace extensions { @@ -169,8 +171,7 @@ bool GetProxyServer(const base::DictionaryValue* proxy_server, proxy_server->GetStringASCII(proxy_api_constants::kProxyConfigRuleScheme, &scheme_string); - net::ProxyServer::Scheme scheme = - net::ProxyServer::GetSchemeFromURI(scheme_string); + net::ProxyServer::Scheme scheme = net::GetSchemeFromUriScheme(scheme_string); if (scheme == net::ProxyServer::SCHEME_INVALID) scheme = default_scheme; @@ -249,7 +250,8 @@ bool GetProxyRulesStringFromExtensionPref( return false; } } - *out = proxy_server[proxy_api_constants::SCHEME_ALL].ToURI(); + *out = net::ProxyServerToProxyUri( + proxy_server[proxy_api_constants::SCHEME_ALL]); return true; } @@ -264,7 +266,7 @@ bool GetProxyRulesStringFromExtensionPref( proxy_pref.append(";"); proxy_pref.append(proxy_api_constants::scheme_name[i]); proxy_pref.append("="); - proxy_pref.append(proxy_server[i].ToURI()); + proxy_pref.append(net::ProxyServerToProxyUri(proxy_server[i])); } } @@ -278,7 +280,7 @@ bool JoinUrlList(const base::ListValue* list, std::string* error, bool* bad_message) { std::string result; - for (size_t i = 0; i < list->GetSize(); ++i) { + for (size_t i = 0; i < list->GetList().size(); ++i) { if (!result.empty()) result.append(joiner); @@ -518,7 +520,7 @@ std::unique_ptr<base::ListValue> TokenizeToStringList( auto out = std::make_unique<base::ListValue>(); base::StringTokenizer entries(in, delims); while (entries.GetNext()) - out->AppendString(entries.token_piece()); + out->Append(entries.token_piece()); return out; } diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc index 3fbd517dedf..7b708a1681a 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers_unittest.cc @@ -13,6 +13,8 @@ #include "chrome/browser/extensions/api/proxy/proxy_api_constants.h" #include "components/proxy_config/proxy_config_dictionary.h" #include "components/proxy_config/proxy_prefs.h" +#include "net/base/proxy_server.h" +#include "net/base/proxy_string_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -280,7 +282,8 @@ TEST(ExtensionProxyApiHelpers, GetProxyServer) { ASSERT_TRUE( GetProxyServer(&proxy_server_dict, net::ProxyServer::SCHEME_HTTP, &created, &error, &bad_message)); - EXPECT_EQ("PROXY proxy_server:80", created.ToPacString()); + EXPECT_EQ("PROXY proxy_server:80", + net::ProxyServerToPacResultElement(created)); EXPECT_FALSE(bad_message); // Test complete case. @@ -289,16 +292,17 @@ TEST(ExtensionProxyApiHelpers, GetProxyServer) { ASSERT_TRUE( GetProxyServer(&proxy_server_dict, net::ProxyServer::SCHEME_HTTP, &created, &error, &bad_message)); - EXPECT_EQ("SOCKS proxy_server:1234", created.ToPacString()); + EXPECT_EQ("SOCKS proxy_server:1234", + net::ProxyServerToPacResultElement(created)); EXPECT_FALSE(bad_message); } TEST(ExtensionProxyApiHelpers, JoinUrlList) { bool bad_message = false; base::ListValue list; - list.AppendString("s1"); - list.AppendString("s2"); - list.AppendString("s3"); + list.Append("s1"); + list.Append("s2"); + list.Append("s3"); std::string out; std::string error; @@ -390,9 +394,9 @@ TEST(ExtensionProxyApiHelpers, CreatePacScriptDictWidthData) { TEST(ExtensionProxyApiHelpers, TokenizeToStringList) { base::ListValue expected; - expected.AppendString("s1"); - expected.AppendString("s2"); - expected.AppendString("s3"); + expected.Append("s1"); + expected.Append("s2"); + expected.Append("s3"); std::unique_ptr<base::ListValue> out(TokenizeToStringList("s1;s2;s3", ";")); EXPECT_EQ(expected, *out); diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc index 96e48ce101f..419d67415a3 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_apitest.cc @@ -32,6 +32,9 @@ class ProxySettingsApiTest : public ExtensionApiTest { public: ProxySettingsApiTest() {} + ProxySettingsApiTest(const ProxySettingsApiTest&) = delete; + ProxySettingsApiTest& operator=(const ProxySettingsApiTest&) = delete; + protected: void ValidateSettings(int expected_mode, const std::string& expected_server, @@ -94,9 +97,6 @@ class ProxySettingsApiTest : public ExtensionApiTest { extensions::ManagementPolicy* GetManagementPolicy() { return ExtensionSystem::Get(profile())->management_policy(); } - - private: - DISALLOW_COPY_AND_ASSIGN(ProxySettingsApiTest); }; // Tests direct connection settings. diff --git a/chromium/chrome/browser/extensions/api/quick_unlock_private/DIR_METADATA b/chromium/chrome/browser/extensions/api/quick_unlock_private/DIR_METADATA new file mode 100644 index 00000000000..704a8962aa0 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/quick_unlock_private/DIR_METADATA @@ -0,0 +1,3 @@ +monorail: { + component: "UI>Settings" +} diff --git a/chromium/chrome/browser/extensions/api/quick_unlock_private/OWNERS b/chromium/chrome/browser/extensions/api/quick_unlock_private/OWNERS new file mode 100644 index 00000000000..965fbf792c1 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/quick_unlock_private/OWNERS @@ -0,0 +1,3 @@ +alemate@chromium.org + +file://chrome/browser/resources/settings/chromeos/OWNERS diff --git a/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.cc b/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.cc new file mode 100644 index 00000000000..0e378a20acf --- /dev/null +++ b/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.cc @@ -0,0 +1,673 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.h" + +#include <algorithm> +#include <string> +#include <utility> + +#include "ash/constants/ash_pref_names.h" +#include "base/bind.h" +#include "base/containers/contains.h" +#include "chrome/browser/ash/login/quick_unlock/auth_token.h" +#include "chrome/browser/ash/login/quick_unlock/fingerprint_storage.h" +#include "chrome/browser/ash/login/quick_unlock/pin_backend.h" +#include "chrome/browser/ash/login/quick_unlock/pin_storage_prefs.h" +#include "chrome/browser/ash/login/quick_unlock/quick_unlock_factory.h" +#include "chrome/browser/ash/login/quick_unlock/quick_unlock_storage.h" +#include "chrome/browser/ash/login/quick_unlock/quick_unlock_utils.h" +#include "chrome/browser/ash/login/users/chrome_user_manager.h" +#include "chrome/browser/ash/profiles/profile_helper.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chromeos/login/auth/extended_authenticator.h" +#include "chromeos/login/auth/user_context.h" +#include "components/prefs/pref_service.h" +#include "content/public/browser/browser_task_traits.h" +#include "content/public/browser/browser_thread.h" +#include "extensions/browser/event_router.h" + +namespace extensions { + +namespace quick_unlock_private = api::quick_unlock_private; +namespace SetModes = quick_unlock_private::SetModes; +namespace GetActiveModes = quick_unlock_private::GetActiveModes; +namespace CheckCredential = quick_unlock_private::CheckCredential; +namespace GetCredentialRequirements = + quick_unlock_private::GetCredentialRequirements; +namespace GetAvailableModes = quick_unlock_private::GetAvailableModes; +namespace OnActiveModesChanged = quick_unlock_private::OnActiveModesChanged; + +using CredentialProblem = quick_unlock_private::CredentialProblem; +using CredentialCheck = quick_unlock_private::CredentialCheck; +using CredentialRequirements = quick_unlock_private::CredentialRequirements; +using QuickUnlockMode = quick_unlock_private::QuickUnlockMode; + +using AuthToken = ash::quick_unlock::AuthToken; +using QuickUnlockModeList = std::vector<QuickUnlockMode>; +using QuickUnlockStorage = ash::quick_unlock::QuickUnlockStorage; + +using ActiveModeCallback = base::OnceCallback<void(const QuickUnlockModeList&)>; + +namespace { + +const char kModesAndCredentialsLengthMismatch[] = + "|modes| and |credentials| must have the same number of elements"; +const char kMultipleModesNotSupported[] = + "At most one quick unlock mode can be active."; +const char kPinDisabledByPolicy[] = "PIN unlock has been disabled by policy"; + +const char kInvalidPIN[] = "Invalid PIN."; +const char kInvalidCredential[] = "Invalid credential."; +const char kInternalError[] = "Internal error."; +const char kWeakCredential[] = "Weak credential."; + +const char kPasswordIncorrect[] = "Incorrect Password."; +const char kAuthTokenExpired[] = "Authentication token expired."; +const char kAuthTokenInvalid[] = "Authentication token invalid."; + +// PINs greater in length than |kMinLengthForWeakPin| will be checked for +// weakness. +constexpr size_t kMinLengthForNonWeakPin = 2U; + +// A list of the most commmonly used PINs, whose digits are not all the same, +// increasing or decreasing. This list is taken from +// www.datagenetics.com/blog/september32012/. +constexpr const char* kMostCommonPins[] = {"1212", "1004", "2000", "6969", + "1122", "1313", "2001", "1010"}; + +// Returns the active set of quick unlock modes. +void ComputeActiveModes(Profile* profile, ActiveModeCallback result) { + user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile); + ash::quick_unlock::PinBackend::GetInstance()->IsSet( + user->GetAccountId(), + base::BindOnce( + [](ActiveModeCallback result, bool is_set) { + QuickUnlockModeList modes; + if (is_set) + modes.push_back(quick_unlock_private::QUICK_UNLOCK_MODE_PIN); + std::move(result).Run(modes); + }, + std::move(result))); +} + +// Returns true if |a| and |b| contain the same elements. The elements do not +// need to be in the same order. +bool AreModesEqual(const QuickUnlockModeList& a, const QuickUnlockModeList& b) { + if (a.size() != b.size()) + return false; + + // This is a slow comparison algorithm, but the number of entries in |a| and + // |b| will always be very low (0-3 items) so it doesn't matter. + for (size_t i = 0; i < a.size(); ++i) { + if (!base::Contains(b, a[i])) + return false; + } + + return true; +} + +bool IsPinNumeric(const std::string& pin) { + return std::all_of(pin.begin(), pin.end(), ::isdigit); +} + +// Reads and sanitizes the pin length policy. +// Returns the minimum and maximum required pin lengths. +// - minimum must be at least 1. +// - maximum must be at least |min_length|, or 0. +std::pair<int, int> GetSanitizedPolicyPinMinMaxLength( + PrefService* pref_service) { + int min_length = std::max( + pref_service->GetInteger(ash::prefs::kPinUnlockMinimumLength), 1); + int max_length = + pref_service->GetInteger(ash::prefs::kPinUnlockMaximumLength); + max_length = max_length > 0 ? std::max(max_length, min_length) : 0; + + DCHECK_GE(min_length, 1); + DCHECK_GE(max_length, 0); + return std::make_pair(min_length, max_length); +} + +// Checks whether a given |pin| has any problems given the PIN min/max policies +// in |pref_service|. Returns CREDENTIAL_PROBLEM_NONE if |pin| has no problems, +// or another CREDENTIAL_PROBLEM_ enum value to indicate the detected problem. +CredentialProblem GetCredentialProblemForPin(const std::string& pin, + PrefService* pref_service) { + int min_length; + int max_length; + std::tie(min_length, max_length) = + GetSanitizedPolicyPinMinMaxLength(pref_service); + + // Check if the PIN is shorter than the minimum specified length. + if (pin.size() < static_cast<size_t>(min_length)) + return CredentialProblem::CREDENTIAL_PROBLEM_TOO_SHORT; + + // If the maximum specified length is zero, there is no maximum length. + // Otherwise check if the PIN is longer than the maximum specified length. + if (max_length != 0 && pin.size() > static_cast<size_t>(max_length)) + return CredentialProblem::CREDENTIAL_PROBLEM_TOO_LONG; + + return CredentialProblem::CREDENTIAL_PROBLEM_NONE; +} + +// Checks if a given |pin| is weak or not. A PIN is considered weak if it: +// a) is on this list - www.datagenetics.com/blog/september32012/ +// b) has all the same digits +// c) each digit is one larger than the previous digit +// d) each digit is one smaller than the previous digit +// Note: A 9 followed by a 0 is not considered increasing, and a 0 followed by +// a 9 is not considered decreasing. +bool IsPinDifficultEnough(const std::string& pin) { + // If the pin length is |kMinLengthForNonWeakPin| or less, there is no need to + // check for same character and increasing pin. + if (pin.size() <= kMinLengthForNonWeakPin) + return true; + + // Check if it is on the list of most common PINs. + if (base::Contains(kMostCommonPins, pin)) + return false; + + // Check for same digits, increasing and decreasing PIN simultaneously. + bool is_same = true; + // TODO(sammiequon): Should longer PINs (5+) be still subjected to this? + bool is_increasing = true; + bool is_decreasing = true; + for (size_t i = 1; i < pin.length(); ++i) { + const char previous = pin[i - 1]; + const char current = pin[i]; + + is_same = is_same && (current == previous); + is_increasing = is_increasing && (current == previous + 1); + is_decreasing = is_decreasing && (current == previous - 1); + } + + // PIN is considered weak if any of these conditions is met. + if (is_same || is_increasing || is_decreasing) + return false; + + return true; +} + +Profile* GetActiveProfile(content::BrowserContext* browser_context) { + Profile* profile = Profile::FromBrowserContext(browser_context); + // When OOBE continues in-session as Furst Run UI, it is still executed + // under Sign-In profile. + if (chromeos::ProfileHelper::IsSigninProfile(profile)) + return ProfileManager::GetPrimaryUserProfile(); + + return profile; +} + +AuthToken* GetActiveProfileAuthToken(content::BrowserContext* browser_context) { + return ash::quick_unlock::QuickUnlockFactory::GetForProfile( + GetActiveProfile(browser_context)) + ->GetAuthToken(); +} + +} // namespace + +// quickUnlockPrivate.getAuthToken + +QuickUnlockPrivateGetAuthTokenFunction::QuickUnlockPrivateGetAuthTokenFunction() + : chrome_details_(this) {} + +QuickUnlockPrivateGetAuthTokenFunction:: + ~QuickUnlockPrivateGetAuthTokenFunction() { + if (extended_authenticator_) + extended_authenticator_->SetConsumer(nullptr); +} + +void QuickUnlockPrivateGetAuthTokenFunction:: + SetAuthenticatorAllocatorForTesting( + const QuickUnlockPrivateGetAuthTokenFunction::AuthenticatorAllocator& + allocator) { + authenticator_allocator_ = allocator; +} + +ExtensionFunction::ResponseAction +QuickUnlockPrivateGetAuthTokenFunction::Run() { + std::unique_ptr<quick_unlock_private::GetAuthToken::Params> params = + quick_unlock_private::GetAuthToken::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params); + + const user_manager::User* const user = + chromeos::ProfileHelper::Get()->GetUserByProfile( + GetActiveProfile(browser_context())); + chromeos::UserContext user_context(*user); + user_context.SetKey(chromeos::Key(params->account_password)); + + // Lazily allocate the authenticator. We do this here, instead of in the ctor, + // so that tests can install a fake. + DCHECK(!extended_authenticator_); + if (authenticator_allocator_) + extended_authenticator_ = authenticator_allocator_.Run(this); + else + extended_authenticator_ = chromeos::ExtendedAuthenticator::Create(this); + + // The extension function needs to stay alive while the authenticator is + // running the password check. Add a ref before the authenticator starts, and + // remove the ref after it invokes one of the OnAuth* callbacks. The PostTask + // call applies ref management to the extended_authenticator_ instance and not + // to the extension function instance, which is why the manual ref management + // is needed. + AddRef(); + + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, + base::BindOnce(&chromeos::ExtendedAuthenticator::AuthenticateToCheck, + extended_authenticator_.get(), user_context, + base::OnceClosure())); + + return RespondLater(); +} + +void QuickUnlockPrivateGetAuthTokenFunction::OnAuthFailure( + const chromeos::AuthFailure& error) { + Respond(Error(kPasswordIncorrect)); + Release(); // Balanced in Run(). +} + +void QuickUnlockPrivateGetAuthTokenFunction::OnAuthSuccess( + const chromeos::UserContext& user_context) { + auto result = std::make_unique<quick_unlock_private::TokenInfo>(); + + Profile* profile = GetActiveProfile(browser_context()); + QuickUnlockStorage* quick_unlock_storage = + ash::quick_unlock::QuickUnlockFactory::GetForProfile(profile); + quick_unlock_storage->MarkStrongAuth(); + result->token = quick_unlock_storage->CreateAuthToken(user_context); + result->lifetime_seconds = AuthToken::kTokenExpirationSeconds; + + // The user has successfully authenticated so we should reset pin/fingerprint + // attempt counts. + quick_unlock_storage->pin_storage_prefs()->ResetUnlockAttemptCount(); + quick_unlock_storage->fingerprint_storage()->ResetUnlockAttemptCount(); + + Respond(ArgumentList( + quick_unlock_private::GetAuthToken::Results::Create(*result))); + Release(); // Balanced in Run(). +} + +// quickUnlockPrivate.setLockScreenEnabled + +QuickUnlockPrivateSetLockScreenEnabledFunction:: + QuickUnlockPrivateSetLockScreenEnabledFunction() + : chrome_details_(this) {} + +QuickUnlockPrivateSetLockScreenEnabledFunction:: + ~QuickUnlockPrivateSetLockScreenEnabledFunction() {} + +ExtensionFunction::ResponseAction +QuickUnlockPrivateSetLockScreenEnabledFunction::Run() { + auto params = + quick_unlock_private::SetLockScreenEnabled::Params::Create(args()); + AuthToken* auth_token = GetActiveProfileAuthToken(browser_context()); + if (!auth_token) + return RespondNow(Error(kAuthTokenExpired)); + if (params->token != auth_token->Identifier()) + return RespondNow(Error(kAuthTokenInvalid)); + + GetActiveProfile(browser_context()) + ->GetPrefs() + ->SetBoolean(ash::prefs::kEnableAutoScreenLock, params->enabled); + + return RespondNow(ArgumentList( + quick_unlock_private::SetLockScreenEnabled::Results::Create())); +} + +// quickUnlockPrivate.setPinAutosubmitEnabled + +QuickUnlockPrivateSetPinAutosubmitEnabledFunction:: + QuickUnlockPrivateSetPinAutosubmitEnabledFunction() + : chrome_details_(this) {} + +QuickUnlockPrivateSetPinAutosubmitEnabledFunction:: + ~QuickUnlockPrivateSetPinAutosubmitEnabledFunction() = default; + +ExtensionFunction::ResponseAction +QuickUnlockPrivateSetPinAutosubmitEnabledFunction::Run() { + auto params = + quick_unlock_private::SetPinAutosubmitEnabled::Params::Create(args()); + + AuthToken* auth_token = GetActiveProfileAuthToken(browser_context()); + if (!auth_token) + return RespondNow(Error(kAuthTokenExpired)); + if (params->token != auth_token->Identifier()) + return RespondNow(Error(kAuthTokenInvalid)); + + Profile* profile = GetActiveProfile(browser_context()); + user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile); + + ash::quick_unlock::PinBackend::GetInstance()->SetPinAutoSubmitEnabled( + user->GetAccountId(), params->pin, params->enabled, + base::BindOnce(&QuickUnlockPrivateSetPinAutosubmitEnabledFunction:: + HandleSetPinAutoSubmitResult, + this)); + + return RespondLater(); +} + +void QuickUnlockPrivateSetPinAutosubmitEnabledFunction:: + HandleSetPinAutoSubmitResult(bool result) { + Respond(ArgumentList( + quick_unlock_private::SetPinAutosubmitEnabled::Results::Create(result))); +} + +// quickUnlockPrivate.canAuthenticatePin + +QuickUnlockPrivateCanAuthenticatePinFunction:: + QuickUnlockPrivateCanAuthenticatePinFunction() + : chrome_details_(this) {} + +QuickUnlockPrivateCanAuthenticatePinFunction:: + ~QuickUnlockPrivateCanAuthenticatePinFunction() = default; + +ExtensionFunction::ResponseAction +QuickUnlockPrivateCanAuthenticatePinFunction::Run() { + AuthToken* auth_token = GetActiveProfileAuthToken(browser_context()); + if (!auth_token) + return RespondNow(Error(kAuthTokenExpired)); + + Profile* profile = GetActiveProfile(browser_context()); + user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile); + + ash::quick_unlock::PinBackend::GetInstance()->CanAuthenticate( + user->GetAccountId(), + base::BindOnce(&QuickUnlockPrivateCanAuthenticatePinFunction:: + HandleCanAuthenticateResult, + this)); + return RespondLater(); +} + +void QuickUnlockPrivateCanAuthenticatePinFunction::HandleCanAuthenticateResult( + bool result) { + Respond(ArgumentList( + quick_unlock_private::CanAuthenticatePin::Results::Create(result))); +} + +// quickUnlockPrivate.getAvailableModes + +QuickUnlockPrivateGetAvailableModesFunction:: + QuickUnlockPrivateGetAvailableModesFunction() + : chrome_details_(this) {} + +QuickUnlockPrivateGetAvailableModesFunction:: + ~QuickUnlockPrivateGetAvailableModesFunction() {} + +ExtensionFunction::ResponseAction +QuickUnlockPrivateGetAvailableModesFunction::Run() { + QuickUnlockModeList modes; + if (!ash::quick_unlock::IsPinDisabledByPolicy( + GetActiveProfile(browser_context())->GetPrefs())) { + modes.push_back(quick_unlock_private::QUICK_UNLOCK_MODE_PIN); + } + + return RespondNow(ArgumentList(GetAvailableModes::Results::Create(modes))); +} + +// quickUnlockPrivate.getActiveModes + +QuickUnlockPrivateGetActiveModesFunction:: + QuickUnlockPrivateGetActiveModesFunction() + : chrome_details_(this) {} + +QuickUnlockPrivateGetActiveModesFunction:: + ~QuickUnlockPrivateGetActiveModesFunction() = default; + +ExtensionFunction::ResponseAction +QuickUnlockPrivateGetActiveModesFunction::Run() { + ComputeActiveModes( + GetActiveProfile(browser_context()), + base::BindOnce( + &QuickUnlockPrivateGetActiveModesFunction::OnGetActiveModes, this)); + return RespondLater(); +} + +void QuickUnlockPrivateGetActiveModesFunction::OnGetActiveModes( + const std::vector<api::quick_unlock_private::QuickUnlockMode>& modes) { + Respond(ArgumentList(GetActiveModes::Results::Create(modes))); +} + +// quickUnlockPrivate.checkCredential + +QuickUnlockPrivateCheckCredentialFunction:: + QuickUnlockPrivateCheckCredentialFunction() {} + +QuickUnlockPrivateCheckCredentialFunction:: + ~QuickUnlockPrivateCheckCredentialFunction() {} + +ExtensionFunction::ResponseAction +QuickUnlockPrivateCheckCredentialFunction::Run() { + std::unique_ptr<CheckCredential::Params> params_ = + CheckCredential::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params_); + + auto result = std::make_unique<CredentialCheck>(); + + // Only handles pins for now. + if (params_->mode != QuickUnlockMode::QUICK_UNLOCK_MODE_PIN) + return RespondNow(ArgumentList(CheckCredential::Results::Create(*result))); + + const std::string& credential = params_->credential; + + Profile* profile = GetActiveProfile(browser_context()); + PrefService* pref_service = profile->GetPrefs(); + bool allow_weak = + pref_service->GetBoolean(ash::prefs::kPinUnlockWeakPinsAllowed); + bool is_allow_weak_pin_pref_set = + pref_service->HasPrefPath(ash::prefs::kPinUnlockWeakPinsAllowed); + + // Check and return the problems. + std::vector<CredentialProblem>& warnings = result->warnings; + std::vector<CredentialProblem>& errors = result->errors; + if (!IsPinNumeric(credential)) + errors.push_back(CredentialProblem::CREDENTIAL_PROBLEM_CONTAINS_NONDIGIT); + + CredentialProblem length_problem = + GetCredentialProblemForPin(credential, pref_service); + if (length_problem != CredentialProblem::CREDENTIAL_PROBLEM_NONE) + errors.push_back(length_problem); + + if ((!allow_weak || !is_allow_weak_pin_pref_set) && + !IsPinDifficultEnough(credential)) { + auto& log = allow_weak ? warnings : errors; + log.push_back(CredentialProblem::CREDENTIAL_PROBLEM_TOO_WEAK); + } + + return RespondNow(ArgumentList(CheckCredential::Results::Create(*result))); +} + +QuickUnlockPrivateGetCredentialRequirementsFunction:: + QuickUnlockPrivateGetCredentialRequirementsFunction() {} + +QuickUnlockPrivateGetCredentialRequirementsFunction:: + ~QuickUnlockPrivateGetCredentialRequirementsFunction() {} + +ExtensionFunction::ResponseAction +QuickUnlockPrivateGetCredentialRequirementsFunction::Run() { + std::unique_ptr<GetCredentialRequirements::Params> params_ = + GetCredentialRequirements::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params_); + + auto result = std::make_unique<CredentialRequirements>(); + std::tie(result->min_length, result->max_length) = + GetSanitizedPolicyPinMinMaxLength( + GetActiveProfile(browser_context())->GetPrefs()); + + return RespondNow( + ArgumentList(GetCredentialRequirements::Results::Create(*result))); +} + +// quickUnlockPrivate.setModes + +QuickUnlockPrivateSetModesFunction::QuickUnlockPrivateSetModesFunction() + : chrome_details_(this) {} + +QuickUnlockPrivateSetModesFunction::~QuickUnlockPrivateSetModesFunction() = + default; + +void QuickUnlockPrivateSetModesFunction::SetModesChangedEventHandlerForTesting( + const ModesChangedEventHandler& handler) { + modes_changed_handler_ = handler; +} + +ExtensionFunction::ResponseAction QuickUnlockPrivateSetModesFunction::Run() { + params_ = SetModes::Params::Create(args()); + EXTENSION_FUNCTION_VALIDATE(params_); + + if (params_->modes.size() != params_->credentials.size()) + return RespondNow(Error(kModesAndCredentialsLengthMismatch)); + + if (params_->modes.size() > 1) + return RespondNow(Error(kMultipleModesNotSupported)); + + AuthToken* auth_token = GetActiveProfileAuthToken(browser_context()); + if (!auth_token) + return RespondNow(Error(kAuthTokenExpired)); + if (params_->token != auth_token->Identifier()) + return RespondNow(Error(kAuthTokenInvalid)); + + // Verify every credential is valid based on policies. + PrefService* pref_service = GetActiveProfile(browser_context())->GetPrefs(); + + // Do not allow setting a PIN if it is disabled by policy. It is disabled + // on the UI, but users can still reach here via dev tools. + for (size_t i = 0; i < params_->modes.size(); ++i) { + if (params_->modes[i] == QuickUnlockMode::QUICK_UNLOCK_MODE_PIN && + ash::quick_unlock::IsPinDisabledByPolicy(pref_service)) { + return RespondNow(Error(kPinDisabledByPolicy)); + } + } + + // Verify every credential is valid based on policies. + bool allow_weak = + pref_service->GetBoolean(ash::prefs::kPinUnlockWeakPinsAllowed); + for (size_t i = 0; i < params_->modes.size(); ++i) { + if (params_->credentials[i].empty()) + continue; + + if (params_->modes[i] != QuickUnlockMode::QUICK_UNLOCK_MODE_PIN) + continue; + + if (!IsPinNumeric(params_->credentials[i])) + return RespondNow(Error(kInvalidPIN)); + + CredentialProblem problem = + GetCredentialProblemForPin(params_->credentials[i], pref_service); + if (problem != CredentialProblem::CREDENTIAL_PROBLEM_NONE) + return RespondNow(Error(kInvalidCredential)); + + if (!allow_weak && !IsPinDifficultEnough(params_->credentials[i])) + return RespondNow(Error(kWeakCredential)); + } + + ComputeActiveModes( + GetActiveProfile(browser_context()), + base::BindOnce(&QuickUnlockPrivateSetModesFunction::OnGetActiveModes, + this)); + + return RespondLater(); +} + +void QuickUnlockPrivateSetModesFunction::OnGetActiveModes( + const std::vector<QuickUnlockMode>& initial_modes) { + initial_modes_ = initial_modes; + + // This function is setup so it is easy to add another quick unlock mode while + // following all of the invariants, which are: + // + // 1: If an unlock type is not specified, it should be deactivated. + // 2: If a credential for an unlock type is empty, it should not be touched. + // 3: Otherwise, the credential should be set to the new value. + + bool update_pin = true; + std::string pin_credential; + + // Compute needed changes. + DCHECK_EQ(params_->credentials.size(), params_->modes.size()); + for (size_t i = 0; i < params_->modes.size(); ++i) { + const QuickUnlockMode mode = params_->modes[i]; + const std::string& credential = params_->credentials[i]; + + if (mode == quick_unlock_private::QUICK_UNLOCK_MODE_PIN) { + update_pin = !credential.empty(); + pin_credential = credential; + } + } + + // Apply changes. + if (update_pin) { + Profile* profile = GetActiveProfile(browser_context()); + user_manager::User* user = + chromeos::ProfileHelper::Get()->GetUserByProfile(profile); + if (pin_credential.empty()) { + ash::quick_unlock::PinBackend::GetInstance()->Remove( + user->GetAccountId(), params_->token, + base::BindOnce( + &QuickUnlockPrivateSetModesFunction::PinRemoveCallComplete, + this)); + } else { + ash::quick_unlock::PinBackend::GetInstance()->Set( + user->GetAccountId(), params_->token, pin_credential, + base::BindOnce( + &QuickUnlockPrivateSetModesFunction::PinSetCallComplete, this)); + } + } else { + // No changes to apply. Call result directly. + ModeChangeComplete(initial_modes_); + } +} + +void QuickUnlockPrivateSetModesFunction::PinSetCallComplete(bool result) { + if (!result) { + Respond(Error(kInternalError)); + return; + } + ComputeActiveModes( + GetActiveProfile(browser_context()), + base::BindOnce(&QuickUnlockPrivateSetModesFunction::ModeChangeComplete, + this)); +} + +void QuickUnlockPrivateSetModesFunction::PinRemoveCallComplete(bool result) { + ComputeActiveModes( + GetActiveProfile(browser_context()), + base::BindOnce(&QuickUnlockPrivateSetModesFunction::ModeChangeComplete, + this)); +} + +void QuickUnlockPrivateSetModesFunction::ModeChangeComplete( + const std::vector<QuickUnlockMode>& updated_modes) { + if (!AreModesEqual(initial_modes_, updated_modes)) + FireEvent(updated_modes); + + const user_manager::User* const user = + chromeos::ProfileHelper::Get()->GetUserByProfile( + GetActiveProfile(browser_context())); + const chromeos::UserContext user_context(*user); + + Respond(ArgumentList(SetModes::Results::Create())); +} + +// Triggers a quickUnlockPrivate.onActiveModesChanged change event. +void QuickUnlockPrivateSetModesFunction::FireEvent( + const QuickUnlockModeList& modes) { + // Allow unit tests to override how events are raised/handled. + if (modes_changed_handler_) { + modes_changed_handler_.Run(modes); + return; + } + + auto args = OnActiveModesChanged::Create(modes); + auto event = std::make_unique<Event>( + events::QUICK_UNLOCK_PRIVATE_ON_ACTIVE_MODES_CHANGED, + OnActiveModesChanged::kEventName, std::move(args)); + EventRouter::Get(browser_context())->BroadcastEvent(std::move(event)); +} + +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.h b/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.h new file mode 100644 index 00000000000..4570db37007 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.h @@ -0,0 +1,263 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_EXTENSIONS_API_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_H_ + +#include <memory> +#include <vector> + +#include "base/callback.h" +#include "base/memory/ref_counted.h" +#include "chrome/browser/extensions/chrome_extension_function_details.h" +#include "chrome/common/extensions/api/quick_unlock_private.h" +#include "chromeos/login/auth/auth_status_consumer.h" +#include "extensions/browser/extension_function.h" + +namespace chromeos { +class ExtendedAuthenticator; +} + +namespace extensions { + +class QuickUnlockPrivateGetAuthTokenFunction + : public ExtensionFunction, + public chromeos::AuthStatusConsumer { + public: + using AuthenticatorAllocator = + base::RepeatingCallback<chromeos::ExtendedAuthenticator*( + chromeos::AuthStatusConsumer* auth_status_consumer)>; + + QuickUnlockPrivateGetAuthTokenFunction(); + QuickUnlockPrivateGetAuthTokenFunction( + const QuickUnlockPrivateGetAuthTokenFunction&) = delete; + const QuickUnlockPrivateGetAuthTokenFunction& operator=( + const QuickUnlockPrivateGetAuthTokenFunction&) = delete; + + // Use the given |allocator| to create an ExtendedAuthenticator instance. This + // lets tests intercept authentication calls. + void SetAuthenticatorAllocatorForTesting( + const AuthenticatorAllocator& allocator); + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.getAuthToken", + QUICKUNLOCKPRIVATE_GETAUTHTOKEN) + + protected: + ~QuickUnlockPrivateGetAuthTokenFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + // AuthStatusConsumer overrides. + void OnAuthFailure(const chromeos::AuthFailure& error) override; + void OnAuthSuccess(const chromeos::UserContext& user_context) override; + + private: + ChromeExtensionFunctionDetails chrome_details_; + scoped_refptr<chromeos::ExtendedAuthenticator> extended_authenticator_; + AuthenticatorAllocator authenticator_allocator_; +}; + +class QuickUnlockPrivateSetLockScreenEnabledFunction + : public ExtensionFunction { + public: + QuickUnlockPrivateSetLockScreenEnabledFunction(); + QuickUnlockPrivateSetLockScreenEnabledFunction( + const QuickUnlockPrivateSetLockScreenEnabledFunction&) = delete; + const QuickUnlockPrivateSetLockScreenEnabledFunction& operator=( + const QuickUnlockPrivateSetLockScreenEnabledFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.setLockScreenEnabled", + QUICKUNLOCKPRIVATE_SETLOCKSCREENENABLED) + + protected: + ~QuickUnlockPrivateSetLockScreenEnabledFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + ChromeExtensionFunctionDetails chrome_details_; +}; + +class QuickUnlockPrivateSetPinAutosubmitEnabledFunction + : public ExtensionFunction { + public: + QuickUnlockPrivateSetPinAutosubmitEnabledFunction(); + QuickUnlockPrivateSetPinAutosubmitEnabledFunction( + const QuickUnlockPrivateSetPinAutosubmitEnabledFunction&) = delete; + const QuickUnlockPrivateSetPinAutosubmitEnabledFunction& operator=( + const QuickUnlockPrivateSetPinAutosubmitEnabledFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.setPinAutosubmitEnabled", + QUICKUNLOCKPRIVATE_SETPINAUTOSUBMITENABLED) + + protected: + ~QuickUnlockPrivateSetPinAutosubmitEnabledFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + void HandleSetPinAutoSubmitResult(bool result); + + ChromeExtensionFunctionDetails chrome_details_; +}; + +class QuickUnlockPrivateCanAuthenticatePinFunction : public ExtensionFunction { + public: + QuickUnlockPrivateCanAuthenticatePinFunction(); + QuickUnlockPrivateCanAuthenticatePinFunction( + const QuickUnlockPrivateCanAuthenticatePinFunction&) = delete; + const QuickUnlockPrivateCanAuthenticatePinFunction& operator=( + const QuickUnlockPrivateCanAuthenticatePinFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.canAuthenticatePin", + QUICKUNLOCKPRIVATE_CANAUTHENTICATEPIN) + + protected: + ~QuickUnlockPrivateCanAuthenticatePinFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + void HandleCanAuthenticateResult(bool result); + + ChromeExtensionFunctionDetails chrome_details_; +}; + +class QuickUnlockPrivateGetAvailableModesFunction : public ExtensionFunction { + public: + QuickUnlockPrivateGetAvailableModesFunction(); + QuickUnlockPrivateGetAvailableModesFunction( + const QuickUnlockPrivateGetAvailableModesFunction&) = delete; + const QuickUnlockPrivateGetAvailableModesFunction& operator=( + const QuickUnlockPrivateGetAvailableModesFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.getAvailableModes", + QUICKUNLOCKPRIVATE_GETAVAILABLEMODES) + + protected: + ~QuickUnlockPrivateGetAvailableModesFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + ChromeExtensionFunctionDetails chrome_details_; +}; + +class QuickUnlockPrivateGetActiveModesFunction : public ExtensionFunction { + public: + QuickUnlockPrivateGetActiveModesFunction(); + QuickUnlockPrivateGetActiveModesFunction( + const QuickUnlockPrivateGetActiveModesFunction&) = delete; + const QuickUnlockPrivateGetActiveModesFunction& operator=( + const QuickUnlockPrivateGetActiveModesFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.getActiveModes", + QUICKUNLOCKPRIVATE_GETACTIVEMODES) + + protected: + ~QuickUnlockPrivateGetActiveModesFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + void OnGetActiveModes( + const std::vector<api::quick_unlock_private::QuickUnlockMode>& modes); + + ChromeExtensionFunctionDetails chrome_details_; +}; + +class QuickUnlockPrivateCheckCredentialFunction : public ExtensionFunction { + public: + QuickUnlockPrivateCheckCredentialFunction(); + QuickUnlockPrivateCheckCredentialFunction( + const QuickUnlockPrivateCheckCredentialFunction&) = delete; + const QuickUnlockPrivateCheckCredentialFunction& operator=( + const QuickUnlockPrivateCheckCredentialFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.checkCredential", + QUICKUNLOCKPRIVATE_CHECKCREDENTIAL) + + protected: + ~QuickUnlockPrivateCheckCredentialFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; +}; + +class QuickUnlockPrivateGetCredentialRequirementsFunction + : public ExtensionFunction { + public: + QuickUnlockPrivateGetCredentialRequirementsFunction(); + QuickUnlockPrivateGetCredentialRequirementsFunction( + const QuickUnlockPrivateGetCredentialRequirementsFunction&) = delete; + const QuickUnlockPrivateGetCredentialRequirementsFunction& operator=( + const QuickUnlockPrivateGetCredentialRequirementsFunction&) = delete; + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.getCredentialRequirements", + QUICKUNLOCKPRIVATE_GETCREDENTIALREQUIREMENTS) + + protected: + ~QuickUnlockPrivateGetCredentialRequirementsFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; +}; + +class QuickUnlockPrivateSetModesFunction : public ExtensionFunction { + public: + using QuickUnlockMode = + extensions::api::quick_unlock_private::QuickUnlockMode; + using ModesChangedEventHandler = + base::RepeatingCallback<void(const std::vector<QuickUnlockMode>&)>; + + QuickUnlockPrivateSetModesFunction(); + QuickUnlockPrivateSetModesFunction( + const QuickUnlockPrivateSetModesFunction&) = delete; + const QuickUnlockPrivateSetModesFunction& operator=( + const QuickUnlockPrivateSetModesFunction&) = delete; + + // The given event handler will be called whenever a + // quickUnlockPrivate.onActiveModesChanged event is raised instead of the + // default event handling mechanism. + void SetModesChangedEventHandlerForTesting( + const ModesChangedEventHandler& handler); + + DECLARE_EXTENSION_FUNCTION("quickUnlockPrivate.setModes", + QUICKUNLOCKPRIVATE_SETMODES) + + protected: + ~QuickUnlockPrivateSetModesFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + // Continuation of OnAuthSuccess after active modes have been fetched. + void OnGetActiveModes(const std::vector<QuickUnlockMode>& modes); + + void PinSetCallComplete(bool result); + void PinRemoveCallComplete(bool result); + + // Apply any changes specified in |params_|. Returns the new active modes. + void ModeChangeComplete(const std::vector<QuickUnlockMode>& updated_modes); + + private: + void FireEvent(const std::vector<QuickUnlockMode>& modes); + + ChromeExtensionFunctionDetails chrome_details_; + std::unique_ptr<api::quick_unlock_private::SetModes::Params> params_; + + std::vector<QuickUnlockMode> initial_modes_; + + ModesChangedEventHandler modes_changed_handler_; +}; + +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_QUICK_UNLOCK_PRIVATE_QUICK_UNLOCK_PRIVATE_API_H_ diff --git a/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api_unittest.cc new file mode 100644 index 00000000000..fba74d26d48 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api_unittest.cc @@ -0,0 +1,1145 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// This file tests the chromeos.quickUnlockPrivate extension API. + +#include "chrome/browser/extensions/api/quick_unlock_private/quick_unlock_private_api.h" + +#include <memory> + +#include "ash/constants/ash_features.h" +#include "ash/constants/ash_pref_names.h" +#include "base/bind.h" +#include "base/callback_helpers.h" +#include "base/containers/contains.h" +#include "base/memory/ptr_util.h" +#include "base/no_destructor.h" +#include "base/run_loop.h" +#include "base/strings/strcat.h" +#include "base/strings/string_piece_forward.h" +#include "base/test/bind.h" +#include "base/test/metrics/histogram_tester.h" +#include "base/test/scoped_feature_list.h" +#include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/ash/login/easy_unlock/easy_unlock_service_factory.h" +#include "chrome/browser/ash/login/easy_unlock/easy_unlock_service_regular.h" +#include "chrome/browser/ash/login/quick_unlock/auth_token.h" +#include "chrome/browser/ash/login/quick_unlock/pin_backend.h" +#include "chrome/browser/ash/login/quick_unlock/pin_storage_prefs.h" +#include "chrome/browser/ash/login/quick_unlock/quick_unlock_factory.h" +#include "chrome/browser/ash/login/quick_unlock/quick_unlock_storage.h" +#include "chrome/browser/ash/login/quick_unlock/quick_unlock_utils.h" +#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h" +#include "chrome/browser/ash/profiles/profile_helper.h" +#include "chrome/browser/extensions/extension_api_unittest.h" +#include "chrome/browser/prefs/browser_prefs.h" +#include "chrome/common/chrome_features.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/base/testing_profile_manager.h" +#include "chromeos/cryptohome/system_salt_getter.h" +#include "chromeos/dbus/userdataauth/fake_cryptohome_misc_client.h" +#include "chromeos/dbus/userdataauth/fake_userdataauth_client.h" +#include "chromeos/login/auth/fake_extended_authenticator.h" +#include "chromeos/services/device_sync/public/cpp/fake_device_sync_client.h" +#include "chromeos/services/multidevice_setup/public/cpp/fake_multidevice_setup_client.h" +#include "chromeos/services/secure_channel/public/cpp/client/fake_secure_channel_client.h" +#include "components/prefs/pref_service.h" +#include "components/prefs/testing_pref_service.h" +#include "components/sync_preferences/testing_pref_service_syncable.h" +#include "components/user_manager/known_user.h" +#include "components/user_manager/scoped_user_manager.h" +#include "content/public/test/test_utils.h" +#include "extensions/browser/api_test_utils.h" +#include "extensions/browser/extension_function_dispatcher.h" + +namespace extensions { +namespace { + +namespace quick_unlock_private = api::quick_unlock_private; +using CredentialCheck = quick_unlock_private::CredentialCheck; +using CredentialProblem = quick_unlock_private::CredentialProblem; +using CredentialRequirements = quick_unlock_private::CredentialRequirements; +using QuickUnlockMode = quick_unlock_private::QuickUnlockMode; +using QuickUnlockModeList = std::vector<QuickUnlockMode>; +using CredentialList = std::vector<std::string>; + +// The type of the test. Either based on Prefs or Cryptohome +enum class TestType { kPrefs, kCryptohome }; + +const base::StringPiece TestTypeStr(TestType type) { + switch (type) { + case TestType::kPrefs: + return "PrefBased"; + case TestType::kCryptohome: + return "CryptohomeBased"; + } +} + +constexpr char kTestUserEmail[] = "testuser@gmail.com"; +constexpr char kTestUserGaiaId[] = "9876543210"; +constexpr char kTestUserEmailHash[] = "testuser@gmail.com-hash"; +constexpr char kInvalidToken[] = "invalid"; +constexpr char kValidPassword[] = "valid"; +constexpr char kInvalidPassword[] = "invalid"; + +class FakeEasyUnlockService : public ash::EasyUnlockServiceRegular { + public: + FakeEasyUnlockService( + Profile* profile, + chromeos::device_sync::FakeDeviceSyncClient* fake_device_sync_client, + chromeos::secure_channel::FakeSecureChannelClient* + fake_secure_channel_client, + chromeos::multidevice_setup::FakeMultiDeviceSetupClient* + fake_multidevice_setup_client) + : ash::EasyUnlockServiceRegular(profile, + fake_secure_channel_client, + fake_device_sync_client, + fake_multidevice_setup_client) {} + + FakeEasyUnlockService(const FakeEasyUnlockService&) = delete; + FakeEasyUnlockService& operator=(const FakeEasyUnlockService&) = delete; + + ~FakeEasyUnlockService() override {} + + // ash::EasyUnlockServiceRegular: + void InitializeInternal() override {} + void ShutdownInternal() override {} +}; + +std::unique_ptr<KeyedService> CreateEasyUnlockServiceForTest( + content::BrowserContext* context) { + static base::NoDestructor<chromeos::device_sync::FakeDeviceSyncClient> + fake_device_sync_client; + static base::NoDestructor<chromeos::secure_channel::FakeSecureChannelClient> + fake_secure_channel_client; + static base::NoDestructor< + chromeos::multidevice_setup::FakeMultiDeviceSetupClient> + fake_multidevice_setup_client; + + return std::make_unique<FakeEasyUnlockService>( + Profile::FromBrowserContext(context), fake_device_sync_client.get(), + fake_secure_channel_client.get(), fake_multidevice_setup_client.get()); +} + +ash::ExtendedAuthenticator* CreateFakeAuthenticator( + ash::AuthStatusConsumer* auth_status_consumer) { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + ash::UserContext expected_context(user_manager::USER_TYPE_REGULAR, + account_id); + expected_context.SetKey(ash::Key(kValidPassword)); + + auto* authenticator = new ash::FakeExtendedAuthenticator(auth_status_consumer, + expected_context); + return authenticator; +} + +void FailIfCalled(const QuickUnlockModeList& modes) { + FAIL(); +} + +enum ExpectedPinState { + PIN_GOOD = 1 << 0, + PIN_TOO_SHORT = 1 << 1, + PIN_TOO_LONG = 1 << 2, + PIN_WEAK_ERROR = 1 << 3, + PIN_WEAK_WARNING = 1 << 4, + PIN_CONTAINS_NONDIGIT = 1 << 5 +}; + +} // namespace + +class QuickUnlockPrivateUnitTest + : public ExtensionApiUnittest, + public ::testing::WithParamInterface<std::tuple<TestType, bool>> { + public: + static std::string ParamInfoToString( + testing::TestParamInfo<QuickUnlockPrivateUnitTest::ParamType> info) { + return base::StrCat( + {TestTypeStr(std::get<0>(info.param)), + std::get<1>(info.param) ? "AutosubmitEnabled" : "AutosubmitDisabled"}); + } + + QuickUnlockPrivateUnitTest() = default; + + QuickUnlockPrivateUnitTest(const QuickUnlockPrivateUnitTest&) = delete; + QuickUnlockPrivateUnitTest& operator=(const QuickUnlockPrivateUnitTest&) = + delete; + + ~QuickUnlockPrivateUnitTest() override = default; + + protected: + void SetUp() override { + // Enable/disable PIN auto submit + auto param = GetParam(); + feature_list_.InitWithFeatureState(ash::features::kQuickUnlockPinAutosubmit, + std::get<1>(param)); + + ash::CryptohomeMiscClient::InitializeFake(); + ash::UserDataAuthClient::InitializeFake(); + if (std::get<0>(param) == TestType::kCryptohome) { + auto* cryptohome_client = ash::FakeUserDataAuthClient::Get(); + cryptohome_client->set_supports_low_entropy_credentials(true); + cryptohome_client->set_enable_auth_check(true); + } + ash::SystemSaltGetter::Initialize(); + + fake_user_manager_ = new ash::FakeChromeUserManager(); + scoped_user_manager_ = std::make_unique<user_manager::ScopedUserManager>( + base::WrapUnique(fake_user_manager_)); + + ExtensionApiUnittest::SetUp(); + + ash::SystemSaltGetter::Get()->SetRawSaltForTesting( + {1, 2, 3, 4, 5, 6, 7, 8}); + fake_user_manager_->CreateLocalState(); + + // Rebuild quick unlock state. + ash::quick_unlock::EnabledForTesting(true); + ash::quick_unlock::PinBackend::ResetForTesting(); + + base::RunLoop().RunUntilIdle(); + + modes_changed_handler_ = base::DoNothing(); + + // Ensure that quick unlock is turned off. + RunSetModes(QuickUnlockModeList{}, CredentialList{}); + } + + TestingProfile* CreateProfile() override { + auto pref_service = + std::make_unique<sync_preferences::TestingPrefServiceSyncable>(); + RegisterUserProfilePrefs(pref_service->registry()); + test_pref_service_ = pref_service.get(); + + TestingProfile* profile = profile_manager()->CreateTestingProfile( + kTestUserEmail, std::move(pref_service), u"Test profile", + 1 /* avatar_id */, std::string() /* supervised_user_id */, + GetTestingFactories()); + + // Setup a primary user. + auto test_account = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + fake_user_manager_->AddUser(test_account); + fake_user_manager_->UserLoggedIn(test_account, kTestUserEmailHash, false, + false); + ash::ProfileHelper::Get()->SetUserToProfileMappingForTesting( + fake_user_manager_->GetPrimaryUser(), profile); + + // Generate an auth token. + auth_token_user_context_.SetAccountId(test_account); + auth_token_user_context_.SetUserIDHash(kTestUserEmailHash); + token_ = ash::quick_unlock::QuickUnlockFactory::GetForProfile(profile) + ->CreateAuthToken(auth_token_user_context_); + base::RunLoop().RunUntilIdle(); + + return profile; + } + + void TearDown() override { + ash::quick_unlock::EnabledForTesting(false); + ash::quick_unlock::DisablePinByPolicyForTesting(false); + + base::RunLoop().RunUntilIdle(); + + ExtensionApiUnittest::TearDown(); + + fake_user_manager_ = nullptr; + scoped_user_manager_.reset(); + + ash::SystemSaltGetter::Shutdown(); + ash::UserDataAuthClient::Shutdown(); + ash::CryptohomeMiscClient::Shutdown(); + } + + TestingProfile::TestingFactories GetTestingFactories() override { + return {{ash::EasyUnlockServiceFactory::GetInstance(), + base::BindRepeating(&CreateEasyUnlockServiceForTest)}}; + } + + // If a mode change event is raised, fail the test. + void FailIfModesChanged() { + modes_changed_handler_ = base::BindRepeating(&FailIfCalled); + } + + // If a mode change event is raised, expect the given |modes|. + void ExpectModesChanged(const QuickUnlockModeList& modes) { + modes_changed_handler_ = + base::BindRepeating(&QuickUnlockPrivateUnitTest::ExpectModeList, + base::Unretained(this), modes); + expect_modes_changed_ = true; + } + + // Wrapper for chrome.quickUnlockPrivate.getAuthToken. Expects the function + // to succeed and returns the result. + std::unique_ptr<quick_unlock_private::TokenInfo> GetAuthToken( + const std::string& password) { + // Setup a fake authenticator to avoid calling cryptohome methods. + auto* func = new QuickUnlockPrivateGetAuthTokenFunction(); + func->SetAuthenticatorAllocatorForTesting( + base::BindRepeating(&CreateFakeAuthenticator)); + + auto params = std::make_unique<base::ListValue>(); + params->Append(base::Value(password)); + std::unique_ptr<base::Value> result = RunFunction(func, std::move(params)); + EXPECT_TRUE(result); + auto token_info = quick_unlock_private::TokenInfo::FromValue(*result); + EXPECT_TRUE(token_info); + return token_info; + } + + // Wrapper for chrome.quickUnlockPrivate.getAuthToken with an invalid + // password. Expects the function to fail and returns the error. + std::string RunAuthTokenWithInvalidPassword() { + // Setup a fake authenticator to avoid calling cryptohome methods. + auto* func = new QuickUnlockPrivateGetAuthTokenFunction(); + func->SetAuthenticatorAllocatorForTesting( + base::BindRepeating(&CreateFakeAuthenticator)); + + auto params = std::make_unique<base::ListValue>(); + params->Append(base::Value(kInvalidPassword)); + return RunFunctionAndReturnError(func, std::move(params)); + } + + // Wrapper for chrome.quickUnlockPrivate.setLockScreenEnabled. + void SetLockScreenEnabled(const std::string& token, bool enabled) { + auto params = std::make_unique<base::ListValue>(); + params->Append(token); + params->Append(enabled); + RunFunction(new QuickUnlockPrivateSetLockScreenEnabledFunction(), + std::move(params)); + } + + // Wrapper for chrome.quickUnlockPrivate.setLockScreenEnabled. + std::string SetLockScreenEnabledWithInvalidToken(bool enabled) { + auto params = std::make_unique<base::ListValue>(); + params->Append(kInvalidToken); + params->Append(enabled); + return RunFunctionAndReturnError( + new QuickUnlockPrivateSetLockScreenEnabledFunction(), + std::move(params)); + } + + // Wrapper for chrome.quickUnlockPrivate.getAvailableModes. + QuickUnlockModeList GetAvailableModes() { + // Run the function. + std::unique_ptr<base::Value> result = + RunFunction(new QuickUnlockPrivateGetAvailableModesFunction(), + std::make_unique<base::ListValue>()); + + // Extract the results. + QuickUnlockModeList modes; + + EXPECT_TRUE(result->is_list()); + for (const base::Value& value : result->GetList()) { + EXPECT_TRUE(value.is_string()); + modes.push_back( + quick_unlock_private::ParseQuickUnlockMode(value.GetString())); + } + + return modes; + } + + // Wrapper for chrome.quickUnlockPrivate.getActiveModes. + QuickUnlockModeList GetActiveModes() { + std::unique_ptr<base::Value> result = + RunFunction(new QuickUnlockPrivateGetActiveModesFunction(), + std::make_unique<base::ListValue>()); + + QuickUnlockModeList modes; + + EXPECT_TRUE(result->is_list()); + for (const base::Value& value : result->GetList()) { + EXPECT_TRUE(value.is_string()); + modes.push_back( + quick_unlock_private::ParseQuickUnlockMode(value.GetString())); + } + + return modes; + } + + bool HasFlag(int outcome, int flag) { return (outcome & flag) != 0; } + + // Helper function for checking whether |IsCredentialUsableUsingPin| will + // return the right message given a pin. + void CheckPin(int expected_outcome, const std::string& pin) { + CredentialCheck result = CheckCredentialUsingPin(pin); + const std::vector<CredentialProblem> errors(result.errors); + const std::vector<CredentialProblem> warnings(result.warnings); + + // A pin is considered good if it emits no errors or warnings. + EXPECT_EQ(HasFlag(expected_outcome, PIN_GOOD), + errors.empty() && warnings.empty()); + EXPECT_EQ(HasFlag(expected_outcome, PIN_TOO_SHORT), + base::Contains(errors, + CredentialProblem::CREDENTIAL_PROBLEM_TOO_SHORT)); + EXPECT_EQ( + HasFlag(expected_outcome, PIN_TOO_LONG), + base::Contains(errors, CredentialProblem::CREDENTIAL_PROBLEM_TOO_LONG)); + EXPECT_EQ(HasFlag(expected_outcome, PIN_WEAK_WARNING), + base::Contains(warnings, + CredentialProblem::CREDENTIAL_PROBLEM_TOO_WEAK)); + EXPECT_EQ( + HasFlag(expected_outcome, PIN_WEAK_ERROR), + base::Contains(errors, CredentialProblem::CREDENTIAL_PROBLEM_TOO_WEAK)); + EXPECT_EQ( + HasFlag(expected_outcome, PIN_CONTAINS_NONDIGIT), + base::Contains( + errors, CredentialProblem::CREDENTIAL_PROBLEM_CONTAINS_NONDIGIT)); + } + + CredentialCheck CheckCredentialUsingPin(const std::string& pin) { + auto params = std::make_unique<base::ListValue>(); + params->Append(ToString(QuickUnlockMode::QUICK_UNLOCK_MODE_PIN)); + params->Append(pin); + + std::unique_ptr<base::Value> result = RunFunction( + new QuickUnlockPrivateCheckCredentialFunction(), std::move(params)); + + CredentialCheck function_result; + EXPECT_TRUE(CredentialCheck::Populate(*result, &function_result)); + return function_result; + } + + void CheckGetCredentialRequirements(int expected_pin_min_length, + int expected_pin_max_length) { + auto params = std::make_unique<base::ListValue>(); + params->Append(ToString(QuickUnlockMode::QUICK_UNLOCK_MODE_PIN)); + + std::unique_ptr<base::Value> result = + RunFunction(new QuickUnlockPrivateGetCredentialRequirementsFunction(), + std::move(params)); + + CredentialRequirements function_result; + EXPECT_TRUE(CredentialRequirements::Populate(*result, &function_result)); + + EXPECT_EQ(function_result.min_length, expected_pin_min_length); + EXPECT_EQ(function_result.max_length, expected_pin_max_length); + } + + std::unique_ptr<base::ListValue> GetSetModesParams( + const std::string& token, + const QuickUnlockModeList& modes, + const CredentialList& passwords) { + auto params = std::make_unique<base::ListValue>(); + params->Append(token); + + auto serialized_modes = std::make_unique<base::ListValue>(); + for (QuickUnlockMode mode : modes) + serialized_modes->Append(quick_unlock_private::ToString(mode)); + params->Append(std::move(serialized_modes)); + + auto serialized_passwords = std::make_unique<base::ListValue>(); + for (const std::string& password : passwords) + serialized_passwords->Append(password); + params->Append(std::move(serialized_passwords)); + + return params; + } + + // Runs chrome.quickUnlockPrivate.setModes using a valid token. Expects the + // function to succeed. + void RunSetModes(const QuickUnlockModeList& modes, + const CredentialList& passwords) { + std::unique_ptr<base::ListValue> params = + GetSetModesParams(token_, modes, passwords); + auto* func = new QuickUnlockPrivateSetModesFunction(); + + // Stub out event handling since we are not setting up an event router. + func->SetModesChangedEventHandlerForTesting(modes_changed_handler_); + + // Run the function. Expect a non null result. + RunFunction(func, std::move(params)); + + // Verify that the mode change event handler was run if it was registered. + // ExpectModesChanged will set expect_modes_changed_ to true and the event + // handler will set it to false; so if the handler never runs, + // expect_modes_changed_ will still be true. + EXPECT_FALSE(expect_modes_changed_) << "Mode change event was not raised"; + } + + // Runs chrome.quickUnlockPrivate.setModes using an invalid token. Expects the + // function to fail and returns the error. + std::string RunSetModesWithInvalidToken() { + std::unique_ptr<base::ListValue> params = GetSetModesParams( + kInvalidToken, {QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, {"111111"}); + auto* func = new QuickUnlockPrivateSetModesFunction(); + + // Stub out event handling since we are not setting up an event router. + func->SetModesChangedEventHandlerForTesting(modes_changed_handler_); + + // Run function, expecting it to fail. + return RunFunctionAndReturnError(func, std::move(params)); + } + + std::string SetModesWithError(const std::string& args) { + auto* func = new QuickUnlockPrivateSetModesFunction(); + func->SetModesChangedEventHandlerForTesting(base::DoNothing()); + + return api_test_utils::RunFunctionAndReturnError(func, args, profile()); + } + + std::string token() { return token_; } + + // Returns if the pin is set in the backend. + bool IsPinSetInBackend() { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + + bool called = false; + bool is_set = false; + ash::quick_unlock::PinBackend::GetInstance()->IsSet( + account_id, base::BindOnce( + [](bool* out_called, bool* out_is_set, bool is_set) { + *out_called = true; + *out_is_set = is_set; + }, + &called, &is_set)); + base::RunLoop().RunUntilIdle(); + CHECK(called); + return is_set; + } + + // Checks whether there is a user value set for the PIN auto submit + // preference. + bool HasUserValueForPinAutosubmitPref() { + const bool has_user_val = + test_pref_service_->GetUserPrefValue( + ::prefs::kPinUnlockAutosubmitEnabled) != nullptr; + return has_user_val; + } + + bool GetAutosubmitPrefVal() { + return test_pref_service_->GetBoolean(::prefs::kPinUnlockAutosubmitEnabled); + } + + int GetExposedPinLength() { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + return user_manager::known_user::GetUserPinLength(account_id); + } + + void ClearExposedPinLength() { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + user_manager::known_user::SetUserPinLength(account_id, 0); + } + + bool IsBackfillNeeded() { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + return user_manager::known_user::PinAutosubmitIsBackfillNeeded(account_id); + } + + void SetBackfillNotNeeded() { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + user_manager::known_user::PinAutosubmitSetBackfillNotNeeded(account_id); + } + + void SetBackfillNeededForTests() { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + user_manager::known_user::PinAutosubmitSetBackfillNeededForTests( + account_id); + } + + void OnUpdateUserPods() { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + ash::quick_unlock::PinBackend::GetInstance()->GetExposedPinLength( + account_id); + } + + void SetPin(const std::string& pin) { + RunSetModes(QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, + {pin}); + } + + void SetPinForBackfillTests(const std::string& pin) { + // No PIN set. By default IsBackfillNeeded should return true. + ASSERT_EQ(IsBackfillNeeded(), true); + + // Set PIN. Backfill must be marked as 'not needed' internally by the API. + SetPin(pin); + ASSERT_EQ(IsBackfillNeeded(), false); + ASSERT_EQ(HasUserValueForPinAutosubmitPref(), false); + + // Set 'backfill needed' and clear the exposed length to simulate a PIN that + // was set before the PIN auto submit feature existed. + SetBackfillNeededForTests(); + ClearExposedPinLength(); + ASSERT_EQ(IsBackfillNeeded(), true); + ASSERT_EQ(GetExposedPinLength(), 0); + } + + void ClearPin() { RunSetModes(QuickUnlockModeList{}, CredentialList{}); } + + // Run an authentication attempt with the plain-text |password|. + bool TryAuthenticate(const std::string& password) { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + bool called = false; + bool success = false; + base::RunLoop loop; + ash::quick_unlock::PinBackend::GetInstance()->TryAuthenticate( + account_id, ash::Key(password), + base::BindLambdaForTesting([&](bool auth_success) { + called = true; + success = auth_success; + loop.Quit(); + })); + loop.Run(); + return success; + } + + bool SetPinAutosubmitEnabled(const std::string& pin, const bool enabled) { + const AccountId account_id = + AccountId::FromUserEmailGaiaId(kTestUserEmail, kTestUserGaiaId); + bool called = false; + bool success = false; + base::RunLoop loop; + ash::quick_unlock::PinBackend::GetInstance()->SetPinAutoSubmitEnabled( + account_id, pin, enabled, + base::BindLambdaForTesting([&](bool autosubmit_success) { + called = true; + success = autosubmit_success; + loop.Quit(); + })); + loop.Run(); + return success; + } + + bool IsAutosubmitFeatureEnabled() { return std::get<1>(GetParam()); } + + base::test::ScopedFeatureList feature_list_; + sync_preferences::TestingPrefServiceSyncable* test_pref_service_; + + private: + // Runs the given |func| with the given |params|. + std::unique_ptr<base::Value> RunFunction( + scoped_refptr<ExtensionFunction> func, + std::unique_ptr<base::ListValue> params) { + base::RunLoop().RunUntilIdle(); + std::unique_ptr<base::Value> result = + api_test_utils::RunFunctionWithDelegateAndReturnSingleResult( + func, std::move(params), profile(), + std::make_unique<ExtensionFunctionDispatcher>(profile()), + api_test_utils::NONE); + base::RunLoop().RunUntilIdle(); + return result; + } + + // Runs |func| with |params|. Expects and returns an error result. + std::string RunFunctionAndReturnError( + scoped_refptr<ExtensionFunction> func, + std::unique_ptr<base::ListValue> params) { + base::RunLoop().RunUntilIdle(); + auto dispatcher = std::make_unique<ExtensionFunctionDispatcher>(profile()); + api_test_utils::RunFunction(func.get(), std::move(params), profile(), + std::move(dispatcher), api_test_utils::NONE); + EXPECT_TRUE(func->GetResultList()->GetList().empty()); + base::RunLoop().RunUntilIdle(); + return func->GetError(); + } + + // Verifies a mode change event is raised and that |expected| is now the + // active set of quick unlock modes. + void ExpectModeList(const QuickUnlockModeList& expected, + const QuickUnlockModeList& actual) { + EXPECT_EQ(expected, actual); + expect_modes_changed_ = false; + } + + ash::FakeChromeUserManager* fake_user_manager_ = nullptr; + std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_; + QuickUnlockPrivateSetModesFunction::ModesChangedEventHandler + modes_changed_handler_; + bool expect_modes_changed_ = false; + chromeos::UserContext auth_token_user_context_; + std::string token_; +}; + +// Verifies that GetAuthTokenValid succeeds when a valid password is provided. +TEST_P(QuickUnlockPrivateUnitTest, GetAuthTokenValid) { + std::unique_ptr<quick_unlock_private::TokenInfo> token_info = + GetAuthToken(kValidPassword); + + ash::quick_unlock::QuickUnlockStorage* quick_unlock_storage = + ash::quick_unlock::QuickUnlockFactory::GetForProfile(profile()); + EXPECT_EQ(token_info->token, + quick_unlock_storage->GetAuthToken()->Identifier()); + EXPECT_EQ(token_info->lifetime_seconds, + ash::quick_unlock::AuthToken::kTokenExpirationSeconds); +} + +// Verifies that GetAuthTokenValid fails when an invalid password is provided. +TEST_P(QuickUnlockPrivateUnitTest, GetAuthTokenInvalid) { + std::string error = RunAuthTokenWithInvalidPassword(); + EXPECT_FALSE(error.empty()); +} + +// Verifies that setting lock screen enabled modifies the setting. +TEST_P(QuickUnlockPrivateUnitTest, SetLockScreenEnabled) { + PrefService* pref_service = profile()->GetPrefs(); + bool lock_screen_enabled = + pref_service->GetBoolean(ash::prefs::kEnableAutoScreenLock); + + SetLockScreenEnabled(token(), !lock_screen_enabled); + + EXPECT_EQ(!lock_screen_enabled, + pref_service->GetBoolean(ash::prefs::kEnableAutoScreenLock)); +} + +// Verifies that setting lock screen enabled fails to modify the setting with +// an invalid token. +TEST_P(QuickUnlockPrivateUnitTest, SetLockScreenEnabledFailsWithInvalidToken) { + PrefService* pref_service = profile()->GetPrefs(); + bool lock_screen_enabled = + pref_service->GetBoolean(ash::prefs::kEnableAutoScreenLock); + + std::string error = + SetLockScreenEnabledWithInvalidToken(!lock_screen_enabled); + EXPECT_FALSE(error.empty()); + + EXPECT_EQ(lock_screen_enabled, + pref_service->GetBoolean(ash::prefs::kEnableAutoScreenLock)); +} + +// Verifies that this returns PIN for GetAvailableModes, unless it is blocked by +// policy. +TEST_P(QuickUnlockPrivateUnitTest, GetAvailableModes) { + EXPECT_EQ(GetAvailableModes(), + QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}); + + ash::quick_unlock::DisablePinByPolicyForTesting(true); + EXPECT_TRUE(GetAvailableModes().empty()); +} + +// Verfies that trying to set modes with a valid PIN failes when PIN is blocked +// by policy. +TEST_P(QuickUnlockPrivateUnitTest, SetModesForPinFailsWhenPinDisabledByPolicy) { + ash::quick_unlock::DisablePinByPolicyForTesting(true); + EXPECT_FALSE(SetModesWithError("[\"valid\", [\"PIN\"], [\"111\"]]").empty()); +} + +// Verifies that SetModes succeeds with a valid token. +TEST_P(QuickUnlockPrivateUnitTest, SetModes) { + // Verify there is no active mode. + EXPECT_EQ(GetActiveModes(), QuickUnlockModeList{}); + + RunSetModes(QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, + {"111111"}); + EXPECT_EQ(GetActiveModes(), + QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}); +} + +// Verifies that an invalid password cannot be used to update the mode list. +TEST_P(QuickUnlockPrivateUnitTest, SetModesFailsWithInvalidPassword) { + // Verify there is no active mode. + EXPECT_EQ(GetActiveModes(), QuickUnlockModeList{}); + + // Try to enable PIN, but use an invalid password. Verify that no event is + // raised and GetActiveModes still returns an empty set. + FailIfModesChanged(); + std::string error = RunSetModesWithInvalidToken(); + EXPECT_FALSE(error.empty()); + EXPECT_EQ(GetActiveModes(), QuickUnlockModeList{}); +} + +// Verifies that the quickUnlockPrivate.onActiveModesChanged is only raised when +// the active set of modes changes. +TEST_P(QuickUnlockPrivateUnitTest, ModeChangeEventOnlyRaisedWhenModesChange) { + // Make sure quick unlock is turned off, and then verify that turning it off + // again does not trigger an event. + RunSetModes(QuickUnlockModeList{}, CredentialList{}); + FailIfModesChanged(); + RunSetModes(QuickUnlockModeList{}, CredentialList{}); + + // Turn on PIN unlock, and then verify turning it on again and also changing + // the password does not trigger an event. + ExpectModesChanged( + QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}); + RunSetModes(QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, + {"111111"}); + FailIfModesChanged(); + RunSetModes(QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, + {"222222"}); + RunSetModes(QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, + {""}); +} + +// Ensures that quick unlock can be enabled and disabled by checking the result +// of quickUnlockPrivate.GetActiveModes and PinStoragePrefs::IsPinSet. +TEST_P(QuickUnlockPrivateUnitTest, SetModesAndGetActiveModes) { + // Update mode to PIN raises an event and updates GetActiveModes. + ExpectModesChanged( + QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}); + RunSetModes(QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, + {"111111"}); + EXPECT_EQ(GetActiveModes(), + QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}); + EXPECT_TRUE(IsPinSetInBackend()); + + // SetModes can be used to turn off a quick unlock mode. + ExpectModesChanged(QuickUnlockModeList{}); + RunSetModes(QuickUnlockModeList{}, CredentialList{}); + EXPECT_EQ(GetActiveModes(), QuickUnlockModeList{}); + EXPECT_FALSE(IsPinSetInBackend()); +} + +// Verifies that enabling PIN quick unlock actually talks to the PIN subsystem. +TEST_P(QuickUnlockPrivateUnitTest, VerifyAuthenticationAgainstPIN) { + RunSetModes(QuickUnlockModeList{}, CredentialList{}); + EXPECT_FALSE(IsPinSetInBackend()); + + RunSetModes(QuickUnlockModeList{QuickUnlockMode::QUICK_UNLOCK_MODE_PIN}, + {"111111"}); + EXPECT_TRUE(IsPinSetInBackend()); + + EXPECT_FALSE(TryAuthenticate("000000")); + EXPECT_TRUE(TryAuthenticate("111111")); + EXPECT_FALSE(TryAuthenticate("000000")); +} + +// Verifies that the number of modes and the number of passwords given must be +// the same. +TEST_P(QuickUnlockPrivateUnitTest, ThrowErrorOnMismatchedParameterCount) { + EXPECT_FALSE(SetModesWithError("[\"valid\", [\"PIN\"], []]").empty()); + EXPECT_FALSE(SetModesWithError("[\"valid\", [], [\"11\"]]").empty()); +} + +// Validates PIN error checking in conjuction with policy-related prefs. +TEST_P(QuickUnlockPrivateUnitTest, CheckCredentialProblemReporting) { + PrefService* pref_service = profile()->GetPrefs(); + + // Verify the pin checks work with the default preferences which are minimum + // length of 6, maximum length of 0 (no maximum) and no easy to guess check. + CheckPin(PIN_GOOD, "111112"); + CheckPin(PIN_GOOD, "1111112"); + CheckPin(PIN_GOOD, "1111111111111112"); + CheckPin(PIN_WEAK_WARNING, "111111"); + CheckPin(PIN_TOO_SHORT, "1"); + CheckPin(PIN_TOO_SHORT, "11"); + CheckPin(PIN_TOO_SHORT | PIN_WEAK_WARNING, "111"); + CheckPin(PIN_TOO_SHORT | PIN_CONTAINS_NONDIGIT, "a"); + CheckPin(PIN_CONTAINS_NONDIGIT, "aaaaab"); + CheckPin(PIN_CONTAINS_NONDIGIT | PIN_WEAK_WARNING, "aaaaaa"); + CheckPin(PIN_CONTAINS_NONDIGIT | PIN_WEAK_WARNING, "abcdef"); + + // Verify that now if the minimum length is set to 3, PINs of length 3 are + // accepted. + pref_service->SetInteger(ash::prefs::kPinUnlockMinimumLength, 3); + CheckPin(PIN_WEAK_WARNING, "111"); + + // Verify setting a nonzero maximum length that is less than the minimum + // length results in the pin only accepting PINs of length minimum length. + pref_service->SetInteger(ash::prefs::kPinUnlockMaximumLength, 2); + pref_service->SetInteger(ash::prefs::kPinUnlockMinimumLength, 4); + CheckPin(PIN_GOOD, "1112"); + CheckPin(PIN_TOO_SHORT, "112"); + CheckPin(PIN_TOO_LONG, "11112"); + + // Verify that now if the maximum length is set to 5, PINs longer than 5 are + // considered too long and cannot be used. + pref_service->SetInteger(ash::prefs::kPinUnlockMaximumLength, 5); + CheckPin(PIN_TOO_LONG | PIN_WEAK_WARNING, "111111"); + CheckPin(PIN_TOO_LONG | PIN_WEAK_WARNING, "1111111"); + + // Verify that if both the minimum length and maximum length is set to 4, only + // 4 digit PINs can be used. + pref_service->SetInteger(ash::prefs::kPinUnlockMinimumLength, 4); + pref_service->SetInteger(ash::prefs::kPinUnlockMaximumLength, 4); + CheckPin(PIN_TOO_SHORT, "122"); + CheckPin(PIN_TOO_LONG, "12222"); + CheckPin(PIN_GOOD, "1222"); + + // Set the PINs minimum/maximum lengths back to their defaults. + pref_service->SetInteger(ash::prefs::kPinUnlockMinimumLength, 4); + pref_service->SetInteger(ash::prefs::kPinUnlockMaximumLength, 0); + + // Verify that PINs that are weak are flagged as such. See + // IsPinDifficultEnough in quick_unlock_private_api.cc for the description of + // a weak pin. + pref_service->SetBoolean(ash::prefs::kPinUnlockWeakPinsAllowed, false); + // Good. + CheckPin(PIN_GOOD, "1112"); + CheckPin(PIN_GOOD, "7890"); + CheckPin(PIN_GOOD, "0987"); + // Same digits. + CheckPin(PIN_WEAK_ERROR, "1111"); + // Increasing. + CheckPin(PIN_WEAK_ERROR, "0123"); + CheckPin(PIN_WEAK_ERROR, "3456789"); + // Decreasing. + CheckPin(PIN_WEAK_ERROR, "3210"); + CheckPin(PIN_WEAK_ERROR, "987654"); + // Too common. + CheckPin(PIN_WEAK_ERROR, "1212"); + + // Verify that if a PIN has more than one error, both are returned. + CheckPin(PIN_TOO_SHORT | PIN_WEAK_ERROR, "111"); + CheckPin(PIN_TOO_SHORT | PIN_WEAK_ERROR, "234"); +} + +TEST_P(QuickUnlockPrivateUnitTest, GetCredentialRequirements) { + PrefService* pref_service = profile()->GetPrefs(); + + // Verify that trying out PINs under the minimum/maximum lengths will send the + // minimum/maximum lengths as additional information for display purposes. + pref_service->SetInteger(ash::prefs::kPinUnlockMinimumLength, 6); + pref_service->SetInteger(ash::prefs::kPinUnlockMaximumLength, 8); + CheckGetCredentialRequirements(6, 8); + + // Verify that by setting a maximum length to be nonzero and smaller than the + // minimum length, the resulting maxium length will be equal to the minimum + // length pref. + pref_service->SetInteger(ash::prefs::kPinUnlockMaximumLength, 4); + CheckGetCredentialRequirements(6, 6); + + // Verify that the values received from policy are sanitized. + pref_service->SetInteger(ash::prefs::kPinUnlockMinimumLength, -3); + pref_service->SetInteger(ash::prefs::kPinUnlockMaximumLength, -3); + CheckGetCredentialRequirements(1, 0); +} + +// Enabling a PIN will by default enable auto submit, unless it is +// recommended/forced by policy to be disabled. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitLongestPossiblePin) { + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + SetPin("123456789012"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_EQ(GetAutosubmitPrefVal(), feature_enabled); + EXPECT_EQ(GetExposedPinLength(), feature_enabled ? 12 : 0); +} + +// When recommended to be disabled, PIN auto submit will not be enabled when +// setting a PIN. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitRecommendedDisabled) { + test_pref_service_->SetRecommendedPref(::prefs::kPinUnlockAutosubmitEnabled, + std::make_unique<base::Value>(false)); + + SetPin("123456"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); +} + +// When forced to be disabled, PIN auto submit will not be enabled when +// setting a PIN. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitForcedDisabled) { + test_pref_service_->SetManagedPref(::prefs::kPinUnlockAutosubmitEnabled, + std::make_unique<base::Value>(false)); + + SetPin("123456"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); + + // Not possible to enable auto submit through Settings. The dialog + // that makes this call cannot even be opened because its a mandatory pref. + EXPECT_FALSE(SetPinAutosubmitEnabled("123456", true /*enabled*/)); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); +} + +// Setting a PIN that is longer than 12 digits does not enable auto submit. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitLongPinIsNotExposed) { + SetPin("1234567890123"); // 13 digits + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); +} + +// When auto submit is enabled, it remains enabled when the PIN is changed +// and the exposed length is updated. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitOnSetAndUpdate) { + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + + SetPin("123456"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_EQ(GetAutosubmitPrefVal(), feature_enabled); + EXPECT_EQ(GetExposedPinLength(), feature_enabled ? 6 : 0); + + SetPin("12345678"); + EXPECT_EQ(GetAutosubmitPrefVal(), feature_enabled); + EXPECT_EQ(GetExposedPinLength(), feature_enabled ? 8 : 0); +} + +// When auto submit is disabled, it remains disabled when the PIN is changed +// and the exposed length remains zero. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitBehaviorWhenDisabled) { + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + + SetPin("123456"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_EQ(GetAutosubmitPrefVal(), feature_enabled); + EXPECT_EQ(GetExposedPinLength(), feature_enabled ? 6 : 0); + + // Disable auto submit + EXPECT_EQ(SetPinAutosubmitEnabled("", false /*enabled*/), feature_enabled); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_EQ(HasUserValueForPinAutosubmitPref(), feature_enabled); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); + + // Change to a different PIN + SetPin("12345678"); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); + EXPECT_EQ(HasUserValueForPinAutosubmitPref(), feature_enabled); +} + +// Disabling PIN removes the user set value for auto submit and clears +// the exposed length. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitOnPinDisabled) { + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + + SetPin("123456"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_EQ(GetAutosubmitPrefVal(), feature_enabled); + EXPECT_EQ(GetExposedPinLength(), feature_enabled ? 6 : 0); + + // Disable PIN + ClearPin(); + EXPECT_FALSE(IsPinSetInBackend()); + EXPECT_FALSE(HasUserValueForPinAutosubmitPref()); + EXPECT_EQ(GetExposedPinLength(), 0); +} + +// If the user has no control over the preference, the pin length is collected +// upon a successful authentication attempt. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitCollectLengthOnAuthSuccess) { + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + + // Start with MANDATORY FALSE to prevent auto enabling when setting a PIN. + test_pref_service_->SetManagedPref(::prefs::kPinUnlockAutosubmitEnabled, + std::make_unique<base::Value>(false)); + SetPin("123456"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); + + // Autosubmit disabled, length unknown. Change to MANDATORY TRUE + test_pref_service_->SetManagedPref(::prefs::kPinUnlockAutosubmitEnabled, + std::make_unique<base::Value>(true)); + EXPECT_TRUE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); + + // Try to authenticate with the wrong pin. Length won't be exposed. + EXPECT_FALSE(TryAuthenticate("1234567")); + EXPECT_EQ(GetExposedPinLength(), 0); + + // Authenticate with the correct pin. Length is exposed. + EXPECT_TRUE(TryAuthenticate("123456")); + EXPECT_EQ(GetExposedPinLength(), feature_enabled ? 6 : 0); +} + +// If the user had PIN auto submit enabled and it was forced disabled via +// policy, the exposed length will be removed when the user pods are updated. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitClearLengthOnUiUpdate) { + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + + SetPin("123456"); + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_EQ(GetAutosubmitPrefVal(), feature_enabled); + EXPECT_EQ(GetExposedPinLength(), feature_enabled ? 6 : 0); + + // Switch to MANDATORY FALSE. + test_pref_service_->SetManagedPref(::prefs::kPinUnlockAutosubmitEnabled, + std::make_unique<base::Value>(false)); + + // Called during user pod update. + OnUpdateUserPods(); + + // Exposed length must have been cleared. + EXPECT_TRUE(IsPinSetInBackend()); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_EQ(GetExposedPinLength(), 0); +} + +// Checks that the feature flag correctly prevents all actions. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitFeatureGuard) { + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + EXPECT_EQ(ash::features::IsPinAutosubmitFeatureEnabled(), feature_enabled); +} + +// Tests that the backfill operation sets a user value for the auto submit pref +// for users who have set a PIN in a version of Chrome OS that did not support +// auto submit. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitBackfillDefaultPinLength) { + base::HistogramTester histogram_tester; + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + if (!feature_enabled) + return; + + SetPinForBackfillTests("123456"); + + // A successful authentication attempt will backfill the user value. + EXPECT_TRUE(TryAuthenticate("123456")); + EXPECT_EQ(GetExposedPinLength(), 6); + EXPECT_TRUE(HasUserValueForPinAutosubmitPref()); + EXPECT_TRUE(GetAutosubmitPrefVal()); + EXPECT_FALSE(IsBackfillNeeded()); + + histogram_tester.ExpectUniqueSample( + "Ash.Login.PinAutosubmit.Backfill", + ash::quick_unlock::PinBackend::BackfillEvent::kEnabled, 1); +} + +// No backfill operation if the PIN is longer than 6 digits. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitBackfillNonDefaultPinLength) { + base::HistogramTester histogram_tester; + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + if (!feature_enabled) + return; + + SetPinForBackfillTests("1234567"); + + // A successful authentication attempt will backfill the user value to false. + EXPECT_TRUE(TryAuthenticate("1234567")); + EXPECT_EQ(GetExposedPinLength(), 0); + EXPECT_TRUE(HasUserValueForPinAutosubmitPref()); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_FALSE(IsBackfillNeeded()); + + histogram_tester.ExpectUniqueSample( + "Ash.Login.PinAutosubmit.Backfill", + ash::quick_unlock::PinBackend::BackfillEvent::kDisabledDueToPinLength, 1); +} + +// Tests that the backfill operation sets a user value for the auto submit pref +// to false for enterprise users even with a default length of 6. +TEST_P(QuickUnlockPrivateUnitTest, PinAutosubmitBackfillEnterprise) { + base::HistogramTester histogram_tester; + const bool feature_enabled = IsAutosubmitFeatureEnabled(); + if (!feature_enabled) + return; + + // Enterprise users have auto submit disabled by default. + test_pref_service_->SetManagedPref(::prefs::kPinUnlockAutosubmitEnabled, + std::make_unique<base::Value>(false)); + + SetPinForBackfillTests("123456"); + + // A successful authentication attempt will backfill the user value to false. + EXPECT_TRUE(TryAuthenticate("123456")); + EXPECT_EQ(GetExposedPinLength(), 0); + EXPECT_TRUE(HasUserValueForPinAutosubmitPref()); + EXPECT_FALSE(GetAutosubmitPrefVal()); + EXPECT_FALSE(IsBackfillNeeded()); + + histogram_tester.ExpectUniqueSample( + "Ash.Login.PinAutosubmit.Backfill", + ash::quick_unlock::PinBackend::BackfillEvent::kDisabledDueToPolicy, 1); +} + +INSTANTIATE_TEST_SUITE_P( + StorageProviders, + QuickUnlockPrivateUnitTest, + testing::Combine(testing::Values(TestType::kPrefs, TestType::kCryptohome), + testing::Bool()), /*autosubmit*/ + QuickUnlockPrivateUnitTest::ParamInfoToString); + +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc index f799b14a58a..511c338c410 100644 --- a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc +++ b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.cc @@ -67,7 +67,7 @@ ResourcesPrivateGetStringsFunction::~ResourcesPrivateGetStringsFunction() {} ExtensionFunction::ResponseAction ResourcesPrivateGetStringsFunction::Run() { std::unique_ptr<get_strings::Params> params( - get_strings::Params::Create(*args_)); + get_strings::Params::Create(args())); auto dict = std::make_unique<base::DictionaryValue>(); api::resources_private::Component component = params->component; diff --git a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h index 4440d65734f..1f7c8c8b424 100644 --- a/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h +++ b/chromium/chrome/browser/extensions/api/resources_private/resources_private_api.h @@ -16,14 +16,16 @@ class ResourcesPrivateGetStringsFunction : public ExtensionFunction { RESOURCESPRIVATE_GETSTRINGS) ResourcesPrivateGetStringsFunction(); + ResourcesPrivateGetStringsFunction( + const ResourcesPrivateGetStringsFunction&) = delete; + ResourcesPrivateGetStringsFunction& operator=( + const ResourcesPrivateGetStringsFunction&) = delete; + protected: ~ResourcesPrivateGetStringsFunction() override; // Override from ExtensionFunction: ExtensionFunction::ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ResourcesPrivateGetStringsFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc index fa84ceb37f0..059415b2282 100644 --- a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc +++ b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.cc @@ -334,7 +334,8 @@ bool ChromeRuntimeAPIDelegate::GetPlatformInfo(PlatformInfo* info) { bool ChromeRuntimeAPIDelegate::RestartDevice(std::string* error_message) { #if BUILDFLAG(IS_CHROMEOS_ASH) - if (user_manager::UserManager::Get()->IsLoggedInAsKioskApp()) { + if (user_manager::UserManager::Get()->IsLoggedInAsKioskApp() || + user_manager::UserManager::Get()->IsLoggedInAsWebKioskApp()) { chromeos::PowerManagerClient::Get()->RequestRestart( power_manager::REQUEST_RESTART_OTHER, "chrome.runtime API"); return true; diff --git a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.h b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.h index b64a0c6877d..1549bdd67f4 100644 --- a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.h +++ b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate.h @@ -39,6 +39,10 @@ class ChromeRuntimeAPIDelegate : public extensions::RuntimeAPIDelegate, public extensions::ExtensionRegistryObserver { public: explicit ChromeRuntimeAPIDelegate(content::BrowserContext* context); + + ChromeRuntimeAPIDelegate(const ChromeRuntimeAPIDelegate&) = delete; + ChromeRuntimeAPIDelegate& operator=(const ChromeRuntimeAPIDelegate&) = delete; + ~ChromeRuntimeAPIDelegate() override; // Sets a custom TickClock to use in tests. @@ -93,8 +97,6 @@ class ChromeRuntimeAPIDelegate : public extensions::RuntimeAPIDelegate, base::ScopedObservation<extensions::ExtensionRegistry, extensions::ExtensionRegistryObserver> extension_registry_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(ChromeRuntimeAPIDelegate); }; #endif // CHROME_BROWSER_EXTENSIONS_API_RUNTIME_CHROME_RUNTIME_API_DELEGATE_H_ diff --git a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc index 37b56dc6e2d..2939de55541 100644 --- a/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc +++ b/chromium/chrome/browser/extensions/api/runtime/chrome_runtime_api_delegate_unittest.cc @@ -44,6 +44,10 @@ class TestEventRouter : public EventRouter { public: explicit TestEventRouter(content::BrowserContext* context) : EventRouter(context, ExtensionPrefs::Get(context)) {} + + TestEventRouter(const TestEventRouter&) = delete; + TestEventRouter& operator=(const TestEventRouter&) = delete; + ~TestEventRouter() override {} // An entry in our fake event registry. @@ -62,8 +66,6 @@ class TestEventRouter : public EventRouter { private: std::set<Entry> fake_registry_; - - DISALLOW_COPY_AND_ASSIGN(TestEventRouter); }; std::unique_ptr<KeyedService> TestEventRouterFactoryFunction( @@ -77,6 +79,9 @@ class DownloaderTestDelegate : public ExtensionDownloaderTestDelegate { public: DownloaderTestDelegate() {} + DownloaderTestDelegate(const DownloaderTestDelegate&) = delete; + DownloaderTestDelegate& operator=(const DownloaderTestDelegate&) = delete; + // On the next update check for extension |id|, we'll respond that no update // is available. void AddNoUpdateResponse(const std::string& id) { @@ -155,8 +160,6 @@ class DownloaderTestDelegate : public ExtensionDownloaderTestDelegate { // other. std::set<std::string> no_updates_; std::map<std::string, DownloadFinishedArgs> updates_; - - DISALLOW_COPY_AND_ASSIGN(DownloaderTestDelegate); }; // Helper to let test code wait for and return an update check result. @@ -164,6 +167,9 @@ class UpdateCheckResultCatcher { public: UpdateCheckResultCatcher() {} + UpdateCheckResultCatcher(const UpdateCheckResultCatcher&) = delete; + UpdateCheckResultCatcher& operator=(const UpdateCheckResultCatcher&) = delete; + void OnResult(const RuntimeAPIDelegate::UpdateCheckResult& result) { EXPECT_EQ(nullptr, result_.get()); result_ = std::make_unique<RuntimeAPIDelegate::UpdateCheckResult>( @@ -183,14 +189,16 @@ class UpdateCheckResultCatcher { private: std::unique_ptr<RuntimeAPIDelegate::UpdateCheckResult> result_; std::unique_ptr<base::RunLoop> run_loop_; - - DISALLOW_COPY_AND_ASSIGN(UpdateCheckResultCatcher); }; class ChromeRuntimeAPIDelegateTest : public ExtensionServiceTestWithInstall { public: ChromeRuntimeAPIDelegateTest() {} + ChromeRuntimeAPIDelegateTest(const ChromeRuntimeAPIDelegateTest&) = delete; + ChromeRuntimeAPIDelegateTest& operator=(const ChromeRuntimeAPIDelegateTest&) = + delete; + void SetUp() override { ExtensionServiceTestWithInstall::SetUp(); ExtensionDownloader::set_test_delegate(&downloader_test_delegate_); @@ -253,9 +261,6 @@ class ChromeRuntimeAPIDelegateTest : public ExtensionServiceTestWithInstall { // For preventing extensions from being updated immediately. std::unique_ptr<UpdateInstallGate> update_install_gate_; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeRuntimeAPIDelegateTest); }; TEST_F(ChromeRuntimeAPIDelegateTest, RequestUpdateCheck) { @@ -287,14 +292,14 @@ TEST_F(ChromeRuntimeAPIDelegateTest, RequestUpdateCheck) { // Check again after a short delay - we should be throttled because // not enough time has passed. - clock_.Advance(base::TimeDelta::FromMinutes(15)); + clock_.Advance(base::Minutes(15)); downloader_test_delegate_.AddNoUpdateResponse(id); DoUpdateCheck(id, "throttled", ""); // Now simulate checking a few times at a 6 hour interval - none of these // should be throttled. for (int i = 0; i < 5; i++) { - clock_.Advance(base::TimeDelta::FromHours(6)); + clock_.Advance(base::Hours(6)); downloader_test_delegate_.AddNoUpdateResponse(id); DoUpdateCheck(id, "no_update", ""); } @@ -302,13 +307,13 @@ TEST_F(ChromeRuntimeAPIDelegateTest, RequestUpdateCheck) { // Run an update check that should get an "update_available" response. This // actually causes the new version to be downloaded/unpacked, but the install // will not complete until we reload the extension. - clock_.Advance(base::TimeDelta::FromDays(1)); + clock_.Advance(base::Days(1)); downloader_test_delegate_.AddUpdateResponse(id, v2_path, "2.0"); DoUpdateCheck(id, "update_available", "2.0"); // Call again after short delay - it should be throttled instead of getting // another "update_available" response. - clock_.Advance(base::TimeDelta::FromMinutes(30)); + clock_.Advance(base::Minutes(30)); downloader_test_delegate_.AddUpdateResponse(id, v2_path, "2.0"); DoUpdateCheck(id, "throttled", ""); @@ -319,16 +324,16 @@ TEST_F(ChromeRuntimeAPIDelegateTest, RequestUpdateCheck) { ExtensionRegistry::Get(browser_context())->GetInstalledExtension(id); ASSERT_NE(nullptr, current); EXPECT_EQ("2.0", current->VersionString()); - clock_.Advance(base::TimeDelta::FromSeconds(10)); + clock_.Advance(base::Seconds(10)); downloader_test_delegate_.AddNoUpdateResponse(id); DoUpdateCheck(id, "no_update", ""); // Check again after short delay; we should be throttled. - clock_.Advance(base::TimeDelta::FromMinutes(5)); + clock_.Advance(base::Minutes(5)); DoUpdateCheck(id, "throttled", ""); // Call again after a longer delay, we should should be unthrottled. - clock_.Advance(base::TimeDelta::FromHours(8)); + clock_.Advance(base::Hours(8)); downloader_test_delegate_.AddNoUpdateResponse(id); DoUpdateCheck(id, "no_update", ""); } @@ -340,6 +345,9 @@ class ExtensionLoadWaiter : public ExtensionRegistryObserver { extension_registry_observation_.Observe(ExtensionRegistry::Get(context_)); } + ExtensionLoadWaiter(const ExtensionLoadWaiter&) = delete; + ExtensionLoadWaiter& operator=(const ExtensionLoadWaiter&) = delete; + void WaitForReload() { run_loop_.Run(); } protected: @@ -369,14 +377,17 @@ class ExtensionLoadWaiter : public ExtensionRegistryObserver { content::BrowserContext* context_; base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(ExtensionLoadWaiter); }; class ChromeRuntimeAPIDelegateReloadTest : public ChromeRuntimeAPIDelegateTest { public: ChromeRuntimeAPIDelegateReloadTest() {} + ChromeRuntimeAPIDelegateReloadTest( + const ChromeRuntimeAPIDelegateReloadTest&) = delete; + ChromeRuntimeAPIDelegateReloadTest& operator=( + const ChromeRuntimeAPIDelegateReloadTest&) = delete; + void SetUp() override { ChromeRuntimeAPIDelegateTest::SetUp(); @@ -398,8 +409,6 @@ class ChromeRuntimeAPIDelegateReloadTest : public ChromeRuntimeAPIDelegateTest { private: ExtensionId extension_id_; - - DISALLOW_COPY_AND_ASSIGN(ChromeRuntimeAPIDelegateReloadTest); }; TEST_F(ChromeRuntimeAPIDelegateReloadTest, @@ -437,7 +446,7 @@ TEST_F(ChromeRuntimeAPIDelegateReloadTest, // Reload one more time after the time threshold for a suspiciously fast // reload has passed. - clock_.Advance(base::TimeDelta::FromSeconds(1000)); + clock_.Advance(base::Seconds(1000)); ReloadExtensionAndWait(); EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id())); diff --git a/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc b/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc index 1819fe2fcba..4586cd8d23d 100644 --- a/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc +++ b/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc @@ -33,21 +33,10 @@ using ContextType = ExtensionBrowserTest::ContextType; class RuntimeApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - RuntimeApiTest() = default; + RuntimeApiTest() : ExtensionApiTest(GetParam()) {} ~RuntimeApiTest() override = default; RuntimeApiTest(const RuntimeApiTest&) = delete; RuntimeApiTest& operator=(const RuntimeApiTest&) = delete; - - const Extension* LoadExtensionWithParamOptions(const base::FilePath& path) { - return LoadExtension(path, {.load_as_service_worker = - GetParam() == ContextType::kServiceWorker}); - } - - bool RunTestWithParamOptions(const char* extension_name) { - return RunExtensionTest( - extension_name, {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -60,19 +49,19 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, // Tests the privileged components of chrome.runtime. IN_PROC_BROWSER_TEST_P(RuntimeApiTest, ChromeRuntimePrivileged) { - ASSERT_TRUE(RunTestWithParamOptions("runtime/privileged")) << message_; + ASSERT_TRUE(RunExtensionTest("runtime/privileged")) << message_; } // Tests the unprivileged components of chrome.runtime. IN_PROC_BROWSER_TEST_P(RuntimeApiTest, ChromeRuntimeUnprivileged) { ASSERT_TRUE(StartEmbeddedTestServer()); - ASSERT_TRUE(LoadExtensionWithParamOptions( - test_data_dir_.AppendASCII("runtime/content_script"))); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("runtime/content_script"))); // The content script runs on this page. extensions::ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), - embedded_test_server()->GetURL("/title1.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/title1.html"))); EXPECT_TRUE(catcher.GetNextResult()) << message_; } @@ -89,16 +78,15 @@ IN_PROC_BROWSER_TEST_P(RuntimeApiTest, ChromeRuntimeUninstallURL) { extensions::ScopedTestDialogAutoConfirm auto_confirm( extensions::ScopedTestDialogAutoConfirm::ACCEPT); ExtensionTestMessageListener ready_listener("ready", false); - ASSERT_TRUE( - LoadExtensionWithParamOptions(test_data_dir_.AppendASCII("runtime") - .AppendASCII("uninstall_url") - .AppendASCII("sets_uninstall_url"))); + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("runtime") + .AppendASCII("uninstall_url") + .AppendASCII("sets_uninstall_url"))); EXPECT_TRUE(ready_listener.WaitUntilSatisfied()); - ASSERT_TRUE(RunTestWithParamOptions("runtime/uninstall_url")) << message_; + ASSERT_TRUE(RunExtensionTest("runtime/uninstall_url")) << message_; } IN_PROC_BROWSER_TEST_P(RuntimeApiTest, GetPlatformInfo) { - ASSERT_TRUE(RunTestWithParamOptions("runtime/get_platform_info")) << message_; + ASSERT_TRUE(RunExtensionTest("runtime/get_platform_info")) << message_; } namespace { @@ -116,6 +104,9 @@ class RuntimeAPIUpdateTest : public ExtensionApiTest { public: RuntimeAPIUpdateTest() {} + RuntimeAPIUpdateTest(const RuntimeAPIUpdateTest&) = delete; + RuntimeAPIUpdateTest& operator=(const RuntimeAPIUpdateTest&) = delete; + protected: void SetUpOnMainThread() override { ExtensionApiTest::SetUpOnMainThread(); @@ -155,8 +146,6 @@ class RuntimeAPIUpdateTest : public ExtensionApiTest { private: base::ScopedTempDir scoped_temp_dir_; - - DISALLOW_COPY_AND_ASSIGN(RuntimeAPIUpdateTest); }; } // namespace @@ -338,9 +327,9 @@ IN_PROC_BROWSER_TEST_P(RuntimeApiTest, ExtensionTestMessageListener ready_listener("ready", false); // Load an extension that has set an uninstall url. scoped_refptr<const extensions::Extension> extension = - LoadExtensionWithParamOptions(test_data_dir_.AppendASCII("runtime") - .AppendASCII("uninstall_url") - .AppendASCII("sets_uninstall_url")); + LoadExtension(test_data_dir_.AppendASCII("runtime") + .AppendASCII("uninstall_url") + .AppendASCII("sets_uninstall_url")); EXPECT_TRUE(ready_listener.WaitUntilSatisfied()); ASSERT_TRUE(extension.get()); extension_service()->AddExtension(extension.get()); @@ -363,10 +352,9 @@ IN_PROC_BROWSER_TEST_P(RuntimeApiTest, // Load the same extension again, except blocklist it after installation. ExtensionTestMessageListener ready_listener_reload("ready", false); - extension = - LoadExtensionWithParamOptions(test_data_dir_.AppendASCII("runtime") - .AppendASCII("uninstall_url") - .AppendASCII("sets_uninstall_url")); + extension = LoadExtension(test_data_dir_.AppendASCII("runtime") + .AppendASCII("uninstall_url") + .AppendASCII("sets_uninstall_url")); EXPECT_TRUE(ready_listener_reload.WaitUntilSatisfied()); extension_service()->AddExtension(extension.get()); ASSERT_TRUE(extension_service()->IsExtensionEnabled(extension->id())); diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc index cf396629f2a..7971b8bc628 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.cc @@ -42,7 +42,7 @@ SafeBrowsingPrivateGetReferrerChainFunction:: ExtensionFunction::ResponseAction SafeBrowsingPrivateGetReferrerChainFunction::Run() { std::unique_ptr<api::safe_browsing_private::GetReferrerChain::Params> params = - api::safe_browsing_private::GetReferrerChain::Params::Create(*args_); + api::safe_browsing_private::GetReferrerChain::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); content::WebContents* contents = nullptr; diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h index 13980a7608a..25f688e775b 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api.h @@ -16,13 +16,16 @@ class SafeBrowsingPrivateGetReferrerChainFunction : public ExtensionFunction { SafeBrowsingPrivateGetReferrerChainFunction(); + SafeBrowsingPrivateGetReferrerChainFunction( + const SafeBrowsingPrivateGetReferrerChainFunction&) = delete; + SafeBrowsingPrivateGetReferrerChainFunction& operator=( + const SafeBrowsingPrivateGetReferrerChainFunction&) = delete; + protected: ~SafeBrowsingPrivateGetReferrerChainFunction() override; // ExtensionFunction: ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateGetReferrerChainFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc index 08e03b288e1..54b4f8cc067 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_api_unittest.cc @@ -24,7 +24,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/test_browser_window.h" #include "chrome/test/base/testing_browser_process.h" -#include "components/password_manager/core/browser/mock_password_store.h" +#include "components/password_manager/core/browser/mock_password_store_interface.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/sessions/content/session_tab_helper.h" #include "content/public/browser/browser_task_traits.h" @@ -103,15 +103,17 @@ void SafeBrowsingPrivateApiUnitTest::SetUp() { PasswordStoreFactory::GetInstance()->SetTestingFactoryAndUse( profile(), - base::BindRepeating(&password_manager::BuildPasswordStore< - content::BrowserContext, - NiceMock<password_manager::MockPasswordStore>>)); + base::BindRepeating( + &password_manager::BuildPasswordStoreInterface< + content::BrowserContext, + NiceMock<password_manager::MockPasswordStoreInterface>>)); AccountPasswordStoreFactory::GetInstance()->SetTestingFactoryAndUse( profile(), - base::BindRepeating(&password_manager::BuildPasswordStore< - content::BrowserContext, - NiceMock<password_manager::MockPasswordStore>>)); + base::BindRepeating( + &password_manager::BuildPasswordStoreInterface< + content::BrowserContext, + NiceMock<password_manager::MockPasswordStoreInterface>>)); // Initialize Safe Browsing service. safe_browsing::TestSafeBrowsingServiceFactory sb_service_factory; diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc index 34e78ca5922..332a147348f 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.cc @@ -45,7 +45,6 @@ #include "url/gurl.h" #if BUILDFLAG(IS_CHROMEOS_ASH) -#include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" #include "chrome/browser/ash/policy/core/user_cloud_policy_manager_ash.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/browser_process_platform_part_chromeos.h" @@ -74,7 +73,8 @@ void AddAnalysisConnectorVerdictToEvent( base::Value* event) { DCHECK(event); base::ListValue triggered_rule_info; - for (const auto& trigger : result.triggered_rules()) { + for (const enterprise_connectors::TriggeredRule& trigger : + result.triggered_rules()) { base::Value triggered_rule(base::Value::Type::DICTIONARY); triggered_rule.SetStringKey( extensions::SafeBrowsingPrivateEventRouter::kKeyTriggeredRuleName, @@ -166,6 +166,18 @@ const char SafeBrowsingPrivateEventRouter::kKeyMalwareCategory[] = const char SafeBrowsingPrivateEventRouter::kKeyEvidenceLockerFilePath[] = "evidenceLockerFilepath"; const char SafeBrowsingPrivateEventRouter::kKeyScanId[] = "scanId"; +const char SafeBrowsingPrivateEventRouter::kKeyIsFederated[] = "isFederated"; +const char SafeBrowsingPrivateEventRouter::kKeyFederatedOrigin[] = + "federatedOrigin"; +const char SafeBrowsingPrivateEventRouter::kKeyLoginUserName[] = + "loginUserName"; +const char SafeBrowsingPrivateEventRouter::kKeyPasswordBreachIdentities[] = + "identities"; +const char SafeBrowsingPrivateEventRouter::kKeyPasswordBreachIdentitiesUrl[] = + "url"; +const char + SafeBrowsingPrivateEventRouter::kKeyPasswordBreachIdentitiesUsername[] = + "username"; // All new event names should be added to the kAllEvents array below! const char SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent[] = @@ -180,14 +192,19 @@ const char SafeBrowsingPrivateEventRouter::kKeySensitiveDataEvent[] = "sensitiveDataEvent"; const char SafeBrowsingPrivateEventRouter::kKeyUnscannedFileEvent[] = "unscannedFileEvent"; +const char SafeBrowsingPrivateEventRouter::kKeyLoginEvent[] = "loginEvent"; +const char SafeBrowsingPrivateEventRouter::kKeyPasswordBreachEvent[] = + "passwordBreachEvent"; // All new event names should be added to this array! -const char* SafeBrowsingPrivateEventRouter::kAllEvents[6] = { +const char* SafeBrowsingPrivateEventRouter::kAllEvents[8] = { SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent, SafeBrowsingPrivateEventRouter::kKeyPasswordChangedEvent, SafeBrowsingPrivateEventRouter::kKeyDangerousDownloadEvent, SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent, SafeBrowsingPrivateEventRouter::kKeySensitiveDataEvent, SafeBrowsingPrivateEventRouter::kKeyUnscannedFileEvent, + SafeBrowsingPrivateEventRouter::kKeyLoginEvent, + SafeBrowsingPrivateEventRouter::kKeyPasswordBreachEvent, }; const char SafeBrowsingPrivateEventRouter::kKeyUnscannedReason[] = @@ -237,7 +254,8 @@ void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordReuseDetected( event_router_->BroadcastEvent(std::move(extension_event)); } - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyPasswordReuseEvent) == 0) { return; @@ -267,7 +285,8 @@ void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordChanged( event_router_->BroadcastEvent(std::move(extension_event)); } - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyPasswordChangedEvent) == 0) { return; @@ -307,7 +326,8 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDownloadOpened( event_router_->BroadcastEvent(std::move(extension_event)); } - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyDangerousDownloadEvent) == 0) { return; @@ -363,14 +383,15 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialShown( event_router_->BroadcastEvent(std::move(extension_event)); } - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyInterstitialEvent) == 0) { return; } PrefService* prefs = Profile::FromBrowserContext(context_)->GetPrefs(); - auto event_result = + safe_browsing::EventResult event_result = prefs->GetBoolean(prefs::kSafeBrowsingProceedAnywayDisabled) ? safe_browsing::EventResult::BLOCKED : safe_browsing::EventResult::WARNED; @@ -412,7 +433,8 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded( event_router_->BroadcastEvent(std::move(extension_event)); } - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyInterstitialEvent) == 0) { return; @@ -469,7 +491,8 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult( const std::string& malware_category, const std::string& evidence_locker_filepath, const std::string& scan_id) { - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyDangerousDownloadEvent) == 0) { return; @@ -517,7 +540,8 @@ void SafeBrowsingPrivateEventRouter::OnSensitiveDataEvent( const enterprise_connectors::ContentAnalysisResponse::Result& result, const int64_t content_size, safe_browsing::EventResult event_result) { - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeySensitiveDataEvent) == 0) { return; @@ -560,7 +584,8 @@ void SafeBrowsingPrivateEventRouter::OnAnalysisConnectorWarningBypassed( safe_browsing::DeepScanAccessPoint access_point, const enterprise_connectors::ContentAnalysisResponse::Result& result, const int64_t content_size) { - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeySensitiveDataEvent) == 0) { return; @@ -603,7 +628,8 @@ void SafeBrowsingPrivateEventRouter::OnUnscannedFileEvent( const std::string& reason, const int64_t content_size, safe_browsing::EventResult event_result) { - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyUnscannedFileEvent) == 0) { return; @@ -653,7 +679,8 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDownloadEvent( const std::string& scan_id, const int64_t content_size, safe_browsing::EventResult event_result) { - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyDangerousDownloadEvent) == 0) { return; @@ -705,7 +732,8 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDownloadWarningBypassed( const std::string& mime_type, const std::string& scan_id, const int64_t content_size) { - auto settings = GetReportingSettings(); + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); if (!settings.has_value() || settings->enabled_event_names.count(kKeyDangerousDownloadEvent) == 0) { return; @@ -736,6 +764,57 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDownloadWarningBypassed( std::move(event)); } +void SafeBrowsingPrivateEventRouter::OnLoginEvent( + const GURL& url, + bool is_federated, + const url::Origin& federated_origin, + const std::u16string& username) { + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); + if (!settings.has_value() || + settings->enabled_event_names.count(kKeyLoginEvent) == 0) { + return; + } + + base::Value event(base::Value::Type::DICTIONARY); + event.SetStringKey(kKeyUrl, url.spec()); + event.SetBoolKey(kKeyIsFederated, is_federated); + if (is_federated) + event.SetStringKey(kKeyFederatedOrigin, federated_origin.Serialize()); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + event.SetStringKey(kKeyLoginUserName, username); + + ReportRealtimeEvent(kKeyLoginEvent, std::move(settings.value()), + std::move(event)); +} + +void SafeBrowsingPrivateEventRouter::OnPasswordBreach( + const std::string& trigger, + const std::vector<std::pair<GURL, std::u16string>>& identities) { + absl::optional<enterprise_connectors::ReportingSettings> settings = + GetReportingSettings(); + if (!settings.has_value() || + settings->enabled_event_names.count(kKeyPasswordBreachEvent) == 0) { + return; + } + + base::Value event(base::Value::Type::DICTIONARY); + std::vector<base::Value> identities_list; + event.SetStringKey(kKeyTrigger, trigger); + for (const std::pair<GURL, std::u16string>& i : identities) { + base::Value identity(base::Value::Type::DICTIONARY); + identity.SetStringKey(kKeyPasswordBreachIdentitiesUrl, i.first.spec()); + identity.SetStringKey(kKeyPasswordBreachIdentitiesUsername, i.second); + identities_list.push_back(std::move(identity)); + } + event.SetKey(kKeyPasswordBreachIdentities, + base::Value(std::move(identities_list))); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + + ReportRealtimeEvent(kKeyPasswordBreachEvent, std::move(settings.value()), + std::move(event)); +} + // static bool SafeBrowsingPrivateEventRouter::ShouldInitRealtimeReportingClient() { if (!base::FeatureList::IsEnabled(kRealtimeReportingFeature) && @@ -745,11 +824,6 @@ bool SafeBrowsingPrivateEventRouter::ShouldInitRealtimeReportingClient() { return false; } - if (!IsRealtimeReportingAvailable()) { - DVLOG(1) << "Safe browsing real-time event reporting is only available for " - "managed browsers, devices or users."; - return false; - } return true; } @@ -803,11 +877,12 @@ void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient( policy::CloudPolicyClient* client = nullptr; std::string policy_client_desc; #if BUILDFLAG(IS_CHROMEOS_ASH) - auto desc_and_client = InitBrowserReportingClient(settings.dm_token); + std::pair<std::string, policy::CloudPolicyClient*> desc_and_client = + InitBrowserReportingClient(settings.dm_token); #else - auto desc_and_client = settings.per_profile - ? InitProfileReportingClient(settings.dm_token) - : InitBrowserReportingClient(settings.dm_token); + std::pair<std::string, policy::CloudPolicyClient*> desc_and_client = + settings.per_profile ? InitProfileReportingClient(settings.dm_token) + : InitBrowserReportingClient(settings.dm_token); #endif if (!desc_and_client.second) return; @@ -841,9 +916,9 @@ SafeBrowsingPrivateEventRouter::InitBrowserReportingClient( policy::CloudPolicyClient* client = nullptr; #if BUILDFLAG(IS_CHROMEOS_ASH) - auto* user = GetChromeOSUser(); + const user_manager::User* user = GetChromeOSUser(); if (user) { - auto* profile = chromeos::ProfileHelper::Get()->GetProfileByUser(user); + Profile* profile = chromeos::ProfileHelper::Get()->GetProfileByUser(user); // If primary user profile is not finalized, use the current profile. if (!profile) profile = Profile::FromBrowserContext(context_); @@ -853,7 +928,8 @@ SafeBrowsingPrivateEventRouter::InitBrowserReportingClient( policy_client_desc = kActiveDirectoryPolicyClientDescription; } else { policy_client_desc = kUserPolicyClientDescription; - auto* policy_manager = profile->GetUserCloudPolicyManagerAsh(); + policy::UserCloudPolicyManagerAsh* policy_manager = + profile->GetUserCloudPolicyManagerAsh(); if (policy_manager) client = policy_manager->core()->client(); } @@ -954,7 +1030,7 @@ void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent( #ifndef NDEBUG // Make sure that the event is included in the kAllEvents array. bool found = false; - for (auto* known_event_name : + for (const char* known_event_name : extensions::SafeBrowsingPrivateEventRouter::kAllEvents) { if (name == known_event_name) { found = true; @@ -979,7 +1055,8 @@ void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent( now_exploded.month, now_exploded.day_of_month, now_exploded.hour, now_exploded.minute, now_exploded.second, now_exploded.millisecond); - auto* client = settings.per_profile ? profile_client_ : browser_client_; + policy::CloudPolicyClient* client = + settings.per_profile ? profile_client_ : browser_client_; base::Value wrapper(base::Value::Type::DICTIONARY); wrapper.SetStringKey("time", now_str); wrapper.SetKey(name, std::move(event)); @@ -1023,25 +1100,6 @@ const user_manager::User* SafeBrowsingPrivateEventRouter::GetChromeOSUser() { #endif -bool SafeBrowsingPrivateEventRouter::IsRealtimeReportingAvailable() { -#if BUILDFLAG(IS_CHROMEOS_ASH) - // The device must be managed. - if (!g_browser_process->platform_part() - ->browser_policy_connector_ash() - ->IsDeviceEnterpriseManaged()) - return false; - - // The Chrome OS user must be affiliated with the device. - // This also implies that the user is managed. - auto* user = GetChromeOSUser(); - return user && user->IsAffiliated(); -#else - // The management status is determined by the settings returned by - // ConnectorsService. - return true; -#endif -} - void SafeBrowsingPrivateEventRouter::RemoveDmTokenFromRejectedSet( const std::string& dm_token) { rejected_dm_token_timers_.erase(dm_token); @@ -1065,7 +1123,7 @@ void SafeBrowsingPrivateEventRouter::OnClientError( rejected_dm_token_timers_[client->dm_token()] = std::make_unique<base::OneShotTimer>(); rejected_dm_token_timers_[client->dm_token()]->Start( - FROM_HERE, base::TimeDelta::FromHours(24), + FROM_HERE, base::Hours(24), base::BindOnce( &SafeBrowsingPrivateEventRouter::RemoveDmTokenFromRejectedSet, weak_ptr_factory_.GetWeakPtr(), client->dm_token())); diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h index 2939379ee00..4d7034acd3b 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router.h @@ -86,6 +86,12 @@ class SafeBrowsingPrivateEventRouter static const char kKeyMalwareCategory[]; static const char kKeyEvidenceLockerFilePath[]; static const char kKeyScanId[]; + static const char kKeyIsFederated[]; + static const char kKeyFederatedOrigin[]; + static const char kKeyLoginUserName[]; + static const char kKeyPasswordBreachIdentities[]; + static const char kKeyPasswordBreachIdentitiesUrl[]; + static const char kKeyPasswordBreachIdentitiesUsername[]; static const char kKeyPasswordReuseEvent[]; static const char kKeyPasswordChangedEvent[]; @@ -93,7 +99,9 @@ class SafeBrowsingPrivateEventRouter static const char kKeyInterstitialEvent[]; static const char kKeySensitiveDataEvent[]; static const char kKeyUnscannedFileEvent[]; - static const char* kAllEvents[6]; + static const char kKeyLoginEvent[]; + static const char kKeyPasswordBreachEvent[]; + static const char* kAllEvents[8]; static const char kKeyUnscannedReason[]; @@ -105,6 +113,11 @@ class SafeBrowsingPrivateEventRouter explicit SafeBrowsingPrivateEventRouter(content::BrowserContext* context); + SafeBrowsingPrivateEventRouter(const SafeBrowsingPrivateEventRouter&) = + delete; + SafeBrowsingPrivateEventRouter& operator=( + const SafeBrowsingPrivateEventRouter&) = delete; + ~SafeBrowsingPrivateEventRouter() override; // Notifies listeners that the user reused a protected password. @@ -215,6 +228,15 @@ class SafeBrowsingPrivateEventRouter const std::string& scan_id, const int64_t content_size); + void OnLoginEvent(const GURL& url, + bool is_federated, + const url::Origin& federated_origin, + const std::u16string& username); + + void OnPasswordBreach( + const std::string& trigger, + const std::vector<std::pair<GURL, std::u16string>>& identities); + // Returns true if enterprise real-time reporting should be initialized, // checking both the feature flag. This function is public so that it can // called in tests. @@ -343,7 +365,6 @@ class SafeBrowsingPrivateEventRouter rejected_dm_token_timers_; base::WeakPtrFactory<SafeBrowsingPrivateEventRouter> weak_ptr_factory_{this}; - DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h index b5e98c491a1..a5a4c9809fd 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h @@ -19,6 +19,11 @@ class SafeBrowsingPrivateEventRouter; class SafeBrowsingPrivateEventRouterFactory : public BrowserContextKeyedServiceFactory { public: + SafeBrowsingPrivateEventRouterFactory( + const SafeBrowsingPrivateEventRouterFactory&) = delete; + SafeBrowsingPrivateEventRouterFactory& operator=( + const SafeBrowsingPrivateEventRouterFactory&) = delete; + // Returns the SafeBrowsingPrivateEventRouter for |profile|, creating it if // it is not yet created. static SafeBrowsingPrivateEventRouter* GetForProfile( @@ -44,8 +49,6 @@ class SafeBrowsingPrivateEventRouterFactory // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; - - DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouterFactory); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc index 98ea93aabe2..6e3f837c507 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_unittest.cc @@ -82,6 +82,10 @@ class SafeBrowsingEventObserver : public TestEventRouter::EventObserver { explicit SafeBrowsingEventObserver(const std::string& event_name) : event_name_(event_name) {} + SafeBrowsingEventObserver(const SafeBrowsingEventObserver&) = delete; + SafeBrowsingEventObserver& operator=(const SafeBrowsingEventObserver&) = + delete; + ~SafeBrowsingEventObserver() override = default; // Removes |event_args_| from |*this| and returns them. @@ -100,8 +104,6 @@ class SafeBrowsingEventObserver : public TestEventRouter::EventObserver { // The arguments passed for the last observed event. base::Value event_args_; - - DISALLOW_COPY_AND_ASSIGN(SafeBrowsingEventObserver); }; std::unique_ptr<KeyedService> BuildSafeBrowsingPrivateEventRouter( @@ -207,6 +209,24 @@ class SafeBrowsingPrivateEventRouterTestBase : public testing::Test { "filePasswordProtected", 12345, result); } + void TriggerOnLoginEvent( + const GURL& url, + const std::u16string& login_user_name, + absl::optional<url::Origin> federated_origin = absl::nullopt) { + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) + ->OnLoginEvent(url, federated_origin.has_value(), + federated_origin.has_value() ? federated_origin.value() + : url::Origin(), + login_user_name); + } + + void TriggerOnPasswordBreachEvent( + const std::string& trigger, + const std::vector<std::pair<GURL, std::u16string>>& identities) { + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) + ->OnPasswordBreach(trigger, identities); + } + void SetReportingPolicy(bool enabled, bool authorized = true, const std::set<std::string>& enabled_event_names = @@ -720,6 +740,69 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, EXPECT_EQ(base::Value::Type::NONE, report.type()); } +TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnLoginEvent) { + SetUpRouters(); + + signin::IdentityTestEnvironment identity_test_environment; + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) + ->SetIdentityManagerForTesting( + identity_test_environment.identity_manager()); + identity_test_environment.MakePrimaryAccountAvailable( + profile_->GetProfileUserName(), signin::ConsentLevel::kSignin); + + safe_browsing::EventReportValidator validator(client_.get()); + validator.ExpectLoginEvent("https://www.example.com/", false, "", + profile_->GetProfileUserName(), u"login-username"); + + TriggerOnLoginEvent(GURL("https://www.example.com/"), u"login-username"); +} + +TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnLoginEventFederated) { + SetUpRouters(); + + signin::IdentityTestEnvironment identity_test_environment; + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) + ->SetIdentityManagerForTesting( + identity_test_environment.identity_manager()); + identity_test_environment.MakePrimaryAccountAvailable( + profile_->GetProfileUserName(), signin::ConsentLevel::kSignin); + + safe_browsing::EventReportValidator validator(client_.get()); + validator.ExpectLoginEvent("https://www.example.com/", true, + "https://www.google.com", + profile_->GetProfileUserName(), u"login-username"); + + TriggerOnLoginEvent(GURL("https://www.example.com/"), u"login-username", + url::Origin::Create(GURL("https://www.google.com"))); +} + +TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnPasswordBreach) { + SetUpRouters(); + + signin::IdentityTestEnvironment identity_test_environment; + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) + ->SetIdentityManagerForTesting( + identity_test_environment.identity_manager()); + identity_test_environment.MakePrimaryAccountAvailable( + profile_->GetProfileUserName(), signin::ConsentLevel::kSignin); + + safe_browsing::EventReportValidator validator(client_.get()); + validator.ExpectPasswordBreachEvent( + "SAFETY_CHECK", + { + {"https://first.example.com/", u"first_user_name"}, + {"https://second.example.com/", u"second_user_name"}, + }, + profile_->GetProfileUserName()); + + TriggerOnPasswordBreachEvent( + "SAFETY_CHECK", + { + {GURL("https://first.example.com"), u"first_user_name"}, + {GURL("https://second.example.com"), u"second_user_name"}, + }); +} + TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSensitiveDataEvent_Allowed) { SetUpRouters(/*authorized=*/true); @@ -1152,11 +1235,7 @@ class SafeBrowsingIsRealtimeReportingEnabledTest } bool should_init() { -#if !BUILDFLAG(IS_CHROMEOS_ASH) return is_feature_flag_enabled_; -#else - return is_feature_flag_enabled_ && is_manageable_; -#endif } protected: @@ -1190,9 +1269,6 @@ TEST_P(SafeBrowsingIsRealtimeReportingEnabledTest, CheckRealtimeReport) { bool should_report = is_feature_flag_enabled_ && is_policy_enabled_ && is_authorized_; -#if BUILDFLAG(IS_CHROMEOS_ASH) - should_report &= is_manageable_; -#endif if (should_report) { EXPECT_CALL(*client_, UploadSecurityEventReport_(_, _, _, _)).Times(1); diff --git a/chromium/chrome/browser/extensions/api/scripting/scripting_api.cc b/chromium/chrome/browser/extensions/api/scripting/scripting_api.cc index 6121e9638c6..ffa75d97a48 100644 --- a/chromium/chrome/browser/extensions/api/scripting/scripting_api.cc +++ b/chromium/chrome/browser/extensions/api/scripting/scripting_api.cc @@ -18,6 +18,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/extension_types_utils.h" +#include "extensions/browser/api/scripting/constants.h" #include "extensions/browser/extension_api_frame_id_map.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/browser/extension_system.h" @@ -30,6 +31,7 @@ #include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/mojom/css_origin.mojom-shared.h" +#include "extensions/common/mojom/execution_world.mojom-shared.h" #include "extensions/common/mojom/host_id.mojom.h" #include "extensions/common/mojom/run_location.mojom-shared.h" #include "extensions/common/permissions/api_permission.h" @@ -52,16 +54,6 @@ constexpr char kExactlyOneOfCssAndFilesError[] = constexpr mojom::RunLocation kCSSRunLocation = mojom::RunLocation::kDocumentStart; -// TODO(crbug.com/1168627): The can_execute_script_everywhere flag is currently -// only used by the legacy version Chromevox extension. We can assume it will -// always be false here, but it may be added back if needed. -constexpr bool kScriptsCanExecuteEverywhere = false; - -// The all_urls_includes_chrome_urls flag is only true for the legacy ChromeVox -// extension, which does not call this API. Therefore we can assume it to be -// always false. -constexpr bool kAllUrlsIncludesChromeUrls = false; - // Converts the given `style_origin` to a CSSOrigin. mojom::CSSOrigin ConvertStyleOriginToCSSOrigin( api::scripting::StyleOrigin style_origin) { @@ -355,11 +347,12 @@ std::unique_ptr<UserScript> ParseUserScript( if (content_script.all_frames) result->set_match_all_frames(*content_script.all_frames); + DCHECK(content_script.matches); if (!script_parsing::ParseMatchPatterns( - content_script.matches, content_script.exclude_matches.get(), + *content_script.matches, content_script.exclude_matches.get(), definition_index, extension.creation_flags(), - kScriptsCanExecuteEverywhere, valid_schemes, - kAllUrlsIncludesChromeUrls, result.get(), error, + scripting::kScriptsCanExecuteEverywhere, valid_schemes, + scripting::kAllUrlsIncludesChromeUrls, result.get(), error, /*wants_file_access=*/nullptr)) { return nullptr; } @@ -396,9 +389,10 @@ api::scripting::RegisteredContentScript CreateRegisteredContentScriptInfo( api::scripting::RegisteredContentScript script_info; script_info.id = script.id(); - script_info.matches.reserve(script.url_patterns().size()); + script_info.matches = std::make_unique<std::vector<std::string>>(); + script_info.matches->reserve(script.url_patterns().size()); for (const URLPattern& pattern : script.url_patterns()) - script_info.matches.push_back(pattern.GetAsString()); + script_info.matches->push_back(pattern.GetAsString()); if (!script.exclude_url_patterns().is_empty()) { script_info.exclude_matches = std::make_unique<std::vector<std::string>>(); @@ -445,7 +439,7 @@ ScriptingExecuteScriptFunction::~ScriptingExecuteScriptFunction() = default; ExtensionFunction::ResponseAction ScriptingExecuteScriptFunction::Run() { std::unique_ptr<api::scripting::ExecuteScript::Params> params( - api::scripting::ExecuteScript::Params::Create(*args_)); + api::scripting::ExecuteScript::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); injection_ = std::move(params->injection); @@ -544,11 +538,20 @@ bool ScriptingExecuteScriptFunction::Execute( return false; } + mojom::ExecutionWorld execution_world = mojom::ExecutionWorld::kIsolated; + switch (injection_.world) { + case api::scripting::EXECUTION_WORLD_NONE: + case api::scripting::EXECUTION_WORLD_ISOLATED: + break; // mojom::ExecutionWorld::kIsolated is correct. + case api::scripting::EXECUTION_WORLD_MAIN: + execution_world = mojom::ExecutionWorld::kMain; + } + script_executor->ExecuteScript( mojom::HostID(mojom::HostID::HostType::kExtensions, extension()->id()), - mojom::CodeInjection::NewJs(mojom::JSInjection::New(std::move(sources), - /*wants_result=*/true, - user_gesture())), + mojom::CodeInjection::NewJs( + mojom::JSInjection::New(std::move(sources), execution_world, + /*wants_result=*/true, user_gesture())), frame_scope, frame_ids, ScriptExecutor::MATCH_ABOUT_BLANK, mojom::RunLocation::kDocumentIdle, ScriptExecutor::DEFAULT_PROCESS, /* webview_src */ GURL(), @@ -596,7 +599,7 @@ ScriptingInsertCSSFunction::~ScriptingInsertCSSFunction() = default; ExtensionFunction::ResponseAction ScriptingInsertCSSFunction::Run() { std::unique_ptr<api::scripting::InsertCSS::Params> params( - api::scripting::InsertCSS::Params::Create(*args_)); + api::scripting::InsertCSS::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); injection_ = std::move(params->injection); @@ -697,7 +700,7 @@ ScriptingRemoveCSSFunction::~ScriptingRemoveCSSFunction() = default; ExtensionFunction::ResponseAction ScriptingRemoveCSSFunction::Run() { std::unique_ptr<api::scripting::RemoveCSS::Params> params( - api::scripting::RemoveCSS::Params::Create(*args_)); + api::scripting::RemoveCSS::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); api::scripting::CSSInjection& injection = params->injection; @@ -777,7 +780,7 @@ ScriptingRegisterContentScriptsFunction:: ExtensionFunction::ResponseAction ScriptingRegisterContentScriptsFunction::Run() { std::unique_ptr<api::scripting::RegisterContentScripts::Params> params( - api::scripting::RegisterContentScripts::Params::Create(*args_)); + api::scripting::RegisterContentScripts::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::vector<api::scripting::RegisteredContentScript>& scripts = @@ -810,16 +813,29 @@ ScriptingRegisterContentScriptsFunction::Run() { std::u16string parse_error; auto parsed_scripts = std::make_unique<UserScriptList>(); - const int valid_schemes = - UserScript::ValidUserScriptSchemes(kScriptsCanExecuteEverywhere); + std::set<std::string> persistent_script_ids; + const int valid_schemes = UserScript::ValidUserScriptSchemes( + scripting::kScriptsCanExecuteEverywhere); + parsed_scripts->reserve(scripts.size()); for (size_t i = 0; i < scripts.size(); ++i) { + if (!scripts[i].matches) { + return RespondNow( + Error(base::StringPrintf("Script with ID '%s' must specify 'matches'", + scripts[i].id.c_str()))); + } + // Parse/Create user script. std::unique_ptr<UserScript> user_script = ParseUserScript( *extension(), scripts[i], i, valid_schemes, &parse_error); if (!user_script) return RespondNow(Error(base::UTF16ToASCII(parse_error))); + // Scripts will persist across sessions by default. + if (!scripts[i].persist_across_sessions || + *scripts[i].persist_across_sessions) { + persistent_script_ids.insert(user_script->id()); + } parsed_scripts->push_back(std::move(user_script)); } @@ -834,7 +850,7 @@ ScriptingRegisterContentScriptsFunction::Run() { std::move(parsed_scripts)), base::BindOnce(&ScriptingRegisterContentScriptsFunction:: OnContentScriptFilesValidated, - this)); + this, std::move(persistent_script_ids))); // Balanced in `OnContentScriptFilesValidated()` or // `OnContentScriptsRegistered()`. @@ -843,8 +859,9 @@ ScriptingRegisterContentScriptsFunction::Run() { } void ScriptingRegisterContentScriptsFunction::OnContentScriptFilesValidated( + std::set<std::string> persistent_script_ids, ValidateContentScriptsResult result) { - auto error = result.second; + auto error = std::move(result.second); auto scripts = std::move(result.first); ExtensionUserScriptLoader* loader = ExtensionSystem::Get(browser_context()) @@ -857,13 +874,13 @@ void ScriptingRegisterContentScriptsFunction::OnContentScriptFilesValidated( ids_to_remove.insert(script->id()); loader->RemovePendingDynamicScriptIDs(std::move(ids_to_remove)); - Respond(Error(*error)); + Respond(Error(std::move(*error))); Release(); // Matches the `AddRef()` in `Run()`. return; } loader->AddDynamicScripts( - std::move(scripts), + std::move(scripts), std::move(persistent_script_ids), base::BindOnce( &ScriptingRegisterContentScriptsFunction::OnContentScriptsRegistered, this)); @@ -872,7 +889,7 @@ void ScriptingRegisterContentScriptsFunction::OnContentScriptFilesValidated( void ScriptingRegisterContentScriptsFunction::OnContentScriptsRegistered( const absl::optional<std::string>& error) { if (error.has_value()) - Respond(Error(*error)); + Respond(Error(std::move(*error))); else Respond(NoArguments()); Release(); // Matches the `AddRef()` in `Run()`. @@ -886,7 +903,7 @@ ScriptingGetRegisteredContentScriptsFunction:: ExtensionFunction::ResponseAction ScriptingGetRegisteredContentScriptsFunction::Run() { std::unique_ptr<api::scripting::GetRegisteredContentScripts::Params> params( - api::scripting::GetRegisteredContentScripts::Params::Create(*args_)); + api::scripting::GetRegisteredContentScripts::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const api::scripting::ContentScriptFilter* filter = params->filter.get(); @@ -903,9 +920,15 @@ ScriptingGetRegisteredContentScriptsFunction::Run() { const UserScriptList& dynamic_scripts = loader->GetLoadedDynamicScripts(); std::vector<api::scripting::RegisteredContentScript> script_infos; + std::set<std::string> persistent_script_ids = + loader->GetPersistentDynamicScriptIDs(); for (const std::unique_ptr<UserScript>& script : dynamic_scripts) { - if (id_filter.empty() || base::Contains(id_filter, script->id())) - script_infos.push_back(CreateRegisteredContentScriptInfo(*script)); + if (id_filter.empty() || base::Contains(id_filter, script->id())) { + auto registered_script = CreateRegisteredContentScriptInfo(*script); + registered_script.persist_across_sessions = std::make_unique<bool>( + base::Contains(persistent_script_ids, script->id())); + script_infos.push_back(std::move(registered_script)); + } } return RespondNow( @@ -920,7 +943,7 @@ ScriptingUnregisterContentScriptsFunction:: ExtensionFunction::ResponseAction ScriptingUnregisterContentScriptsFunction::Run() { - auto params(api::scripting::UnregisterContentScripts::Params::Create(*args_)); + auto params(api::scripting::UnregisterContentScripts::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::unique_ptr<api::scripting::ContentScriptFilter>& filter = params->filter; @@ -967,9 +990,180 @@ ScriptingUnregisterContentScriptsFunction::Run() { void ScriptingUnregisterContentScriptsFunction::OnContentScriptsUnregistered( const absl::optional<std::string>& error) { if (error.has_value()) - Respond(Error(*error)); + Respond(Error(std::move(*error))); else Respond(NoArguments()); } +ScriptingUpdateContentScriptsFunction::ScriptingUpdateContentScriptsFunction() = + default; +ScriptingUpdateContentScriptsFunction:: + ~ScriptingUpdateContentScriptsFunction() = default; + +ExtensionFunction::ResponseAction ScriptingUpdateContentScriptsFunction::Run() { + std::unique_ptr<api::scripting::UpdateContentScripts::Params> params( + api::scripting::UpdateContentScripts::Params::Create(args())); + EXTENSION_FUNCTION_VALIDATE(params); + + std::vector<api::scripting::RegisteredContentScript>& scripts = + params->scripts; + + ExtensionUserScriptLoader* loader = + ExtensionSystem::Get(browser_context()) + ->user_script_manager() + ->GetUserScriptLoaderForExtension(extension()->id()); + + std::map<std::string, api::scripting::RegisteredContentScript> + loaded_scripts_metadata; + const UserScriptList& dynamic_scripts = loader->GetLoadedDynamicScripts(); + for (const std::unique_ptr<UserScript>& script : dynamic_scripts) { + loaded_scripts_metadata.emplace(script->id(), + CreateRegisteredContentScriptInfo(*script)); + } + + std::set<std::string> ids_to_update; + for (const auto& script : scripts) { + if (loaded_scripts_metadata.find(script.id) == + loaded_scripts_metadata.end()) { + return RespondNow( + Error(base::StringPrintf("Content script with ID '%s' does not exist " + "or is not fully registered", + script.id.c_str()))); + } + + DCHECK(!script.id.empty()); + DCHECK(!UserScript::IsIDGenerated(script.id)); + + if (base::Contains(ids_to_update, script.id)) { + return RespondNow(Error( + base::StringPrintf("Duplicate script ID '%s'", script.id.c_str()))); + } + + ids_to_update.insert(script.id); + } + + std::u16string parse_error; + auto parsed_scripts = std::make_unique<UserScriptList>(); + const int valid_schemes = UserScript::ValidUserScriptSchemes( + scripting::kScriptsCanExecuteEverywhere); + + std::set<std::string> updated_script_ids_to_persist; + std::set<std::string> persistent_script_ids = + loader->GetPersistentDynamicScriptIDs(); + + parsed_scripts->reserve(scripts.size()); + for (size_t i = 0; i < scripts.size(); ++i) { + api::scripting::RegisteredContentScript& update_delta = scripts[i]; + DCHECK(base::Contains(loaded_scripts_metadata, update_delta.id)); + + api::scripting::RegisteredContentScript& updated_script = + loaded_scripts_metadata[update_delta.id]; + + if (update_delta.matches) + updated_script.matches = std::move(update_delta.matches); + + if (update_delta.exclude_matches) + updated_script.exclude_matches = std::move(update_delta.exclude_matches); + + if (update_delta.js) + updated_script.js = std::move(update_delta.js); + + if (update_delta.css) + updated_script.css = std::move(update_delta.css); + + if (update_delta.all_frames) + *updated_script.all_frames = *update_delta.all_frames; + + if (update_delta.match_origin_as_fallback) { + *updated_script.match_origin_as_fallback = + *update_delta.match_origin_as_fallback; + } + + if (update_delta.run_at != api::extension_types::RUN_AT_NONE) + updated_script.run_at = update_delta.run_at; + + // Parse/Create user script. + std::unique_ptr<UserScript> user_script = ParseUserScript( + *extension(), updated_script, i, valid_schemes, &parse_error); + if (!user_script) + return RespondNow(Error(base::UTF16ToASCII(parse_error))); + + // Persist the updated script if the flag is specified as true, or if the + // original script is persisted and the flag is not specified. + if ((update_delta.persist_across_sessions && + *update_delta.persist_across_sessions) || + (!update_delta.persist_across_sessions && + base::Contains(persistent_script_ids, update_delta.id))) { + updated_script_ids_to_persist.insert(update_delta.id); + } + + parsed_scripts->push_back(std::move(user_script)); + } + + // Add new script IDs now in case another call with the same script IDs is + // made immediately following this one. + loader->AddPendingDynamicScriptIDs(std::move(ids_to_update)); + + base::PostTaskAndReplyWithResult( + GetExtensionFileTaskRunner().get(), FROM_HERE, + base::BindOnce(&ValidateParsedScriptsOnFileThread, + script_parsing::GetSymlinkPolicy(extension()), + std::move(parsed_scripts)), + base::BindOnce( + &ScriptingUpdateContentScriptsFunction::OnContentScriptFilesValidated, + this, std::move(updated_script_ids_to_persist))); + + // Balanced in `OnContentScriptFilesValidated()` or + // `OnContentScriptsRegistered()`. + AddRef(); + return RespondLater(); +} + +void ScriptingUpdateContentScriptsFunction::OnContentScriptFilesValidated( + std::set<std::string> persistent_script_ids, + ValidateContentScriptsResult result) { + auto error = std::move(result.second); + auto scripts = std::move(result.first); + ExtensionUserScriptLoader* loader = + ExtensionSystem::Get(browser_context()) + ->user_script_manager() + ->GetUserScriptLoaderForExtension(extension()->id()); + + std::set<std::string> script_ids; + for (const auto& script : *scripts) + script_ids.insert(script->id()); + + if (error.has_value()) { + loader->RemovePendingDynamicScriptIDs(script_ids); + Respond(Error(std::move(*error))); + Release(); // Matches the `AddRef()` in `Run()`. + return; + } + + // To guarantee that scripts are updated, they need to be removed then added + // again. It should be guaranteed that the new scripts are added after the old + // ones are removed. + loader->RemoveDynamicScripts(script_ids, /*callback=*/base::DoNothing()); + + // Since RemoveDynamicScripts will remove pending script IDs, but + // AddDynamicScripts will only add scripts that are marked as pending, we must + // mark `script_ids` as pending again here. + loader->AddPendingDynamicScriptIDs(std::move(script_ids)); + + loader->AddDynamicScripts( + std::move(scripts), std::move(persistent_script_ids), + base::BindOnce( + &ScriptingUpdateContentScriptsFunction::OnContentScriptsUpdated, + this)); +} + +void ScriptingUpdateContentScriptsFunction::OnContentScriptsUpdated( + const absl::optional<std::string>& error) { + if (error.has_value()) + Respond(Error(std::move(*error))); + else + Respond(NoArguments()); + Release(); // Matches the `AddRef()` in `Run()`. +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/scripting/scripting_api.h b/chromium/chrome/browser/extensions/api/scripting/scripting_api.h index 733138275ca..093562d9e52 100644 --- a/chromium/chrome/browser/extensions/api/scripting/scripting_api.h +++ b/chromium/chrome/browser/extensions/api/scripting/scripting_api.h @@ -129,7 +129,9 @@ class ScriptingRegisterContentScriptsFunction : public ExtensionFunction { ~ScriptingRegisterContentScriptsFunction() override; // Called when script files have been checked. - void OnContentScriptFilesValidated(ValidateContentScriptsResult result); + void OnContentScriptFilesValidated( + std::set<std::string> persistent_script_ids, + ValidateContentScriptsResult result); // Called when content scripts have been registered. void OnContentScriptsRegistered(const absl::optional<std::string>& error); @@ -174,6 +176,32 @@ class ScriptingUnregisterContentScriptsFunction : public ExtensionFunction { void OnContentScriptsUnregistered(const absl::optional<std::string>& error); }; +class ScriptingUpdateContentScriptsFunction : public ExtensionFunction { + public: + DECLARE_EXTENSION_FUNCTION("scripting.updateContentScripts", + SCRIPTING_UPDATECONTENTSCRIPTS) + + ScriptingUpdateContentScriptsFunction(); + ScriptingUpdateContentScriptsFunction( + const ScriptingUpdateContentScriptsFunction&) = delete; + ScriptingUpdateContentScriptsFunction& operator=( + const ScriptingUpdateContentScriptsFunction&) = delete; + + // ExtensionFunction: + ResponseAction Run() override; + + private: + ~ScriptingUpdateContentScriptsFunction() override; + + // Called when script files have been checked. + void OnContentScriptFilesValidated( + std::set<std::string> persistent_script_ids, + ValidateContentScriptsResult result); + + // Called when content scripts have been updated. + void OnContentScriptsUpdated(const absl::optional<std::string>& error); +}; + } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_SCRIPTING_SCRIPTING_API_H_ diff --git a/chromium/chrome/browser/extensions/api/scripting/scripting_apitest.cc b/chromium/chrome/browser/extensions/api/scripting/scripting_apitest.cc index 77eceeb96f3..e6d0aa83318 100644 --- a/chromium/chrome/browser/extensions/api/scripting/scripting_apitest.cc +++ b/chromium/chrome/browser/extensions/api/scripting/scripting_apitest.cc @@ -11,6 +11,8 @@ #include "content/public/test/browser_test.h" #include "content/public/test/test_navigation_observer.h" #include "extensions/common/features/feature_channel.h" +#include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/result_catcher.h" #include "net/dns/mock_host_resolver.h" #include "ui/base/window_open_disposition.h" #include "url/gurl.h" @@ -36,7 +38,7 @@ class ScriptingAPITest : public ExtensionApiTest { browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(web_contents); content::TestNavigationObserver nav_observer(web_contents); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); nav_observer.Wait(); EXPECT_TRUE(nav_observer.last_navigation_succeeded()); EXPECT_EQ(url, web_contents->GetLastCommittedURL()); @@ -55,14 +57,11 @@ class ScriptingAPITest : public ExtensionApiTest { ->GetActiveWebContents() ->GetLastCommittedURL()); } - - private: - ScopedCurrentChannel current_channel_{version_info::Channel::UNKNOWN}; }; IN_PROC_BROWSER_TEST_F(ScriptingAPITest, MainFrameTests) { - OpenURLInCurrentTab( - embedded_test_server()->GetURL("example.com", "/simple.html")); + OpenURLInCurrentTab(embedded_test_server()->GetURL( + "example.com", "/extensions/main_world_script_flag.html")); OpenURLInNewTab( embedded_test_server()->GetURL("chromium.org", "/title2.html")); @@ -103,4 +102,48 @@ IN_PROC_BROWSER_TEST_F(ScriptingAPITest, DynamicContentScripts) { ASSERT_TRUE(RunExtensionTest("scripting/dynamic_scripts")) << message_; } +// Base test fixture for tests spanning multiple sessions where a custom arg is +// set before the test is run. +class PersistentScriptingAPITest : public ScriptingAPITest { + public: + PersistentScriptingAPITest() = default; + + // ScriptingAPITest override. + void SetUpOnMainThread() override { + ScriptingAPITest::SetUpOnMainThread(); + + // Set the test name as a custom arge before the test is run. This avoids a + // race condition where the extension loads (as part of browser startup) and + // sends a message before a message listener in C++ has been initialized. + SetCustomArg(testing::UnitTest::GetInstance()->current_test_info()->name()); + } + + protected: + // Used to wait for results from extension tests. This is initialized before + // the test is run which avoids a race condition where the extension is loaded + // (as part of startup) and finishes its tests before the ResultCatcher is + // created. + extensions::ResultCatcher result_catcher_; +}; + +// Tests that registered content scripts which persist across sessions behave as +// expected. The test is run across three sessions. +IN_PROC_BROWSER_TEST_F(PersistentScriptingAPITest, + PRE_PRE_PersistentDynamicContentScripts) { + const extensions::Extension* extension = LoadExtension( + test_data_dir_.AppendASCII("scripting/persistent_dynamic_scripts")); + ASSERT_TRUE(extension); + EXPECT_TRUE(result_catcher_.GetNextResult()) << result_catcher_.message(); +} + +IN_PROC_BROWSER_TEST_F(PersistentScriptingAPITest, + PRE_PersistentDynamicContentScripts) { + EXPECT_TRUE(result_catcher_.GetNextResult()) << result_catcher_.message(); +} + +IN_PROC_BROWSER_TEST_F(PersistentScriptingAPITest, + PersistentDynamicContentScripts) { + EXPECT_TRUE(result_catcher_.GetNextResult()) << result_catcher_.message(); +} + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/search/search_api.cc b/chromium/chrome/browser/extensions/api/search/search_api.cc index f4529ca548b..fd3a9ec2c30 100644 --- a/chromium/chrome/browser/extensions/api/search/search_api.cc +++ b/chromium/chrome/browser/extensions/api/search/search_api.cc @@ -33,7 +33,7 @@ using extensions::api::search::Disposition; ExtensionFunction::ResponseAction SearchQueryFunction::Run() { std::unique_ptr<api::search::Query::Params> params( - api::search::Query::Params::Create(*args_)); + api::search::Query::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); // Convenience for input params. diff --git a/chromium/chrome/browser/extensions/api/sessions/session_id.h b/chromium/chrome/browser/extensions/api/sessions/session_id.h index 627542c6c29..11908cd0aff 100644 --- a/chromium/chrome/browser/extensions/api/sessions/session_id.h +++ b/chromium/chrome/browser/extensions/api/sessions/session_id.h @@ -27,6 +27,9 @@ class SessionId { // |session_tag| session. SessionId(const std::string& session_tag, int id); + SessionId(const SessionId&) = delete; + SessionId& operator=(const SessionId&) = delete; + // Returns true if the SessionId represents a foreign session. bool IsForeign() const; @@ -44,8 +47,6 @@ class SessionId { // ID corresponding to a window or tab object. int id_; - - DISALLOW_COPY_AND_ASSIGN(SessionId); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc index e904ad01686..de02aca8d02 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc @@ -210,7 +210,7 @@ SessionsGetRecentlyClosedFunction::CreateSessionModel( ExtensionFunction::ResponseAction SessionsGetRecentlyClosedFunction::Run() { std::unique_ptr<GetRecentlyClosed::Params> params( - GetRecentlyClosed::Params::Create(*args_)); + GetRecentlyClosed::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int max_results = api::sessions::MAX_SESSION_RESULTS; if (params->filter && params->filter->max_results) @@ -234,6 +234,7 @@ ExtensionFunction::ResponseAction SessionsGetRecentlyClosedFunction::Run() { // List of entries. They are ordered from most to least recent. // We prune the list to contain max 25 entries at any time and removes // uninteresting entries. + int counter = 0; for (const auto& entry : tab_restore_service->entries()) { // TODO(crbug.com/1192309): Support group entries in the Sessions API, // rather than sharding the group out into individual tabs. @@ -241,9 +242,15 @@ ExtensionFunction::ResponseAction SessionsGetRecentlyClosedFunction::Run() { auto& group = static_cast<const sessions::TabRestoreService::Group&>(*entry); for (const auto& tab : group.tabs) - result.push_back(std::move(*CreateSessionModel(*tab))); + if (counter++ < max_results) + result.push_back(std::move(*CreateSessionModel(*tab))); + else + break; } else { - result.push_back(std::move(*CreateSessionModel(*entry))); + if (counter++ < max_results) + result.push_back(std::move(*CreateSessionModel(*entry))); + else + break; } } @@ -376,7 +383,7 @@ api::sessions::Device SessionsGetDevicesFunction::CreateDeviceModel( int max_results = api::sessions::MAX_SESSION_RESULTS; // Already validated in RunAsync(). std::unique_ptr<GetDevices::Params> params( - GetDevices::Params::Create(*args_)); + GetDevices::Params::Create(args())); if (params->filter && params->filter->max_results) max_results = *params->filter->max_results; @@ -412,7 +419,7 @@ ExtensionFunction::ResponseAction SessionsGetDevicesFunction::Run() { } std::unique_ptr<GetDevices::Params> params( - GetDevices::Params::Create(*args_)); + GetDevices::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); if (params->filter && params->filter->max_results) { EXTENSION_FUNCTION_VALIDATE(*params->filter->max_results >= 0 && @@ -587,7 +594,7 @@ ExtensionFunction::ResponseValue SessionsRestoreFunction::RestoreForeignSession( } ExtensionFunction::ResponseAction SessionsRestoreFunction::Run() { - std::unique_ptr<Restore::Params> params(Restore::Params::Create(*args_)); + std::unique_ptr<Restore::Params> params(Restore::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); Profile* profile = Profile::FromBrowserContext(browser_context()); diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h index ba77563628b..a7db66ca6a4 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h @@ -87,6 +87,10 @@ class SessionsRestoreFunction : public ExtensionFunction { class SessionsEventRouter : public sessions::TabRestoreServiceObserver { public: explicit SessionsEventRouter(Profile* profile); + + SessionsEventRouter(const SessionsEventRouter&) = delete; + SessionsEventRouter& operator=(const SessionsEventRouter&) = delete; + ~SessionsEventRouter() override; // Observer callback for TabRestoreServiceObserver. Sends data on @@ -104,14 +108,16 @@ class SessionsEventRouter : public sessions::TabRestoreServiceObserver { // TabRestoreService that we are observing. sessions::TabRestoreService* tab_restore_service_; - - DISALLOW_COPY_AND_ASSIGN(SessionsEventRouter); }; class SessionsAPI : public BrowserContextKeyedAPI, public extensions::EventRouter::Observer { public: explicit SessionsAPI(content::BrowserContext* context); + + SessionsAPI(const SessionsAPI&) = delete; + SessionsAPI& operator=(const SessionsAPI&) = delete; + ~SessionsAPI() override; // BrowserContextKeyedService implementation. @@ -136,8 +142,6 @@ class SessionsAPI : public BrowserContextKeyedAPI, // Created lazily upon OnListenerAdded. std::unique_ptr<SessionsEventRouter> sessions_event_router_; - - DISALLOW_COPY_AND_ASSIGN(SessionsAPI); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc index 303c83e7062..224dfe3b8fc 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc @@ -28,6 +28,7 @@ #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/ui_test_utils.h" #include "components/sync/base/client_tag_hash.h" #include "components/sync/engine/data_type_activation_response.h" #include "components/sync/model/data_type_activation_request.h" @@ -103,15 +104,15 @@ void BuildTabSpecifics(const std::string& tag, testing::AssertionResult CheckSessionModels(const base::ListValue& devices, size_t num_sessions) { - EXPECT_EQ(5u, devices.GetSize()); + EXPECT_EQ(5u, devices.GetList().size()); const base::DictionaryValue* device = NULL; const base::ListValue* sessions = NULL; - for (size_t i = 0; i < devices.GetSize(); ++i) { + for (size_t i = 0; i < devices.GetList().size(); ++i) { EXPECT_TRUE(devices.GetDictionary(i, &device)); EXPECT_EQ(kSessionTags[i], api_test_utils::GetString(device, "info")); EXPECT_EQ(kSessionTags[i], api_test_utils::GetString(device, "deviceName")); EXPECT_TRUE(device->GetList("sessions", &sessions)); - EXPECT_EQ(num_sessions, sessions->GetSize()); + EXPECT_EQ(num_sessions, sessions->GetList().size()); // Because this test is hurried, really there are only ever 0 or 1 // sessions, and if 1, that will be a Window. Grab it. if (num_sessions == 0) @@ -123,8 +124,8 @@ testing::AssertionResult CheckSessionModels(const base::ListValue& devices, // Only the tabs are interesting. const base::ListValue* tabs = NULL; EXPECT_TRUE(window->GetList("tabs", &tabs)); - EXPECT_EQ(base::size(kTabIDs), tabs->GetSize()); - for (size_t j = 0; j < tabs->GetSize(); ++j) { + EXPECT_EQ(base::size(kTabIDs), tabs->GetList().size()); + for (size_t j = 0; j < tabs->GetList().size(); ++j) { const base::DictionaryValue* tab = NULL; EXPECT_TRUE(tabs->GetDictionary(j, &tab)); EXPECT_FALSE(tab->HasKey("id")); // sessions API does not give tab IDs @@ -246,8 +247,7 @@ void ExtensionSessionsTest::CreateSessionModels() { header_entity_data.id = "FakeId:" + header_entity_data.client_tag_hash.value(); header_entity_data.specifics = header_entity; - header_entity_data.creation_time = - time_now - base::TimeDelta::FromSeconds(index); + header_entity_data.creation_time = time_now - base::Seconds(index); header_entity_data.modification_time = header_entity_data.creation_time; syncer::UpdateResponseData header_update; @@ -299,7 +299,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetDevicesListEmpty) { ASSERT_TRUE(result); base::ListValue* devices = result.get(); - EXPECT_EQ(0u, devices->GetSize()); + EXPECT_EQ(0u, devices->GetList().size()); } IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionWindow) { @@ -317,13 +317,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionWindow) { ASSERT_TRUE(result); base::ListValue* windows = result.get(); - EXPECT_EQ(2u, windows->GetSize()); + EXPECT_EQ(2u, windows->GetList().size()); base::DictionaryValue* restored_window = NULL; - EXPECT_TRUE(restored_window_session->GetDictionary("window", - &restored_window)); + EXPECT_TRUE( + restored_window_session->GetDictionary("window", &restored_window)); base::DictionaryValue* window = NULL; int restored_id = api_test_utils::GetInteger(restored_window, "id"); - for (size_t i = 0; i < windows->GetSize(); ++i) { + for (size_t i = 0; i < windows->GetList().size(); ++i) { EXPECT_TRUE(windows->GetDictionary(i, &window)); if (api_test_utils::GetInteger(window, "id") == restored_id) break; @@ -344,10 +344,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreForeignSessionInvalidId) { IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, RestoreInIncognito) { CreateSessionModels(); - EXPECT_TRUE(base::MatchPattern(utils::RunFunctionAndReturnError( - CreateFunction<SessionsRestoreFunction>(true).get(), - "[\"1\"]", - CreateIncognitoBrowser()), + EXPECT_TRUE(base::MatchPattern( + utils::RunFunctionAndReturnError( + CreateFunction<SessionsRestoreFunction>(true).get(), "[\"1\"]", + CreateIncognitoBrowser()), "Can not restore sessions in incognito mode.")); } @@ -358,7 +358,49 @@ IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetRecentlyClosedIncognito) { CreateIncognitoBrowser()))); ASSERT_TRUE(result); base::ListValue* sessions = result.get(); - EXPECT_EQ(0u, sessions->GetSize()); + EXPECT_EQ(0u, sessions->GetList().size()); +} + +IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, GetRecentlyClosedMaxResults) { + const size_t kTabCount = 3; + ASSERT_EQ(1, browser()->tab_strip_model()->count()); + for (size_t i = 0; i < kTabCount; ++i) { + ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL("data:text/html"), + WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); + int tab_index = 1; + content::WebContentsDestroyedWatcher destroyed_watcher( + browser()->tab_strip_model()->GetWebContentsAt(tab_index)); + browser()->tab_strip_model()->CloseWebContentsAt( + tab_index, TabStripModel::CLOSE_CREATE_HISTORICAL_TAB); + destroyed_watcher.Wait(); + } + + { + std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( + CreateFunction<SessionsGetRecentlyClosedFunction>(true).get(), "[]", + browser())); + ASSERT_TRUE(result); + ASSERT_TRUE(result->is_list()); + EXPECT_EQ(kTabCount, result->GetList().size()); + } + { + std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( + CreateFunction<SessionsGetRecentlyClosedFunction>(true).get(), + "[{\"maxResults\": 0}]", browser())); + ASSERT_TRUE(result); + ASSERT_TRUE(result->is_list()); + EXPECT_EQ(0u, result->GetList().size()); + } + { + std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( + CreateFunction<SessionsGetRecentlyClosedFunction>(true).get(), + "[{\"maxResults\": 2}]", browser())); + ASSERT_TRUE(result); + ASSERT_TRUE(result->is_list()); + EXPECT_EQ(2u, result->GetList().size()); + } } // http://crbug.com/251199 diff --git a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc index db7161dd289..ce8ecded90e 100644 --- a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc +++ b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.cc @@ -182,8 +182,8 @@ void SettingsOverridesAPI::OnExtensionLoaded( manifest_keys::kSettingsOverride); } std::unique_ptr<base::ListValue> url_list(new base::ListValue); - url_list->AppendString(SubstituteInstallParam( - settings->startup_pages[0].spec(), install_parameter)); + url_list->Append(SubstituteInstallParam(settings->startup_pages[0].spec(), + install_parameter)); SetPref(extension->id(), prefs::kURLsToRestoreOnStartup, std::move(url_list)); } diff --git a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h index 8b742703f09..6b031db15ef 100644 --- a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h +++ b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_api.h @@ -24,6 +24,10 @@ class SettingsOverridesAPI : public BrowserContextKeyedAPI, public ExtensionRegistryObserver { public: explicit SettingsOverridesAPI(content::BrowserContext* context); + + SettingsOverridesAPI(const SettingsOverridesAPI&) = delete; + SettingsOverridesAPI& operator=(const SettingsOverridesAPI&) = delete; + ~SettingsOverridesAPI() override; // BrowserContextKeyedAPI implementation. @@ -57,8 +61,6 @@ class SettingsOverridesAPI : public BrowserContextKeyedAPI, // Listen to extension load, unloaded notifications. base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(SettingsOverridesAPI); }; template <> diff --git a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc index 54c71fed0c6..8fdc8d50935 100644 --- a/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/settings_overrides/settings_overrides_browsertest.cc @@ -236,6 +236,12 @@ class ExtensionsDisabledWithSettingsOverrideAPI : public ExtensionBrowserTest { : prompt_for_external_extensions_( FeatureSwitch::prompt_for_external_extensions(), false) {} + + ExtensionsDisabledWithSettingsOverrideAPI( + const ExtensionsDisabledWithSettingsOverrideAPI&) = delete; + ExtensionsDisabledWithSettingsOverrideAPI& operator=( + const ExtensionsDisabledWithSettingsOverrideAPI&) = delete; + ~ExtensionsDisabledWithSettingsOverrideAPI() override = default; void SetUpCommandLine(base::CommandLine* command_line) override { @@ -252,8 +258,6 @@ class ExtensionsDisabledWithSettingsOverrideAPI : public ExtensionBrowserTest { private: FeatureSwitch::ScopedOverride prompt_for_external_extensions_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionsDisabledWithSettingsOverrideAPI); }; // The following test combo is a regression test for https://crbug.com/828295. diff --git a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc index 0d1bb8a6058..2f85efd04ed 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.cc @@ -27,14 +27,17 @@ class GeneratedResolveTimezoneByGeolocationMethodShort : public GeneratedTimeZonePrefBase { public: explicit GeneratedResolveTimezoneByGeolocationMethodShort(Profile* profile); + + GeneratedResolveTimezoneByGeolocationMethodShort( + const GeneratedResolveTimezoneByGeolocationMethodShort&) = delete; + GeneratedResolveTimezoneByGeolocationMethodShort& operator=( + const GeneratedResolveTimezoneByGeolocationMethodShort&) = delete; + ~GeneratedResolveTimezoneByGeolocationMethodShort() override; // GeneratedPrefsChromeOSImpl implementation: std::unique_ptr<settings_api::PrefObject> GetPrefObject() const override; SetPrefResult SetPref(const base::Value* value) override; - - private: - DISALLOW_COPY_AND_ASSIGN(GeneratedResolveTimezoneByGeolocationMethodShort); }; GeneratedResolveTimezoneByGeolocationMethodShort:: diff --git a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc index 8f404b82d48..91eba0206f4 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.cc @@ -28,14 +28,17 @@ class GeneratedResolveTimezoneByGeolocationOnOff : public GeneratedTimeZonePrefBase { public: explicit GeneratedResolveTimezoneByGeolocationOnOff(Profile* profile); + + GeneratedResolveTimezoneByGeolocationOnOff( + const GeneratedResolveTimezoneByGeolocationOnOff&) = delete; + GeneratedResolveTimezoneByGeolocationOnOff& operator=( + const GeneratedResolveTimezoneByGeolocationOnOff&) = delete; + ~GeneratedResolveTimezoneByGeolocationOnOff() override; // GeneratedPref implementation: std::unique_ptr<settings_api::PrefObject> GetPrefObject() const override; SetPrefResult SetPref(const base::Value* value) override; - - private: - DISALLOW_COPY_AND_ASSIGN(GeneratedResolveTimezoneByGeolocationOnOff); }; GeneratedResolveTimezoneByGeolocationOnOff:: diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h b/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h index 6914046e18a..07e16f86e12 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h +++ b/chromium/chrome/browser/extensions/api/settings_private/generated_pref.h @@ -35,16 +35,20 @@ class GeneratedPref { class Observer { public: Observer(); + + Observer(const Observer&) = delete; + Observer& operator=(const Observer&) = delete; + virtual ~Observer(); // This method is called to notify observer that visible value // of the preference has changed. virtual void OnGeneratedPrefChanged(const std::string& pref_name) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(Observer); }; + GeneratedPref(const GeneratedPref&) = delete; + GeneratedPref& operator=(const GeneratedPref&) = delete; + virtual ~GeneratedPref(); // Returns fully populated PrefObject. @@ -85,8 +89,6 @@ class GeneratedPref { private: base::ObserverList<Observer>::Unchecked observers_; - - DISALLOW_COPY_AND_ASSIGN(GeneratedPref); }; } // namespace settings_private diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.h b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.h index c58a5fef3f8..ad7f955f1b4 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.h +++ b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs.h @@ -39,6 +39,10 @@ class GeneratedPrefs : public KeyedService { std::unordered_map<std::string, std::unique_ptr<GeneratedPref>>; explicit GeneratedPrefs(Profile* profile); + + GeneratedPrefs(const GeneratedPrefs&) = delete; + GeneratedPrefs& operator=(const GeneratedPrefs&) = delete; + ~GeneratedPrefs() override; // Returns true if preference is supported. @@ -72,8 +76,6 @@ class GeneratedPrefs : public KeyedService { PrefsMap prefs_; Profile* profile_; - - DISALLOW_COPY_AND_ASSIGN(GeneratedPrefs); }; } // namespace settings_private diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h index 10fc892653c..92d70b733bd 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h +++ b/chromium/chrome/browser/extensions/api/settings_private/generated_prefs_factory.h @@ -17,6 +17,9 @@ class GeneratedPrefs; // BrowserContextKeyedServiceFactory for GeneratedPrefs. class GeneratedPrefsFactory : public BrowserContextKeyedServiceFactory { public: + GeneratedPrefsFactory(const GeneratedPrefsFactory&) = delete; + GeneratedPrefsFactory& operator=(const GeneratedPrefsFactory&) = delete; + static GeneratedPrefs* GetForBrowserContext( content::BrowserContext* browser_context); @@ -34,8 +37,6 @@ class GeneratedPrefsFactory : public BrowserContextKeyedServiceFactory { bool ServiceIsNULLWhileTesting() const override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; - - DISALLOW_COPY_AND_ASSIGN(GeneratedPrefsFactory); }; } // namespace settings_private diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.h b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.h index 6b0d431705e..f13499ad92c 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.h +++ b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.h @@ -21,6 +21,10 @@ class GeneratedTimeZonePrefBase : public GeneratedPref, public ash::system::TimeZoneResolverManager::Observer { public: + GeneratedTimeZonePrefBase(const GeneratedTimeZonePrefBase&) = delete; + GeneratedTimeZonePrefBase& operator=(const GeneratedTimeZonePrefBase&) = + delete; + ~GeneratedTimeZonePrefBase() override; // chromeos::system::TimeZoneResolverManager::Observer @@ -35,8 +39,6 @@ class GeneratedTimeZonePrefBase const std::string pref_name_; Profile* const profile_; - - DISALLOW_COPY_AND_ASSIGN(GeneratedTimeZonePrefBase); }; } // namespace settings_private diff --git a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc index 9687ed9061c..b23375aa581 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc @@ -58,11 +58,12 @@ #include "extensions/common/extension.h" #if BUILDFLAG(IS_CHROMEOS_ASH) +#include "ash/components/quick_answers/public/cpp/quick_answers_prefs.h" #include "ash/constants/ash_pref_names.h" #include "ash/constants/ash_pref_names.h" // nogncheck #include "ash/public/cpp/ambient/ambient_prefs.h" +#include "chrome/browser/ash/app_restore/full_restore_prefs.h" #include "chrome/browser/ash/crostini/crostini_pref_names.h" -#include "chrome/browser/ash/full_restore/full_restore_prefs.h" #include "chrome/browser/ash/guest_os/guest_os_pref_names.h" #include "chrome/browser/ash/ownership/owner_settings_service_ash.h" #include "chrome/browser/ash/ownership/owner_settings_service_ash_factory.h" @@ -74,7 +75,6 @@ #include "chrome/browser/ash/system/timezone_util.h" #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_method_short.h" #include "chrome/browser/extensions/api/settings_private/chromeos_resolve_time_zone_by_geolocation_on_off.h" -#include "chromeos/components/quick_answers/public/cpp/quick_answers_prefs.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/settings/cros_settings_names.h" #include "components/account_manager_core/pref_names.h" @@ -272,17 +272,15 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetAllowlistedKeys() { (*s_allowlist)[::prefs::kDnsOverHttpsTemplates] = settings_api::PrefType::PREF_TYPE_STRING; - // Privacy sandbox - if (PrivacySandboxSettings::PrivacySandboxSettingsFunctional()) { - (*s_allowlist)[::prefs::kPrivacySandboxApisEnabled] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_allowlist)[::prefs::kPrivacySandboxManuallyControlled] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_allowlist)[::prefs::kPrivacySandboxPageViewed] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_allowlist)[::kGeneratedFlocPref] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; - } + // Privacy Sandbox page + (*s_allowlist)[::prefs::kPrivacySandboxApisEnabled] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_allowlist)[::prefs::kPrivacySandboxManuallyControlled] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_allowlist)[::prefs::kPrivacySandboxPageViewed] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_allowlist)[::kGeneratedFlocPref] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; // Security page (*s_allowlist)[::kGeneratedPasswordLeakDetectionPref] = @@ -326,6 +324,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetAllowlistedKeys() { settings_api::PrefType::PREF_TYPE_STRING; (*s_allowlist)[language::prefs::kForcedLanguages] = settings_api::PrefType::PREF_TYPE_LIST; + (*s_allowlist)[::language::prefs::kAcceptLanguages] = + settings_api::PrefType::PREF_TYPE_STRING; (*s_allowlist)[translate::prefs::kPrefTranslateRecentTarget] = settings_api::PrefType::PREF_TYPE_STRING; (*s_allowlist)[translate::prefs::kPrefAlwaysTranslateList] = @@ -339,6 +339,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetAllowlistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_allowlist)[chromeos::prefs::kEmojiSuggestionEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_allowlist)[ash::prefs::kLacrosProxyControllingExtension] = + settings_api::PrefType::PREF_TYPE_DICTIONARY; (*s_allowlist)[::prefs::kLanguageInputMethodSpecificSettings] = settings_api::PrefType::PREF_TYPE_DICTIONARY; (*s_allowlist)[ash::prefs::kLastUsedImeShortcutReminderDismissed] = @@ -351,6 +353,9 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetAllowlistedKeys() { // Nearby Share. (*s_allowlist)[::prefs::kNearbySharingEnabledPrefName] = settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_allowlist) + [::prefs::kNearbySharingFastInitiationNotificationStatePrefName] = + settings_api::PrefType::PREF_TYPE_NUMBER; (*s_allowlist)[::prefs::kNearbySharingOnboardingCompletePrefName] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_allowlist)[::prefs::kNearbySharingActiveProfilePrefName] = @@ -620,16 +625,14 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetAllowlistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; // Quick Answers. - (*s_allowlist)[chromeos::quick_answers::prefs::kQuickAnswersEnabled] = + (*s_allowlist)[ash::quick_answers::prefs::kQuickAnswersEnabled] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_allowlist)[ash::quick_answers::prefs::kQuickAnswersDefinitionEnabled] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_allowlist)[ash::quick_answers::prefs::kQuickAnswersTranslationEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_allowlist) - [chromeos::quick_answers::prefs::kQuickAnswersDefinitionEnabled] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_allowlist) - [chromeos::quick_answers::prefs::kQuickAnswersTranslationEnabled] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_allowlist) - [chromeos::quick_answers::prefs::kQuickAnswersUnitConverstionEnabled] = + [ash::quick_answers::prefs::kQuickAnswersUnitConverstionEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; // Misc. @@ -789,9 +792,6 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetAllowlistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; #else - (*s_allowlist)[::language::prefs::kAcceptLanguages] = - settings_api::PrefType::PREF_TYPE_STRING; - // System settings. (*s_allowlist)[::prefs::kBackgroundModeEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; @@ -1101,12 +1101,12 @@ settings_private::SetPrefResult PrefsUtil::SetCrosSettingsPref( const base::Value* value) { #if BUILDFLAG(IS_CHROMEOS_ASH) if (pref_name == chromeos::kSystemTimezone) { - std::string string_value; - if (!value->GetAsString(&string_value)) + const std::string* string_value = value->GetIfString(); + if (!string_value) return settings_private::SetPrefResult::PREF_TYPE_MISMATCH; const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile(profile_); - if (user && ash::system::SetSystemTimezone(user, string_value)) + if (user && ash::system::SetSystemTimezone(user, *string_value)) return settings_private::SetPrefResult::SUCCESS; return settings_private::SetPrefResult::PREF_NOT_MODIFIABLE; } diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc index fe46d3740f2..01435feac3e 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.cc @@ -27,7 +27,7 @@ SettingsPrivateSetPrefFunction::~SettingsPrivateSetPrefFunction() { ExtensionFunction::ResponseAction SettingsPrivateSetPrefFunction::Run() { std::unique_ptr<api::settings_private::SetPref::Params> parameters = - api::settings_private::SetPref::Params::Create(*args_); + api::settings_private::SetPref::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); SettingsPrivateDelegate* delegate = @@ -79,7 +79,7 @@ SettingsPrivateGetPrefFunction::~SettingsPrivateGetPrefFunction() { ExtensionFunction::ResponseAction SettingsPrivateGetPrefFunction::Run() { std::unique_ptr<api::settings_private::GetPref::Params> parameters = - api::settings_private::GetPref::Params::Create(*args_); + api::settings_private::GetPref::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); SettingsPrivateDelegate* delegate = @@ -122,7 +122,7 @@ SettingsPrivateSetDefaultZoomFunction:: ExtensionFunction::ResponseAction SettingsPrivateSetDefaultZoomFunction::Run() { std::unique_ptr<api::settings_private::SetDefaultZoom::Params> parameters = - api::settings_private::SetDefaultZoom::Params::Create(*args_); + api::settings_private::SetDefaultZoom::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(parameters.get()); SettingsPrivateDelegate* delegate = diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h index e5d283a7374..33723deb876 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_api.h @@ -14,6 +14,12 @@ namespace extensions { class SettingsPrivateSetPrefFunction : public ExtensionFunction { public: SettingsPrivateSetPrefFunction() {} + + SettingsPrivateSetPrefFunction(const SettingsPrivateSetPrefFunction&) = + delete; + SettingsPrivateSetPrefFunction& operator=( + const SettingsPrivateSetPrefFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("settingsPrivate.setPref", SETTINGSPRIVATE_SETPREF) protected: @@ -21,14 +27,18 @@ class SettingsPrivateSetPrefFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateSetPrefFunction); }; // Implements the chrome.settingsPrivate.getAllPrefs method. class SettingsPrivateGetAllPrefsFunction : public ExtensionFunction { public: SettingsPrivateGetAllPrefsFunction() {} + + SettingsPrivateGetAllPrefsFunction( + const SettingsPrivateGetAllPrefsFunction&) = delete; + SettingsPrivateGetAllPrefsFunction& operator=( + const SettingsPrivateGetAllPrefsFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("settingsPrivate.getAllPrefs", SETTINGSPRIVATE_GETALLPREFS) @@ -37,14 +47,18 @@ class SettingsPrivateGetAllPrefsFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetAllPrefsFunction); }; // Implements the chrome.settingsPrivate.getPref method. class SettingsPrivateGetPrefFunction : public ExtensionFunction { public: SettingsPrivateGetPrefFunction() {} + + SettingsPrivateGetPrefFunction(const SettingsPrivateGetPrefFunction&) = + delete; + SettingsPrivateGetPrefFunction& operator=( + const SettingsPrivateGetPrefFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("settingsPrivate.getPref", SETTINGSPRIVATE_GETPREF) protected: @@ -52,14 +66,18 @@ class SettingsPrivateGetPrefFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetPrefFunction); }; // Implements the chrome.settingsPrivate.getDefaultZoom method. class SettingsPrivateGetDefaultZoomFunction : public ExtensionFunction { public: SettingsPrivateGetDefaultZoomFunction() {} + + SettingsPrivateGetDefaultZoomFunction( + const SettingsPrivateGetDefaultZoomFunction&) = delete; + SettingsPrivateGetDefaultZoomFunction& operator=( + const SettingsPrivateGetDefaultZoomFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("settingsPrivate.getDefaultZoom", SETTINGSPRIVATE_GETDEFAULTZOOMFUNCTION) @@ -68,14 +86,18 @@ class SettingsPrivateGetDefaultZoomFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetDefaultZoomFunction); }; // Implements the chrome.settingsPrivate.setDefaultZoom method. class SettingsPrivateSetDefaultZoomFunction : public ExtensionFunction { public: SettingsPrivateSetDefaultZoomFunction() {} + + SettingsPrivateSetDefaultZoomFunction( + const SettingsPrivateSetDefaultZoomFunction&) = delete; + SettingsPrivateSetDefaultZoomFunction& operator=( + const SettingsPrivateSetDefaultZoomFunction&) = delete; + DECLARE_EXTENSION_FUNCTION("settingsPrivate.setDefaultZoom", SETTINGSPRIVATE_SETDEFAULTZOOMFUNCTION) @@ -84,8 +106,6 @@ class SettingsPrivateSetDefaultZoomFunction : public ExtensionFunction { // ExtensionFunction overrides. ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateSetDefaultZoomFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc index 34cba206880..fd8b8ac13d0 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_apitest.cc @@ -50,7 +50,7 @@ using ContextType = ExtensionBrowserTest::ContextType; class SettingsPrivateApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - SettingsPrivateApiTest() = default; + SettingsPrivateApiTest() : ExtensionApiTest(GetParam()) {} ~SettingsPrivateApiTest() override = default; SettingsPrivateApiTest(const SettingsPrivateApiTest&) = delete; SettingsPrivateApiTest& operator=(const SettingsPrivateApiTest&) = delete; @@ -65,10 +65,8 @@ class SettingsPrivateApiTest : public ExtensionApiTest, protected: bool RunSettingsSubtest(const std::string& subtest) { - return RunExtensionTest( - "settings_private", {.custom_arg = subtest.c_str()}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker, - .load_as_component = true}); + return RunExtensionTest("settings_private", {.custom_arg = subtest.c_str()}, + {.load_as_component = true}); } void SetPrefPolicy(const std::string& key, policy::PolicyLevel level) { diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc b/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc index 9a73cdb95c6..e36b9b52c5b 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_browsertest_chromeos.cc @@ -21,7 +21,7 @@ namespace { class SettingsPrivateGuestModeTest : public MixinBasedInProcessBrowserTest { protected: - chromeos::GuestSessionMixin guest_session_{&mixin_host_}; + ash::GuestSessionMixin guest_session_{&mixin_host_}; }; // Regression test for https://crbug.com/887383. diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h index 1826e7b90a1..81a8d627c93 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate.h @@ -32,6 +32,10 @@ using TypedPrefMap = std::map<std::string, api::settings_private::PrefType>; class SettingsPrivateDelegate : public KeyedService { public: explicit SettingsPrivateDelegate(Profile* profile); + + SettingsPrivateDelegate(const SettingsPrivateDelegate&) = delete; + SettingsPrivateDelegate& operator=(const SettingsPrivateDelegate&) = delete; + ~SettingsPrivateDelegate() override; // Sets the pref with the given name and value in the proper PrefService. @@ -55,9 +59,6 @@ class SettingsPrivateDelegate : public KeyedService { protected: Profile* profile_; // weak; not owned by us std::unique_ptr<PrefsUtil> prefs_util_; - - private: - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateDelegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.h index 65a19ab7d18..25b1d8492c9 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.h +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_delegate_factory.h @@ -20,6 +20,11 @@ class SettingsPrivateDelegate; class SettingsPrivateDelegateFactory : public BrowserContextKeyedServiceFactory { public: + SettingsPrivateDelegateFactory(const SettingsPrivateDelegateFactory&) = + delete; + SettingsPrivateDelegateFactory& operator=( + const SettingsPrivateDelegateFactory&) = delete; + static SettingsPrivateDelegate* GetForBrowserContext( content::BrowserContext* browser_context); @@ -36,8 +41,6 @@ class SettingsPrivateDelegateFactory content::BrowserContext* profile) const override; content::BrowserContext* GetBrowserContextToUse( content::BrowserContext* context) const override; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateDelegateFactory); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h index 1ee722b2169..11c0572734f 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router.h @@ -37,6 +37,11 @@ class SettingsPrivateEventRouter public: static SettingsPrivateEventRouter* Create( content::BrowserContext* browser_context); + + SettingsPrivateEventRouter(const SettingsPrivateEventRouter&) = delete; + SettingsPrivateEventRouter& operator=(const SettingsPrivateEventRouter&) = + delete; + ~SettingsPrivateEventRouter() override; // settings_private::GeneratedPref::Observer implementation. @@ -85,8 +90,6 @@ class SettingsPrivateEventRouter std::unique_ptr<PrefsUtil> prefs_util_; base::WeakPtrFactory<SettingsPrivateEventRouter> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h index fe475609fe7..cf6859dc25a 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h +++ b/chromium/chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h @@ -19,6 +19,11 @@ class SettingsPrivateEventRouter; class SettingsPrivateEventRouterFactory : public BrowserContextKeyedServiceFactory { public: + SettingsPrivateEventRouterFactory(const SettingsPrivateEventRouterFactory&) = + delete; + SettingsPrivateEventRouterFactory& operator=( + const SettingsPrivateEventRouterFactory&) = delete; + // Returns the SettingsPrivateEventRouter for |profile|, creating it if // it is not yet created. static SettingsPrivateEventRouter* GetForProfile( @@ -43,8 +48,6 @@ class SettingsPrivateEventRouterFactory // BrowserContextKeyedServiceFactory: KeyedService* BuildServiceInstanceFor( content::BrowserContext* profile) const override; - - DISALLOW_COPY_AND_ASSIGN(SettingsPrivateEventRouterFactory); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc index 5aba4b391f3..0e9371f640d 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc @@ -118,7 +118,7 @@ std::unique_ptr<DeviceInfo> GetLocalDeviceInfo(const std::string& extension_id, ExtensionFunction::ResponseAction SignedInDevicesGetFunction::Run() { std::unique_ptr<api::signed_in_devices::Get::Params> params( - api::signed_in_devices::Get::Params::Create(*args_)); + api::signed_in_devices::Get::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); bool is_local = params->is_local.get() ? *params->is_local : false; diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h index b5ec792cf65..8c015fcc85f 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager.h @@ -42,6 +42,11 @@ class SignedInDevicesChangeObserver public: SignedInDevicesChangeObserver(const std::string& extension_id, Profile* profile); + + SignedInDevicesChangeObserver(const SignedInDevicesChangeObserver&) = delete; + SignedInDevicesChangeObserver& operator=( + const SignedInDevicesChangeObserver&) = delete; + virtual ~SignedInDevicesChangeObserver(); void OnDeviceInfoChange() override; @@ -54,8 +59,6 @@ class SignedInDevicesChangeObserver std::string extension_id_; Profile* const profile_; content::NotificationRegistrar registrar_; - - DISALLOW_COPY_AND_ASSIGN(SignedInDevicesChangeObserver); }; class SignedInDevicesManager : public BrowserContextKeyedAPI, @@ -65,6 +68,10 @@ class SignedInDevicesManager : public BrowserContextKeyedAPI, // Default constructor used for testing. SignedInDevicesManager(); explicit SignedInDevicesManager(content::BrowserContext* context); + + SignedInDevicesManager(const SignedInDevicesManager&) = delete; + SignedInDevicesManager& operator=(const SignedInDevicesManager&) = delete; + ~SignedInDevicesManager() override; // BrowserContextKeyedAPI implementation. @@ -100,8 +107,6 @@ class SignedInDevicesManager : public BrowserContextKeyedAPI, extension_registry_observation_{this}; FRIEND_TEST_ALL_PREFIXES(SignedInDevicesManager, UpdateListener); - - DISALLOW_COPY_AND_ASSIGN(SignedInDevicesManager); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc index 5c184988ba3..48b59f5d54f 100644 --- a/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/tcp_socket_unittest.cc @@ -474,6 +474,11 @@ class ExtensionsMockClientSocket : public net::MockTCPClientSocket { success_(success) { this->set_enable_read_if_ready(true); } + + ExtensionsMockClientSocket(const ExtensionsMockClientSocket&) = delete; + ExtensionsMockClientSocket& operator=(const ExtensionsMockClientSocket&) = + delete; + ~ExtensionsMockClientSocket() override {} bool SetNoDelay(bool no_delay) override { return success_; } @@ -482,8 +487,6 @@ class ExtensionsMockClientSocket : public net::MockTCPClientSocket { private: // Whether to return success for SetNoDelay() and SetKeepAlive(). const bool success_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionsMockClientSocket); }; static const net::MockRead kMockReads[] = {net::MockRead(net::ASYNC, net::OK)}; @@ -493,6 +496,10 @@ static const net::MockRead kMockReads[] = {net::MockRead(net::ASYNC, net::OK)}; class TestSocketFactory : public net::ClientSocketFactory { public: explicit TestSocketFactory(bool success) : success_(success) {} + + TestSocketFactory(const TestSocketFactory&) = delete; + TestSocketFactory& operator=(const TestSocketFactory&) = delete; + ~TestSocketFactory() override = default; std::unique_ptr<net::DatagramClientSocket> CreateDatagramClientSocket( @@ -541,8 +548,6 @@ class TestSocketFactory : public net::ClientSocketFactory { // Whether to return success for net::TransportClientSocket::SetNoDelay() and // SetKeepAlive(). const bool success_; - - DISALLOW_COPY_AND_ASSIGN(TestSocketFactory); }; } // namespace @@ -680,14 +685,16 @@ TEST_F(TCPSocketServerTest, ReadAndWrite) { // Create a server socket. std::unique_ptr<TCPSocket> socket = CreateSocket(); net::TestCompletionCallback callback; - base::RunLoop run_loop; - socket->Listen( - "127.0.0.1", 0 /* port */, 1 /* backlog */, - base::BindLambdaForTesting([&](int result, const std::string& error_msg) { - EXPECT_EQ(net::OK, result); - run_loop.Quit(); - })); - run_loop.Run(); + { + base::RunLoop run_loop; + socket->Listen("127.0.0.1", 0 /* port */, 1 /* backlog */, + base::BindLambdaForTesting( + [&](int result, const std::string& error_msg) { + EXPECT_EQ(net::OK, result); + run_loop.Quit(); + })); + run_loop.Run(); + } net::IPEndPoint server_addr; EXPECT_TRUE(socket->GetLocalAddress(&server_addr)); diff --git a/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc b/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc index 9db910b3146..92f003e2477 100644 --- a/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc @@ -151,7 +151,7 @@ static void SendMulticastPacket(base::OnceClosure quit_run_loop, FROM_HERE, base::BindOnce(&SendMulticastPacket, std::move(quit_run_loop), src, result), - base::TimeDelta::FromSeconds(1)); + base::Seconds(1)); } else { std::move(quit_run_loop).Run(); FAIL() << "Failed to connect to multicast address. Error code: " << result; diff --git a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc index 07f55616e2f..2269b14015f 100644 --- a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc +++ b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.cc @@ -25,16 +25,17 @@ #include "components/policy/core/common/schema.h" #include "components/policy/core/common/schema_map.h" #include "components/policy/core/common/schema_registry.h" +#include "components/value_store/value_store_change.h" +#include "components/value_store/value_store_factory.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/storage/backend_task_runner.h" +#include "extensions/browser/api/storage/value_store_util.h" #include "extensions/browser/extension_file_task_runner.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/browser/extension_system.h" -#include "extensions/browser/value_store/value_store_change.h" -#include "extensions/browser/value_store/value_store_factory.h" #include "extensions/common/api/storage.h" #include "extensions/common/constants.h" #include "extensions/common/extension.h" @@ -56,8 +57,8 @@ class ExtensionRegistry; namespace { // Only extension settings are stored in the managed namespace - not apps. -const ValueStoreFactory::ModelType kManagedModelType = - ValueStoreFactory::ModelType::EXTENSION; +const value_store_util::ModelType kManagedModelType = + value_store_util::ModelType::EXTENSION; } // namespace @@ -70,6 +71,10 @@ class ManagedValueStoreCache::ExtensionTracker : public ExtensionRegistryObserver { public: ExtensionTracker(Profile* profile, policy::PolicyDomain policy_domain); + + ExtensionTracker(const ExtensionTracker&) = delete; + ExtensionTracker& operator=(const ExtensionTracker&) = delete; + ~ExtensionTracker() override {} private: @@ -103,8 +108,6 @@ class ManagedValueStoreCache::ExtensionTracker extension_registry_observation_{this}; policy::SchemaRegistry* schema_registry_; base::WeakPtrFactory<ExtensionTracker> weak_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(ExtensionTracker); }; ManagedValueStoreCache::ExtensionTracker::ExtensionTracker( @@ -229,7 +232,7 @@ void ManagedValueStoreCache::ExtensionTracker::Register( ManagedValueStoreCache::ManagedValueStoreCache( BrowserContext* context, - scoped_refptr<ValueStoreFactory> factory, + scoped_refptr<value_store::ValueStoreFactory> factory, scoped_refptr<SettingsObserverList> observers) : profile_(Profile::FromBrowserContext(context)), policy_domain_(GetPolicyDomain(profile_)), @@ -359,8 +362,9 @@ PolicyValueStore* ManagedValueStoreCache::GetStoreFor( // sends updated values. std::unique_ptr<PolicyValueStore> store(new PolicyValueStore( extension_id, observers_, - storage_factory_->CreateSettingsStore(settings_namespace::MANAGED, - kManagedModelType, extension_id))); + value_store_util::CreateSettingsStore(settings_namespace::MANAGED, + kManagedModelType, extension_id, + storage_factory_))); PolicyValueStore* raw_store = store.get(); store_map_[extension_id] = std::move(store); @@ -369,8 +373,9 @@ PolicyValueStore* ManagedValueStoreCache::GetStoreFor( bool ManagedValueStoreCache::HasStore(const std::string& extension_id) const { // Note: Currently only manage extensions (not apps). - return storage_factory_->HasSettings(settings_namespace::MANAGED, - kManagedModelType, extension_id); + return value_store_util::HasValueStore(settings_namespace::MANAGED, + kManagedModelType, extension_id, + storage_factory_); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.h b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.h index a4d0b437b1d..c6a377061f3 100644 --- a/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.h +++ b/chromium/chrome/browser/extensions/api/storage/managed_value_store_cache.h @@ -27,10 +27,13 @@ namespace policy { class PolicyMap; } +namespace value_store { +class ValueStoreFactory; +} + namespace extensions { class PolicyValueStore; -class ValueStoreFactory; // A ValueStoreCache that manages a PolicyValueStore for each extension that // uses the storage.managed namespace. This class observes policy changes and @@ -43,8 +46,12 @@ class ManagedValueStoreCache : public ValueStoreCache, // |observers| is the list of SettingsObservers to notify when a ValueStore // changes. ManagedValueStoreCache(content::BrowserContext* context, - scoped_refptr<ValueStoreFactory> factory, + scoped_refptr<value_store::ValueStoreFactory> factory, scoped_refptr<SettingsObserverList> observers); + + ManagedValueStoreCache(const ManagedValueStoreCache&) = delete; + ManagedValueStoreCache& operator=(const ManagedValueStoreCache&) = delete; + ~ManagedValueStoreCache() override; private: @@ -93,14 +100,12 @@ class ManagedValueStoreCache : public ValueStoreCache, std::unique_ptr<ExtensionTracker> extension_tracker_; // These live on the FILE thread. - scoped_refptr<ValueStoreFactory> storage_factory_; + scoped_refptr<value_store::ValueStoreFactory> storage_factory_; scoped_refptr<SettingsObserverList> observers_; // All the PolicyValueStores live on the FILE thread, and |store_map_| can be // accessed only on the FILE thread as well. std::map<std::string, std::unique_ptr<PolicyValueStore>> store_map_; - - DISALLOW_COPY_AND_ASSIGN(ManagedValueStoreCache); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc b/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc index 431f560418f..4965996f42b 100644 --- a/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc +++ b/chromium/chrome/browser/extensions/api/storage/policy_value_store.cc @@ -10,9 +10,11 @@ #include "base/values.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" +#include "components/value_store/value_store_change.h" #include "extensions/browser/api/storage/backend_task_runner.h" #include "extensions/browser/api/storage/storage_area_namespace.h" -#include "extensions/browser/value_store/value_store_change.h" + +using value_store::ValueStore; namespace extensions { @@ -72,7 +74,7 @@ void PolicyValueStore::SetCurrentPolicy(const policy::PolicyMap& policy) { removed_keys.push_back(it.key()); } - ValueStoreChangeList changes; + value_store::ValueStoreChangeList changes; { WriteResult result = delegate_->Remove(removed_keys); @@ -98,9 +100,10 @@ void PolicyValueStore::SetCurrentPolicy(const policy::PolicyMap& policy) { } if (!changes.empty()) { - observers_->Notify(FROM_HERE, &SettingsObserver::OnSettingsChanged, - extension_id_, StorageAreaNamespace::kManaged, - ValueStoreChange::ToValue(std::move(changes))); + observers_->Notify( + FROM_HERE, &SettingsObserver::OnSettingsChanged, extension_id_, + StorageAreaNamespace::kManaged, + value_store::ValueStoreChange::ToValue(std::move(changes))); } } diff --git a/chromium/chrome/browser/extensions/api/storage/policy_value_store.h b/chromium/chrome/browser/extensions/api/storage/policy_value_store.h index da8da845e59..4efbb6dc8ab 100644 --- a/chromium/chrome/browser/extensions/api/storage/policy_value_store.h +++ b/chromium/chrome/browser/extensions/api/storage/policy_value_store.h @@ -14,8 +14,8 @@ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "components/value_store/value_store.h" #include "extensions/browser/api/storage/settings_observer.h" -#include "extensions/browser/value_store/value_store.h" namespace policy { class PolicyMap; @@ -28,11 +28,15 @@ namespace extensions { // run the function of the storage.managed namespace; it's read-only for the // extension. The ManagedValueStoreCache sends updated policy to this store // and manages its lifetime. -class PolicyValueStore : public ValueStore { +class PolicyValueStore : public value_store::ValueStore { public: PolicyValueStore(const std::string& extension_id, scoped_refptr<SettingsObserverList> observers, - std::unique_ptr<ValueStore> delegate); + std::unique_ptr<value_store::ValueStore> delegate); + + PolicyValueStore(const PolicyValueStore&) = delete; + PolicyValueStore& operator=(const PolicyValueStore&) = delete; + ~PolicyValueStore() override; // Stores |policy| in the persistent database represented by the |delegate_| @@ -59,14 +63,12 @@ class PolicyValueStore : public ValueStore { WriteResult Clear() override; // For unit tests. - ValueStore* delegate() { return delegate_.get(); } + value_store::ValueStore* delegate() { return delegate_.get(); } private: std::string extension_id_; scoped_refptr<SettingsObserverList> observers_; - std::unique_ptr<ValueStore> delegate_; - - DISALLOW_COPY_AND_ASSIGN(PolicyValueStore); + std::unique_ptr<value_store::ValueStore> delegate_; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc b/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc index 6ceb7b0f98a..a6327a52707 100644 --- a/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc +++ b/chromium/chrome/browser/extensions/api/storage/policy_value_store_unittest.cc @@ -16,19 +16,21 @@ #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_types.h" +#include "components/value_store/leveldb_value_store.h" +#include "components/value_store/value_store_test_suite.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/storage/backend_task_runner.h" #include "extensions/browser/api/storage/settings_observer.h" #include "extensions/browser/api/storage/storage_area_namespace.h" -#include "extensions/browser/value_store/leveldb_value_store.h" -#include "extensions/browser/value_store/value_store_unittest.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::Mock; using testing::NiceMock; +using value_store::ValueStore; +using value_store::ValueStoreTestSuite; namespace extensions { @@ -44,8 +46,9 @@ std::string ValueToJson(const base::Value& changes) { return json; } -std::string ValueStoreChangeToJson(ValueStoreChangeList changes) { - return ValueToJson(ValueStoreChange::ToValue(std::move(changes))); +std::string ValueStoreChangeToJson(value_store::ValueStoreChangeList changes) { + return ValueToJson( + value_store::ValueStoreChange::ToValue(std::move(changes))); } class MockSettingsObserver : public SettingsObserver { @@ -63,17 +66,21 @@ class MockSettingsObserver : public SettingsObserver { }; // Extends PolicyValueStore by overriding the mutating methods, so that the -// Get() base implementation can be tested with the ValueStoreTest parameterized -// tests. +// Get() base implementation can be tested with the ValueStoreTestSuite +// parameterized tests. class MutablePolicyValueStore : public PolicyValueStore { public: explicit MutablePolicyValueStore(const base::FilePath& path) - : PolicyValueStore( - kTestExtensionId, - base::MakeRefCounted<SettingsObserverList>(), - std::make_unique<LeveldbValueStore>(kDatabaseUMAClientName, path)) { - } - ~MutablePolicyValueStore() override {} + : PolicyValueStore(kTestExtensionId, + base::MakeRefCounted<SettingsObserverList>(), + std::make_unique<value_store::LeveldbValueStore>( + kDatabaseUMAClientName, + path)) {} + + MutablePolicyValueStore(const MutablePolicyValueStore&) = delete; + MutablePolicyValueStore& operator=(const MutablePolicyValueStore&) = delete; + + ~MutablePolicyValueStore() override = default; WriteResult Set(WriteOptions options, const std::string& key, @@ -95,9 +102,6 @@ class MutablePolicyValueStore : public PolicyValueStore { } WriteResult Clear() override { return delegate()->Clear(); } - - private: - DISALLOW_COPY_AND_ASSIGN(MutablePolicyValueStore); }; ValueStore* Param(const base::FilePath& file_path) { @@ -107,7 +111,7 @@ ValueStore* Param(const base::FilePath& file_path) { } // namespace INSTANTIATE_TEST_SUITE_P(PolicyValueStoreTest, - ValueStoreTest, + ValueStoreTestSuite, testing::Values(&Param)); class PolicyValueStoreTest : public testing::Test { @@ -121,8 +125,8 @@ class PolicyValueStoreTest : public testing::Test { observers_->AddObserver(&observer_); store_ = std::make_unique<PolicyValueStore>( kTestExtensionId, observers_, - std::make_unique<LeveldbValueStore>(kDatabaseUMAClientName, - scoped_temp_dir_.GetPath())); + std::make_unique<value_store::LeveldbValueStore>( + kDatabaseUMAClientName, scoped_temp_dir_.GetPath())); } void TearDown() override { @@ -192,8 +196,9 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { // Notify when setting the initial policy. const base::Value value("111"); { - ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("aaa", absl::nullopt, value.Clone())); + value_store::ValueStoreChangeList changes; + changes.push_back( + value_store::ValueStoreChange("aaa", absl::nullopt, value.Clone())); EXPECT_CALL(observer_, OnSettingsChangedJSON( kTestExtensionId, StorageAreaNamespace::kManaged, ValueStoreChangeToJson(std::move(changes)))); @@ -207,8 +212,9 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { // Notify when new policies are added. { - ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("bbb", absl::nullopt, value.Clone())); + value_store::ValueStoreChangeList changes; + changes.push_back( + value_store::ValueStoreChange("bbb", absl::nullopt, value.Clone())); EXPECT_CALL(observer_, OnSettingsChangedJSON( kTestExtensionId, StorageAreaNamespace::kManaged, ValueStoreChangeToJson(std::move(changes)))); @@ -222,9 +228,9 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { // Notify when policies change. const base::Value new_value("222"); { - ValueStoreChangeList changes; + value_store::ValueStoreChangeList changes; changes.push_back( - ValueStoreChange("bbb", value.Clone(), new_value.Clone())); + value_store::ValueStoreChange("bbb", value.Clone(), new_value.Clone())); EXPECT_CALL(observer_, OnSettingsChangedJSON( kTestExtensionId, StorageAreaNamespace::kManaged, ValueStoreChangeToJson(std::move(changes)))); @@ -237,9 +243,9 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { // Notify when policies are removed. { - ValueStoreChangeList changes; + value_store::ValueStoreChangeList changes; changes.push_back( - ValueStoreChange("bbb", new_value.Clone(), absl::nullopt)); + value_store::ValueStoreChange("bbb", new_value.Clone(), absl::nullopt)); EXPECT_CALL(observer_, OnSettingsChangedJSON( kTestExtensionId, StorageAreaNamespace::kManaged, ValueStoreChangeToJson(std::move(changes)))); diff --git a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h index 21f1c2ad4c8..cb0bb196ada 100644 --- a/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h +++ b/chromium/chrome/browser/extensions/api/storage/setting_sync_data.h @@ -35,6 +35,9 @@ class SettingSyncData { const std::string& key, std::unique_ptr<base::Value> value); + SettingSyncData(const SettingSyncData&) = delete; + SettingSyncData& operator=(const SettingSyncData&) = delete; + ~SettingSyncData(); // May return absl::nullopt if this object represents sync data that isn't @@ -61,8 +64,6 @@ class SettingSyncData { std::string extension_id_; std::string key_; std::unique_ptr<base::Value> value_; - - DISALLOW_COPY_AND_ASSIGN(SettingSyncData); }; using SettingSyncDataList = std::vector<std::unique_ptr<SettingSyncData>>; diff --git a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc index c130c238069..33f5b030e4f 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_apitest.cc @@ -36,10 +36,10 @@ #include "components/version_info/channel.h" #include "content/public/test/browser_test.h" #include "extensions/browser/api/storage/backend_task_runner.h" +#include "extensions/browser/api/storage/settings_namespace.h" #include "extensions/browser/api/storage/storage_area_namespace.h" #include "extensions/browser/api/storage/storage_frontend.h" #include "extensions/browser/extension_system.h" -#include "extensions/browser/value_store/settings_namespace.h" #include "extensions/common/features/feature_channel.h" #include "extensions/common/value_builder.h" #include "extensions/test/extension_test_message_listener.h" @@ -49,10 +49,7 @@ namespace extensions { -using testing::_; -using testing::Mock; using testing::NiceMock; -using testing::Return; namespace { @@ -64,17 +61,39 @@ const syncer::ModelType kModelType = syncer::EXTENSION_SETTINGS; // the extension. const char kManagedStorageExtensionId[] = "kjmkgkdkpedkejedfhmfcenooemhbpbo"; -class MockSchemaRegistryObserver : public policy::SchemaRegistry::Observer { +class TestSchemaRegistryObserver : public policy::SchemaRegistry::Observer { public: - MockSchemaRegistryObserver() {} - ~MockSchemaRegistryObserver() override {} + TestSchemaRegistryObserver() = default; + ~TestSchemaRegistryObserver() override = default; + TestSchemaRegistryObserver(const TestSchemaRegistryObserver&) = delete; + TestSchemaRegistryObserver& operator=(const TestSchemaRegistryObserver&) = + delete; + + void OnSchemaRegistryUpdated(bool has_new_schemas) override { + has_new_schemas_ = has_new_schemas; + run_loop_.Quit(); + } - MOCK_METHOD1(OnSchemaRegistryUpdated, void(bool)); + void WaitForSchemaRegistryUpdated() { run_loop_.Run(); } + + bool has_new_schemas() const { return has_new_schemas_; } + + private: + bool has_new_schemas_ = false; + base::RunLoop run_loop_; }; } // namespace class ExtensionSettingsApiTest : public ExtensionApiTest { + public: + explicit ExtensionSettingsApiTest( + ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) {} + ~ExtensionSettingsApiTest() override = default; + ExtensionSettingsApiTest(const ExtensionSettingsApiTest&) = delete; + ExtensionSettingsApiTest& operator=(const ExtensionSettingsApiTest&) = delete; + protected: void SetUpInProcessBrowserTestFixture() override { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); @@ -230,65 +249,30 @@ class ExtensionSettingsApiTest : public ExtensionApiTest { testing::NiceMock<policy::MockConfigurationPolicyProvider> policy_provider_; }; -// A specialization of ExtensionSettingsApiTest that pretends it's running -// on version_info::Channel::UNKNOWN. -class ExtensionSettingsTrunkApiTest : public ExtensionSettingsApiTest { - public: - ExtensionSettingsTrunkApiTest() = default; - ~ExtensionSettingsTrunkApiTest() override = default; - ExtensionSettingsTrunkApiTest(const ExtensionSettingsTrunkApiTest& other) = - delete; - ExtensionSettingsTrunkApiTest& operator=( - const ExtensionSettingsTrunkApiTest& other) = delete; - - private: - // TODO(crbug.com/1185226): Remove unknown channel when chrome.storage.session - // is released in stable. - ScopedCurrentChannel current_channel_{version_info::Channel::UNKNOWN}; -}; - -// A specialization of ExtensionSettingsApiTest that pretends it's running -// on version_info::Channel::DEV. -class ExtensionSettingsDevApiTest : public ExtensionSettingsApiTest { - public: - ExtensionSettingsDevApiTest() = default; - ~ExtensionSettingsDevApiTest() override = default; - ExtensionSettingsDevApiTest(const ExtensionSettingsDevApiTest& other) = - delete; - ExtensionSettingsDevApiTest& operator=( - const ExtensionSettingsDevApiTest& other) = delete; - - private: - // TODO(crbug.com/1185226): Remove dev channel when chrome.storage.session - // is released in stable. - ScopedCurrentChannel current_channel_{version_info::Channel::DEV}; -}; - -// TODO(crbug.com/1185226): Remove test when chrome.storage.session -// is released in stable. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsDevApiTest, - SessionInUnsupportedChannel) { +IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, + SessionInUnsupportedExtension) { constexpr char kManifest[] = R"({ - "name": "Unsupported channel for session", - "manifest_version": 3, - "version": "0.1", - "background": { "service_worker": "worker.js" }, - "permissions": ["storage"] - })"; - - constexpr char kWorker[] = - R"(chrome.test.runTests([ - function unsupported() { - chrome.test.assertEq(undefined, chrome.storage.session); - chrome.test.assertTrue(!!chrome.storage.local); - chrome.test.succeed(); - }, - ]);)"; + "name": "Unsupported manifest version for Storage API", + "manifest_version": 2, + "version": "0.1", + "background": {"scripts": ["script.js"]}, + "permissions": ["storage"] + })"; + constexpr char kScript[] = + R"({ + chrome.test.runTests([ + function unsupported() { + chrome.test.assertEq(undefined, chrome.storage.session), + chrome.test.assertTrue(!!chrome.storage.local); + chrome.test.succeed(); + } + ]) + })"; TestExtensionDir test_dir; test_dir.WriteManifest(kManifest); - test_dir.WriteFile(FILE_PATH_LITERAL("worker.js"), kWorker); + test_dir.WriteFile(FILE_PATH_LITERAL("script.js"), kScript); ResultCatcher catcher; const Extension* extension = LoadExtension(test_dir.UnpackedPath()); @@ -296,9 +280,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsDevApiTest, ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } -// TODO(crbug.com/1185226): Change parent class to `ExtensionSettingsApiTest` -// when chrome.storage.session is released in stable. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsTrunkApiTest, SimpleTest) { +IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, SimpleTest) { ASSERT_TRUE(RunExtensionTest("settings/simple_test")) << message_; } @@ -306,9 +288,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsTrunkApiTest, SimpleTest) { // Note that only split-mode incognito is tested, because spanning mode // incognito looks the same as normal mode when the only API activity comes // from background pages. -// TODO(crbug.com/1185226): Change parent class to `ExtensionSettingsApiTest` -// when chrome.storage.session is released in stable. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsTrunkApiTest, SplitModeIncognito) { +IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, SplitModeIncognito) { // We need 2 ResultCatchers because we'll be running the same test in both // regular and incognito mode. ResultCatcher catcher; @@ -342,14 +322,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsTrunkApiTest, SplitModeIncognito) { EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); } -// TODO(crbug.com/1185226): Change parent class to `ExtensionSettingsApiTest` -// when chrome.storage.session is released in stable. // TODO(crbug.com/1229351): Service worker extension listener should receive an // event before the callback is made. Current workaround: wait for the event to // be received by the extension before checking for it. Potential solution: once // browser-side observation of SW lifetime work is finished, check if it fixes // this test. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsTrunkApiTest, +IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, OnChangedNotificationsBetweenBackgroundPages) { // We need 2 ResultCatchers because we'll be running the same test in both // regular and incognito mode. @@ -397,9 +375,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsTrunkApiTest, EXPECT_TRUE(catcher_incognito.GetNextResult()) << catcher.message(); } -// TODO(crbug.com/1185226): Change parent class to `ExtensionSettingsApiTest` -// when chrome.storage.session is released in stable. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsTrunkApiTest, +IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, SyncLocalAndSessionAreasAreSeparate) { // We need 2 ResultCatchers because we'll be running the same test in both // regular and incognito mode. @@ -605,9 +581,40 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, IsStorageEnabled) { EXPECT_TRUE(frontend->IsStorageEnabled(settings_namespace::MANAGED)); } -// Bulk disabled as part of arm64 bot stabilization: https://crbug.com/1154345 -// TODO(crbug.com/1177118) Re-enable test -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, DISABLED_ExtensionsSchemas) { +using ContextType = ExtensionBrowserTest::ContextType; + +class ExtensionSettingsManagedStorageApiTest + : public ExtensionSettingsApiTest, + public testing::WithParamInterface<ContextType> { + public: + ExtensionSettingsManagedStorageApiTest() + : ExtensionSettingsApiTest(GetParam()) {} + ~ExtensionSettingsManagedStorageApiTest() override = default; + ExtensionSettingsManagedStorageApiTest( + const ExtensionSettingsManagedStorageApiTest& other) = delete; + ExtensionSettingsManagedStorageApiTest& operator=( + const ExtensionSettingsManagedStorageApiTest& other) = delete; + + // TODO(crbug.com/1247323): Remove this. + // The ManagedStorageEvents test has a PRE_ step loads an extension which + // then runs in the main step. Since the extension immediately starts + // running the tests, constructing a ResultCatcher in the body of the + // fixture will occasionally miss the result from the JS test, leading + // to a flaky result. This ResultCatcher will be always be constructed + // before the test starts running. + ResultCatcher events_result_catcher_; +}; + +INSTANTIATE_TEST_SUITE_P(PersistentBackground, + ExtensionSettingsManagedStorageApiTest, + ::testing::Values(ContextType::kPersistentBackground)); + +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + ExtensionSettingsManagedStorageApiTest, + ::testing::Values(ContextType::kServiceWorker)); + +IN_PROC_BROWSER_TEST_P(ExtensionSettingsManagedStorageApiTest, + ExtensionsSchemas) { // Verifies that the Schemas for the extensions domain are created on startup. Profile* profile = browser()->profile(); ExtensionSystem* extension_system = ExtensionSystem::Get(profile); @@ -629,15 +636,20 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, DISABLED_ExtensionsSchemas) { EXPECT_FALSE(registry->schema_map()->GetSchema(policy::PolicyNamespace( policy::POLICY_DOMAIN_EXTENSIONS, kManagedStorageExtensionId))); - NiceMock<MockSchemaRegistryObserver> observer; + TestSchemaRegistryObserver observer; registry->AddObserver(&observer); // Install a managed extension. - EXPECT_CALL(observer, OnSchemaRegistryUpdated(true)); - const Extension* extension = - LoadExtension(test_data_dir_.AppendASCII("settings/managed_storage")); + ExtensionTestMessageListener listener("ready", false); + const Extension* extension = LoadExtension( + test_data_dir_.AppendASCII("settings/managed_storage_schemas")); + ASSERT_TRUE(listener.WaitUntilSatisfied()); ASSERT_TRUE(extension); - Mock::VerifyAndClearExpectations(&observer); + observer.WaitForSchemaRegistryUpdated(); + + // Verify the schemas were installed. + EXPECT_TRUE(observer.has_new_schemas()); + registry->RemoveObserver(&observer); // Verify that its schema has been published, and verify its contents. @@ -686,9 +698,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, DISABLED_ExtensionsSchemas) { EXPECT_EQ(base::Value::Type::INTEGER, dict.GetProperty("anything").type()); } -// Bulk disabled as part of arm64 bot stabilization: https://crbug.com/1154345 -// TODO(crbug.com/1177118) Re-enable test -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, DISABLED_ManagedStorage) { +// TODO(crbug.com/1247323): This test should be rewritten. See the bug for more +// details. +IN_PROC_BROWSER_TEST_P(ExtensionSettingsManagedStorageApiTest, ManagedStorage) { // Set policies for the test extension. std::unique_ptr<base::DictionaryValue> policy = extensions::DictionaryBuilder() @@ -722,12 +734,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, DISABLED_ManagedStorage) { ASSERT_TRUE(RunExtensionTest("settings/managed_storage")) << message_; } -// TODO(crbug.com/1241501): Somewhat flaky on all bots, but worse on the Linux -// and ChromeOS bots. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, - DISABLED_PRE_ManagedStorageEvents) { - ResultCatcher catcher; - +// TODO(crbug.com/1247323): This test should be rewritten. See the bug for more +// details. +IN_PROC_BROWSER_TEST_P(ExtensionSettingsManagedStorageApiTest, + PRE_ManagedStorageEvents) { // This test starts without any test extensions installed. EXPECT_FALSE(GetSingleLoadedExtension()); message_.clear(); @@ -742,9 +752,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, SetPolicies(*policy); ExtensionTestMessageListener ready_listener("ready", false); - // Load the extension to install the event listener. + // Load the extension to install the event listener and wait for the + // extension's registration to be stored since it must persist after + // this PRE_ step exits. Otherwise, the test will be flaky, since the + // extension's service worker registration might not get stored. const Extension* extension = LoadExtension( - test_data_dir_.AppendASCII("settings/managed_storage_events")); + test_data_dir_.AppendASCII("settings/managed_storage_events"), + {.wait_for_registration_stored = true}); ASSERT_TRUE(extension); // Wait until the extension sends the "ready" message. ASSERT_TRUE(ready_listener.WaitUntilSatisfied()); @@ -756,20 +770,17 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, .Set("new-policy", "eee") .Build(); SetPolicies(*policy); - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); + EXPECT_TRUE(events_result_catcher_.GetNextResult()) + << events_result_catcher_.message(); } -// TODO(crbug.com/1241501): Somewhat flaky on all bots, but worse on the Linux -// and ChromeOS bots. -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, - DISABLED_ManagedStorageEvents) { +IN_PROC_BROWSER_TEST_P(ExtensionSettingsManagedStorageApiTest, + ManagedStorageEvents) { // This test runs after PRE_ManagedStorageEvents without having deleted the // profile, so the extension is still around. While the browser restarted the // policy went back to the empty default, and so the extension should receive // the corresponding change events. - ResultCatcher catcher; - // Verify that the test extension is still installed. const Extension* extension = GetSingleLoadedExtension(); ASSERT_TRUE(extension); @@ -777,10 +788,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, // Running the test again skips the onInstalled callback, and just triggers // the onChanged notification. - EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); + EXPECT_TRUE(events_result_catcher_.GetNextResult()) + << events_result_catcher_.message(); } -IN_PROC_BROWSER_TEST_F(ExtensionSettingsApiTest, ManagedStorageDisabled) { +IN_PROC_BROWSER_TEST_P(ExtensionSettingsManagedStorageApiTest, + ManagedStorageDisabled) { // Disable the 'managed' namespace. StorageFrontend* frontend = StorageFrontend::Get(browser()->profile()); frontend->DisableStorageForTesting(settings_namespace::MANAGED); diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc index c517a240689..90ed73c31c7 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.cc @@ -11,7 +11,7 @@ #include "components/sync/model/sync_data.h" #include "components/sync/protocol/extension_setting_specifics.pb.h" #include "extensions/browser/api/storage/backend_task_runner.h" -#include "extensions/browser/value_store/settings_namespace.h" +#include "extensions/browser/api/storage/settings_namespace.h" namespace extensions { @@ -44,7 +44,7 @@ void SettingsSyncProcessor::Init(const base::DictionaryValue& initial_state) { } absl::optional<syncer::ModelError> SettingsSyncProcessor::SendChanges( - const ValueStoreChangeList& changes) { + const value_store::ValueStoreChangeList& changes) { DCHECK(IsOnBackendSequence()); CHECK(initialized_) << "Init not called"; @@ -94,7 +94,8 @@ absl::optional<syncer::ModelError> SettingsSyncProcessor::SendChanges( return absl::nullopt; } -void SettingsSyncProcessor::NotifyChanges(const ValueStoreChangeList& changes) { +void SettingsSyncProcessor::NotifyChanges( + const value_store::ValueStoreChangeList& changes) { DCHECK(IsOnBackendSequence()); CHECK(initialized_) << "Init not called"; diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h index bebf17e02d7..7e3ca713233 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_processor.h @@ -10,7 +10,7 @@ #include "base/macros.h" #include "components/sync/base/model_type.h" -#include "extensions/browser/value_store/value_store_change.h" +#include "components/value_store/value_store_change.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace syncer { @@ -31,6 +31,10 @@ class SettingsSyncProcessor { SettingsSyncProcessor(const std::string& extension_id, syncer::ModelType type, syncer::SyncChangeProcessor* sync_processor); + + SettingsSyncProcessor(const SettingsSyncProcessor&) = delete; + SettingsSyncProcessor& operator=(const SettingsSyncProcessor&) = delete; + ~SettingsSyncProcessor(); // Initializes this with the initial state of sync. @@ -38,11 +42,11 @@ class SettingsSyncProcessor { // Sends |changes| to sync. absl::optional<syncer::ModelError> SendChanges( - const ValueStoreChangeList& changes); + const value_store::ValueStoreChangeList& changes); // Informs this that |changes| have been receieved from sync. No action will // be taken, but this must be notified for internal bookkeeping. - void NotifyChanges(const ValueStoreChangeList& changes); + void NotifyChanges(const value_store::ValueStoreChangeList& changes); syncer::ModelType type() { return type_; } @@ -62,8 +66,6 @@ class SettingsSyncProcessor { // Keys of the settings that are currently being synced. Used to decide what // kind of action (ADD, UPDATE, REMOVE) to send to sync. std::set<std::string> synced_keys_; - - DISALLOW_COPY_AND_ASSIGN(SettingsSyncProcessor); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc index 6b197617e94..1e7964ddc0b 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc @@ -23,23 +23,26 @@ #include "components/sync/model/sync_error_factory.h" #include "components/sync/test/model/sync_change_processor_wrapper_for_test.h" #include "components/sync/test/model/sync_error_factory_mock.h" +#include "components/value_store/test_value_store_factory.h" +#include "components/value_store/testing_value_store.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/storage/backend_task_runner.h" #include "extensions/browser/api/storage/settings_test_util.h" #include "extensions/browser/api/storage/storage_frontend.h" +#include "extensions/browser/api/storage/value_store_util.h" #include "extensions/browser/event_router.h" #include "extensions/browser/event_router_factory.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/mock_extension_system.h" -#include "extensions/browser/value_store/test_value_store_factory.h" -#include "extensions/browser/value_store/testing_value_store.h" #include "extensions/common/manifest.h" #include "testing/gtest/include/gtest/gtest.h" using base::DictionaryValue; using base::ListValue; using base::Value; +using value_store::ValueStore; + namespace extensions { namespace { @@ -170,7 +173,7 @@ std::unique_ptr<KeyedService> BuildEventRouter( class ExtensionSettingsSyncTest : public testing::Test { public: ExtensionSettingsSyncTest() - : storage_factory_(new TestValueStoreFactory()), + : storage_factory_(new value_store::TestValueStoreFactory()), sync_processor_(new MockSyncChangeProcessor), sync_processor_wrapper_(new syncer::SyncChangeProcessorWrapperForTest( sync_processor_.get())) {} @@ -247,9 +250,25 @@ class ExtensionSettingsSyncTest : public testing::Test { // This class uses it's TestingValueStore in such a way that it always mints // new TestingValueStore instances. - TestingValueStore* GetExisting(const ExtensionId& extension_id) { - return static_cast<TestingValueStore*>( - storage_factory_->GetExisting(extension_id)); + value_store::TestingValueStore* GetExisting(const ExtensionId& extension_id, + syncer::ModelType type) { + base::FilePath value_store_dir; + value_store_util::ModelType model_type; + switch (type) { + case syncer::APP_SETTINGS: + model_type = value_store_util::ModelType::APP; + break; + case syncer::EXTENSION_SETTINGS: + model_type = value_store_util::ModelType::EXTENSION; + break; + default: + NOTREACHED(); + return nullptr; + } + value_store_dir = value_store_util::GetValueStoreDir( + settings_namespace::SYNC, model_type, extension_id); + return static_cast<value_store::TestingValueStore*>( + storage_factory_->GetExisting(value_store_dir)); } template <typename Func> @@ -272,7 +291,7 @@ class ExtensionSettingsSyncTest : public testing::Test { base::ScopedTempDir temp_dir_; std::unique_ptr<TestingProfile> profile_; std::unique_ptr<StorageFrontend> frontend_; - scoped_refptr<TestValueStoreFactory> storage_factory_; + scoped_refptr<value_store::TestValueStoreFactory> storage_factory_; std::unique_ptr<MockSyncChangeProcessor> sync_processor_; std::unique_ptr<syncer::SyncChangeProcessorWrapperForTest> sync_processor_wrapper_; @@ -321,7 +340,7 @@ TEST_F(ExtensionSettingsSyncTest, InSyncDataDoesNotInvokeSync) { base::Value value1("fooValue"); base::ListValue value2; - value2.AppendString("barValue"); + value2.Append("barValue"); ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); @@ -372,7 +391,7 @@ TEST_F(ExtensionSettingsSyncTest, LocalDataWithNoSyncDataIsPushedToSync) { base::Value value1("fooValue"); base::ListValue value2; - value2.AppendString("barValue"); + value2.Append("barValue"); ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); ValueStore* storage2 = AddExtensionAndGetStorage("s2", type); @@ -406,7 +425,7 @@ TEST_F(ExtensionSettingsSyncTest, AnySyncDataOverwritesLocalData) { base::Value value1("fooValue"); base::ListValue value2; - value2.AppendString("barValue"); + value2.Append("barValue"); // Maintain dictionaries mirrored to the expected values of the settings in // each storage area. @@ -451,7 +470,7 @@ TEST_F(ExtensionSettingsSyncTest, ProcessSyncChanges) { base::Value value1("fooValue"); base::ListValue value2; - value2.AppendString("barValue"); + value2.Append("barValue"); // Make storage1 initialised from local data, storage2 initialised from sync. ValueStore* storage1 = AddExtensionAndGetStorage("s1", type); @@ -526,7 +545,7 @@ TEST_F(ExtensionSettingsSyncTest, PushToSync) { base::Value value1("fooValue"); base::ListValue value2; - value2.AppendString("barValue"); + value2.Append("barValue"); // Make storage1/2 initialised from local data, storage3/4 initialised from // sync. @@ -655,7 +674,7 @@ TEST_F(ExtensionSettingsSyncTest, PushToSync) { TEST_F(ExtensionSettingsSyncTest, ExtensionAndAppSettingsSyncSeparately) { base::Value value1("fooValue"); base::ListValue value2; - value2.AppendString("barValue"); + value2.Append("barValue"); // storage1 is an extension, storage2 is an app. ValueStore* storage1 = AddExtensionAndGetStorage( @@ -726,7 +745,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingStartSyncingDisablesSync) { PostOnBackendSequenceAndWait(FROM_HERE, [&, this]() { // Make bad fail for incoming sync changes. - GetExisting("bad")->set_status_code(ValueStore::CORRUPTION); + GetExisting("bad", model_type)->set_status_code(ValueStore::CORRUPTION); { syncer::SyncDataList sync_data; sync_data.push_back( @@ -738,7 +757,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingStartSyncingDisablesSync) { model_type, sync_data, std::move(sync_processor_wrapper_), std::make_unique<syncer::SyncErrorFactoryMock>()); } - GetExisting("bad")->set_status_code(ValueStore::OK); + GetExisting("bad", model_type)->set_status_code(ValueStore::OK); { base::DictionaryValue dict; @@ -820,7 +839,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingStartSyncingDisablesSync) { } // Failing ProcessSyncChanges shouldn't go to the storage. - GetExisting("bad")->set_status_code(ValueStore::CORRUPTION); + GetExisting("bad", model_type)->set_status_code(ValueStore::CORRUPTION); { syncer::SyncChangeList change_list; change_list.push_back(settings_sync_util::CreateUpdate( @@ -831,7 +850,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingStartSyncingDisablesSync) { GetSyncableService(model_type) ->ProcessSyncChanges(FROM_HERE, change_list); } - GetExisting("bad")->set_status_code(ValueStore::OK); + GetExisting("bad", model_type)->set_status_code(ValueStore::OK); { base::DictionaryValue dict; @@ -943,7 +962,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingProcessChangesDisablesSync) { } // Now fail ProcessSyncChanges for bad. - GetExisting("bad")->set_status_code(ValueStore::CORRUPTION); + GetExisting("bad", model_type)->set_status_code(ValueStore::CORRUPTION); { syncer::SyncChangeList change_list; change_list.push_back( @@ -953,7 +972,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingProcessChangesDisablesSync) { GetSyncableService(model_type) ->ProcessSyncChanges(FROM_HERE, change_list); } - GetExisting("bad")->set_status_code(ValueStore::OK); + GetExisting("bad", model_type)->set_status_code(ValueStore::OK); { base::DictionaryValue dict; @@ -1017,7 +1036,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingGetAllSyncDataDoesntStopSync) { // Even though bad will fail to get all sync data, sync data should still // include that from good. - GetExisting("bad")->set_status_code(ValueStore::CORRUPTION); + GetExisting("bad", model_type)->set_status_code(ValueStore::CORRUPTION); { syncer::SyncDataList all_sync_data = GetSyncableService(model_type)->GetAllSyncDataForTesting(model_type); @@ -1025,7 +1044,7 @@ TEST_F(ExtensionSettingsSyncTest, FailingGetAllSyncDataDoesntStopSync) { EXPECT_EQ(syncer::ClientTagHash::FromUnhashed(model_type, "good/foo"), all_sync_data[0].GetClientTagHash()); } - GetExisting("bad")->set_status_code(ValueStore::OK); + GetExisting("bad", model_type)->set_status_code(ValueStore::OK); // Sync shouldn't be disabled for good (nor bad -- but this is unimportant). GetSyncableService(model_type) @@ -1068,13 +1087,13 @@ TEST_F(ExtensionSettingsSyncTest, FailureToReadChangesToPushDisablesSync) { // good will successfully push foo:fooValue to sync, but bad will fail to // get them so won't. - GetExisting("bad")->set_status_code(ValueStore::CORRUPTION); + GetExisting("bad", model_type)->set_status_code(ValueStore::CORRUPTION); GetSyncableService(model_type) ->MergeDataAndStartSyncing( model_type, syncer::SyncDataList(), std::move(sync_processor_wrapper_), std::make_unique<syncer::SyncErrorFactoryMock>()); - GetExisting("bad")->set_status_code(ValueStore::OK); + GetExisting("bad", model_type)->set_status_code(ValueStore::OK); EXPECT_EQ(syncer::SyncChange::ACTION_ADD, sync_processor_->GetOnlyChange("good", "foo")->change_type()); diff --git a/chromium/chrome/browser/extensions/api/storage/storage_session_unittest.cc b/chromium/chrome/browser/extensions/api/storage/storage_session_unittest.cc new file mode 100644 index 00000000000..bbb86d951bb --- /dev/null +++ b/chromium/chrome/browser/extensions/api/storage/storage_session_unittest.cc @@ -0,0 +1,132 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/test/values_test_util.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_service_test_with_install.h" +#include "components/value_store/value_store_factory_impl.h" +#include "extensions/browser/api/storage/storage_api.h" +#include "extensions/browser/api/storage/storage_frontend.h" +#include "extensions/browser/api_test_utils.h" +#include "extensions/browser/event_router.h" +#include "extensions/browser/event_router_factory.h" +#include "extensions/browser/test_extension_registry_observer.h" +#include "extensions/test/test_extension_dir.h" + +namespace extensions { + +namespace { + +std::unique_ptr<KeyedService> CreateStorageFrontendForTesting( + content::BrowserContext* context) { + auto factory = base::MakeRefCounted<value_store::ValueStoreFactoryImpl>( + context->GetPath()); + return StorageFrontend::CreateForTesting(factory, context); +} + +std::unique_ptr<KeyedService> BuildEventRouter( + content::BrowserContext* profile) { + return std::make_unique<extensions::EventRouter>(profile, nullptr); +} + +} // namespace + +class SessionStorageApiUnittest : public ExtensionServiceTestWithInstall { + public: + SessionStorageApiUnittest() = default; + ~SessionStorageApiUnittest() override = default; + SessionStorageApiUnittest(const SessionStorageApiUnittest& other) = delete; + SessionStorageApiUnittest& operator=(SessionStorageApiUnittest& other) = + delete; + + protected: + // A wrapper around api_test_utils::RunFunction that runs the given function + // and args with the associated profile for the session storage. + void RunFunction(scoped_refptr<ExtensionFunction> function, + const std::string& args, + scoped_refptr<const Extension> extension); + + // Returns the session storage of the given extension with the associated + // profile. + std::unique_ptr<base::Value> GetStorage( + scoped_refptr<const Extension> extension); + + // ExtensionServiceTestBase: + void SetUp() override; + void TearDown() override; + + private: + void SetFunctionProperties(scoped_refptr<ExtensionFunction> function, + scoped_refptr<const Extension> extension); +}; + +void SessionStorageApiUnittest::RunFunction( + scoped_refptr<ExtensionFunction> function, + const std::string& args, + scoped_refptr<const Extension> extension) { + SetFunctionProperties(function, extension); + ASSERT_TRUE(api_test_utils::RunFunction( + function.get(), base::StringPrintf("[\"session\", %s]", args.c_str()), + profile())); +} + +std::unique_ptr<base::Value> SessionStorageApiUnittest::GetStorage( + scoped_refptr<const Extension> extension) { + scoped_refptr<ExtensionFunction> function = + base::MakeRefCounted<StorageStorageAreaGetFunction>(); + SetFunctionProperties(function, extension); + return api_test_utils::RunFunctionAndReturnSingleResult( + function.get(), R"(["session", null])", profile()); +} + +void SessionStorageApiUnittest::SetUp() { + ExtensionServiceTestWithInstall::SetUp(); + InitializeEmptyExtensionService(); + + EventRouterFactory::GetInstance()->SetTestingFactory( + browser_context(), base::BindRepeating(&BuildEventRouter)); + + // Ensure a StorageFrontend can be created on demand. The StorageFrontend + // will be owned by the KeyedService system. + StorageFrontend::GetFactoryInstance()->SetTestingFactory( + browser_context(), base::BindRepeating(&CreateStorageFrontendForTesting)); +} + +void SessionStorageApiUnittest::TearDown() { + ExtensionServiceTestWithInstall::TearDown(); +} + +void SessionStorageApiUnittest::SetFunctionProperties( + scoped_refptr<ExtensionFunction> function, + scoped_refptr<const Extension> extension) { + function->set_extension(extension); + function->set_source_context_type(Feature::BLESSED_EXTENSION_CONTEXT); +} + +TEST_F(SessionStorageApiUnittest, + SessionStorageClearedWhenExtensionIsReloaded) { + TestExtensionDir test_dir; + test_dir.WriteManifest(R"({ + "name": "Sample extension", + "manifest_version": 3, + "version": "0.1", + "permissions": ["storage"] + })"); + const Extension* extension = InstallCRX(test_dir.Pack(), INSTALL_NEW); + ExtensionId extension_id = extension->id(); + + // Set a value in the session storage and check it can be retrieved. + RunFunction(base::MakeRefCounted<StorageStorageAreaSetFunction>().get(), + R"({"foo": "bar"})", extension); + EXPECT_THAT(*GetStorage(extension), base::test::IsJson(R"({"foo": "bar"})")); + + // Reload the extension and check the session storage is cleared. + TestExtensionRegistryObserver registry_observer(registry(), extension_id); + service()->ReloadExtension(extension_id); + scoped_refptr<const Extension> reloaded_extension = + registry_observer.WaitForExtensionLoaded(); + EXPECT_THAT(*GetStorage(reloaded_extension), base::test::IsJson(R"({})")); +} + +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc index ce2f024d217..69720a6eaf5 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc +++ b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.cc @@ -15,6 +15,7 @@ #include "components/sync/model/sync_change_processor.h" #include "components/sync/model/sync_error_factory.h" #include "extensions/browser/api/storage/backend_task_runner.h" +#include "extensions/browser/api/storage/value_store_util.h" namespace extensions { @@ -34,22 +35,22 @@ std::unique_ptr<base::DictionaryValue> EmptyDictionaryValue() { return std::make_unique<base::DictionaryValue>(); } -ValueStoreFactory::ModelType ToFactoryModelType(syncer::ModelType sync_type) { +value_store_util::ModelType ToFactoryModelType(syncer::ModelType sync_type) { switch (sync_type) { case syncer::APP_SETTINGS: - return ValueStoreFactory::ModelType::APP; + return value_store_util::ModelType::APP; case syncer::EXTENSION_SETTINGS: - return ValueStoreFactory::ModelType::EXTENSION; + return value_store_util::ModelType::EXTENSION; default: NOTREACHED(); } - return ValueStoreFactory::ModelType::EXTENSION; + return value_store_util::ModelType::EXTENSION; } } // namespace SyncStorageBackend::SyncStorageBackend( - scoped_refptr<ValueStoreFactory> storage_factory, + scoped_refptr<value_store::ValueStoreFactory> storage_factory, const SettingsStorageQuotaEnforcer::Limits& quota, scoped_refptr<SettingsObserverList> observers, syncer::ModelType sync_type, @@ -66,7 +67,8 @@ SyncStorageBackend::SyncStorageBackend( SyncStorageBackend::~SyncStorageBackend() {} -ValueStore* SyncStorageBackend::GetStorage(const std::string& extension_id) { +value_store::ValueStore* SyncStorageBackend::GetStorage( + const std::string& extension_id) { DCHECK(IsOnBackendSequence()); return GetOrCreateStorageWithSyncData(extension_id, EmptyDictionaryValue()); } @@ -83,9 +85,9 @@ SyncableSettingsStorage* SyncStorageBackend::GetOrCreateStorageWithSyncData( std::unique_ptr<SettingsStorageQuotaEnforcer> settings_storage( new SettingsStorageQuotaEnforcer( - quota_, storage_factory_->CreateSettingsStore( + quota_, value_store_util::CreateSettingsStore( settings_namespace::SYNC, ToFactoryModelType(sync_type_), - extension_id))); + extension_id, storage_factory_))); // It's fine to create the quota enforcer underneath the sync layer, since // sync will only go ahead if each underlying storage operation succeeds. @@ -118,24 +120,6 @@ void SyncStorageBackend::DeleteStorage(const std::string& extension_id) { storage_objs_.erase(extension_id); } -std::set<std::string> SyncStorageBackend::GetKnownExtensionIDs( - ValueStoreFactory::ModelType model_type) const { - DCHECK(IsOnBackendSequence()); - std::set<std::string> result; - - // Storage areas can be in-memory as well as on disk. |storage_objs_| will - // contain all that are in-memory. - for (const auto& storage_obj : storage_objs_) { - result.insert(storage_obj.first); - } - - std::set<std::string> disk_ids = storage_factory_->GetKnownExtensionIDs( - settings_namespace::SYNC, model_type); - result.insert(disk_ids.begin(), disk_ids.end()); - - return result; -} - void SyncStorageBackend::WaitUntilReadyToSync(base::OnceClosure done) { DCHECK(IsOnBackendSequence()); // This class is ready to sync immediately upon construction. @@ -148,19 +132,21 @@ syncer::SyncDataList SyncStorageBackend::GetAllSyncDataForTesting( // For all extensions, get all their settings. This has the effect // of bringing in the entire state of extension settings in memory; sad. syncer::SyncDataList all_sync_data; - std::set<std::string> known_extension_ids( - GetKnownExtensionIDs(ToFactoryModelType(type))); - for (auto it = known_extension_ids.cbegin(); it != known_extension_ids.cend(); - ++it) { - ValueStore::ReadResult maybe_settings = - GetOrCreateStorageWithSyncData(*it, EmptyDictionaryValue())->Get(); + // For tests, all storage areas are kept in memory in `storage_objs_`. + for (const auto& storage_obj : storage_objs_) { + std::string extension_id = storage_obj.first; + + value_store::ValueStore::ReadResult maybe_settings = + GetOrCreateStorageWithSyncData(extension_id, EmptyDictionaryValue()) + ->Get(); if (!maybe_settings.status().ok()) { - LOG(WARNING) << "Failed to get settings for " << *it << ": " + LOG(WARNING) << "Failed to get settings for " << extension_id << ": " << maybe_settings.status().message; continue; } - AddAllSyncData(*it, maybe_settings.settings(), type, &all_sync_data); + AddAllSyncData(extension_id, maybe_settings.settings(), type, + &all_sync_data); } return all_sync_data; diff --git a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h index 236b44e3a2c..32777d43788 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h +++ b/chromium/chrome/browser/extensions/api/storage/sync_storage_backend.h @@ -14,19 +14,22 @@ #include "base/macros.h" #include "base/memory/ref_counted.h" #include "components/sync/model/syncable_service.h" +#include "components/value_store/value_store_factory.h" #include "extensions/browser/api/storage/settings_observer.h" #include "extensions/browser/api/storage/settings_storage_quota_enforcer.h" -#include "extensions/browser/value_store/value_store_factory.h" namespace syncer { class SyncErrorFactory; } +namespace value_store { +class ValueStoreFactory; +} + namespace extensions { class SettingsSyncProcessor; class SyncableSettingsStorage; -class ValueStoreFactory; // Manages ValueStore objects for extensions, including routing // changes from sync to them. @@ -35,15 +38,19 @@ class SyncStorageBackend : public syncer::SyncableService { public: // |storage_factory| is use to create leveldb storage areas. // |observers| is the list of observers to settings changes. - SyncStorageBackend(scoped_refptr<ValueStoreFactory> storage_factory, - const SettingsStorageQuotaEnforcer::Limits& quota, - scoped_refptr<SettingsObserverList> observers, - syncer::ModelType sync_type, - const syncer::SyncableService::StartSyncFlare& flare); + SyncStorageBackend( + scoped_refptr<value_store::ValueStoreFactory> storage_factory, + const SettingsStorageQuotaEnforcer::Limits& quota, + scoped_refptr<SettingsObserverList> observers, + syncer::ModelType sync_type, + const syncer::SyncableService::StartSyncFlare& flare); + + SyncStorageBackend(const SyncStorageBackend&) = delete; + SyncStorageBackend& operator=(const SyncStorageBackend&) = delete; ~SyncStorageBackend() override; - virtual ValueStore* GetStorage(const std::string& extension_id); + virtual value_store::ValueStore* GetStorage(const std::string& extension_id); virtual void DeleteStorage(const std::string& extension_id); // syncer::SyncableService implementation. @@ -66,17 +73,12 @@ class SyncStorageBackend : public syncer::SyncableService { const std::string& extension_id, std::unique_ptr<base::DictionaryValue> sync_data) const; - // Gets all extension IDs known to extension settings. This may not be all - // installed extensions. - std::set<std::string> GetKnownExtensionIDs( - ValueStoreFactory::ModelType model_type) const; - // Creates a new SettingsSyncProcessor for an extension. std::unique_ptr<SettingsSyncProcessor> CreateSettingsSyncProcessor( const std::string& extension_id) const; // The Factory to use for creating new ValueStores. - const scoped_refptr<ValueStoreFactory> storage_factory_; + const scoped_refptr<value_store::ValueStoreFactory> storage_factory_; // Quota limits (see SettingsStorageQuotaEnforcer). const SettingsStorageQuotaEnforcer::Limits quota_; @@ -100,8 +102,6 @@ class SyncStorageBackend : public syncer::SyncableService { std::unique_ptr<syncer::SyncErrorFactory> sync_error_factory_; syncer::SyncableService::StartSyncFlare flare_; - - DISALLOW_COPY_AND_ASSIGN(SyncStorageBackend); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc index 14b78e34792..6f2bf3bc4af 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc +++ b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.cc @@ -11,9 +11,9 @@ #include "base/bind.h" #include "chrome/browser/extensions/api/storage/sync_storage_backend.h" #include "chrome/browser/sync/glue/sync_start_util.h" +#include "components/value_store/value_store_factory.h" #include "content/public/browser/browser_thread.h" #include "extensions/browser/api/storage/backend_task_runner.h" -#include "extensions/browser/value_store/value_store_factory.h" #include "extensions/common/api/storage.h" #include "extensions/common/extension.h" @@ -36,7 +36,7 @@ SettingsStorageQuotaEnforcer::Limits GetSyncQuotaLimits() { } // namespace SyncValueStoreCache::SyncValueStoreCache( - scoped_refptr<ValueStoreFactory> factory, + scoped_refptr<value_store::ValueStoreFactory> factory, scoped_refptr<SettingsObserverList> observers, const base::FilePath& profile_path) : initialized_(false) { @@ -92,7 +92,7 @@ void SyncValueStoreCache::DeleteStorageSoon(const std::string& extension_id) { } void SyncValueStoreCache::InitOnBackend( - scoped_refptr<ValueStoreFactory> factory, + scoped_refptr<value_store::ValueStoreFactory> factory, scoped_refptr<SettingsObserverList> observers, const base::FilePath& profile_path) { DCHECK(IsOnBackendSequence()); diff --git a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h index 4c75a677c1b..c466f61eefc 100644 --- a/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h +++ b/chromium/chrome/browser/extensions/api/storage/sync_value_store_cache.h @@ -24,18 +24,25 @@ namespace syncer { class SyncableService; } +namespace value_store { +class ValueStoreFactory; +} + namespace extensions { class SyncStorageBackend; -class ValueStoreFactory; // ValueStoreCache for the SYNC namespace. It owns a backend for apps and // another for extensions. Each backend takes care of persistence and syncing. class SyncValueStoreCache : public ValueStoreCache { public: - SyncValueStoreCache(scoped_refptr<ValueStoreFactory> factory, + SyncValueStoreCache(scoped_refptr<value_store::ValueStoreFactory> factory, scoped_refptr<SettingsObserverList> observers, const base::FilePath& profile_path); + + SyncValueStoreCache(const SyncValueStoreCache&) = delete; + SyncValueStoreCache& operator=(const SyncValueStoreCache&) = delete; + ~SyncValueStoreCache() override; base::WeakPtr<SyncValueStoreCache> AsWeakPtr(); @@ -48,7 +55,7 @@ class SyncValueStoreCache : public ValueStoreCache { void DeleteStorageSoon(const std::string& extension_id) override; private: - void InitOnBackend(scoped_refptr<ValueStoreFactory> factory, + void InitOnBackend(scoped_refptr<value_store::ValueStoreFactory> factory, scoped_refptr<SettingsObserverList> observers, const base::FilePath& profile_path); @@ -56,8 +63,6 @@ class SyncValueStoreCache : public ValueStoreCache { std::unique_ptr<SyncStorageBackend> app_backend_; std::unique_ptr<SyncStorageBackend> extension_backend_; base::WeakPtrFactory<SyncValueStoreCache> weak_ptr_factory_{this}; - - DISALLOW_COPY_AND_ASSIGN(SyncValueStoreCache); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc index afd057080b5..04ff86ed295 100644 --- a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc +++ b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc @@ -17,6 +17,8 @@ #include "extensions/browser/api/storage/backend_task_runner.h" #include "extensions/browser/api/storage/storage_area_namespace.h" +using value_store::ValueStore; + namespace extensions { SyncableSettingsStorage::SyncableSettingsStorage( @@ -187,13 +189,14 @@ SyncableSettingsStorage::SendLocalSettingsToSync( return absl::nullopt; // Transform the current settings into a list of sync changes. - ValueStoreChangeList changes; + value_store::ValueStoreChangeList changes; while (!local_state->DictEmpty()) { // It's not possible to iterate over a DictionaryValue and modify it at the // same time, so hack around that restriction. std::string key = base::DictionaryValue::Iterator(*local_state).key(); absl::optional<base::Value> value = local_state->ExtractKey(key); - changes.push_back(ValueStoreChange(key, absl::nullopt, std::move(*value))); + changes.push_back( + value_store::ValueStoreChange(key, absl::nullopt, std::move(*value))); } absl::optional<syncer::ModelError> error = @@ -265,7 +268,7 @@ absl::optional<syncer::ModelError> SyncableSettingsStorage::ProcessSyncChanges( } std::vector<syncer::SyncError> errors; - ValueStoreChangeList changes; + value_store::ValueStoreChangeList changes; for (const std::unique_ptr<SettingSyncData>& sync_change : *sync_changes) { DCHECK_EQ(extension_id_, sync_change->extension_id()); @@ -339,9 +342,10 @@ absl::optional<syncer::ModelError> SyncableSettingsStorage::ProcessSyncChanges( sync_processor_->NotifyChanges(changes); - observers_->Notify(FROM_HERE, &SettingsObserver::OnSettingsChanged, - extension_id_, StorageAreaNamespace::kSync, - ValueStoreChange::ToValue(std::move(changes))); + observers_->Notify( + FROM_HERE, &SettingsObserver::OnSettingsChanged, extension_id_, + StorageAreaNamespace::kSync, + value_store::ValueStoreChange::ToValue(std::move(changes))); // TODO(kalman): Something sensible with multiple errors. if (errors.empty()) @@ -352,7 +356,7 @@ absl::optional<syncer::ModelError> SyncableSettingsStorage::ProcessSyncChanges( syncer::SyncError SyncableSettingsStorage::OnSyncAdd( const std::string& key, std::unique_ptr<base::Value> new_value, - ValueStoreChangeList* changes) { + value_store::ValueStoreChangeList* changes) { DCHECK(new_value); WriteResult result = HandleResult(delegate_->Set(IGNORE_QUOTA, key, *new_value)); @@ -364,7 +368,7 @@ syncer::SyncError SyncableSettingsStorage::OnSyncAdd( sync_processor_->type()); } changes->push_back( - ValueStoreChange(key, absl::nullopt, std::move(*new_value))); + value_store::ValueStoreChange(key, absl::nullopt, std::move(*new_value))); return syncer::SyncError(); } @@ -372,7 +376,7 @@ syncer::SyncError SyncableSettingsStorage::OnSyncUpdate( const std::string& key, std::unique_ptr<base::Value> old_value, std::unique_ptr<base::Value> new_value, - ValueStoreChangeList* changes) { + value_store::ValueStoreChangeList* changes) { DCHECK(old_value); DCHECK(new_value); WriteResult result = @@ -384,15 +388,15 @@ syncer::SyncError SyncableSettingsStorage::OnSyncUpdate( result.status().message.c_str()), sync_processor_->type()); } - changes->push_back( - ValueStoreChange(key, std::move(*old_value), std::move(*new_value))); + changes->push_back(value_store::ValueStoreChange(key, std::move(*old_value), + std::move(*new_value))); return syncer::SyncError(); } syncer::SyncError SyncableSettingsStorage::OnSyncDelete( const std::string& key, std::unique_ptr<base::Value> old_value, - ValueStoreChangeList* changes) { + value_store::ValueStoreChangeList* changes) { DCHECK(old_value); WriteResult result = HandleResult(delegate_->Remove(key)); if (!result.status().ok()) { @@ -403,7 +407,7 @@ syncer::SyncError SyncableSettingsStorage::OnSyncDelete( sync_processor_->type()); } changes->push_back( - ValueStoreChange(key, std::move(*old_value), absl::nullopt)); + value_store::ValueStoreChange(key, std::move(*old_value), absl::nullopt)); return syncer::SyncError(); } diff --git a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h index 5914c836e38..3578c5402f3 100644 --- a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h +++ b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.h @@ -18,8 +18,8 @@ #include "chrome/browser/extensions/api/storage/setting_sync_data.h" #include "components/sync/model/sync_change.h" #include "components/sync/model/syncable_service.h" +#include "components/value_store/value_store.h" #include "extensions/browser/api/storage/settings_observer.h" -#include "extensions/browser/value_store/value_store.h" namespace syncer { class SyncError; @@ -31,15 +31,18 @@ namespace extensions { class SettingsSyncProcessor; // Decorates a ValueStore with sync behaviour. -class SyncableSettingsStorage : public ValueStore { +class SyncableSettingsStorage : public value_store::ValueStore { public: SyncableSettingsStorage(scoped_refptr<SettingsObserverList> observers, const std::string& extension_id, // Ownership taken. - ValueStore* delegate, + value_store::ValueStore* delegate, syncer::ModelType sync_type, const syncer::SyncableService::StartSyncFlare& flare); + SyncableSettingsStorage(const SyncableSettingsStorage&) = delete; + SyncableSettingsStorage& operator=(const SyncableSettingsStorage&) = delete; + ~SyncableSettingsStorage() override; // ValueStore implementation. @@ -82,7 +85,7 @@ class SyncableSettingsStorage : public ValueStore { private: // Sends the changes from |result| to sync if it's enabled. - void SyncResultIfEnabled(const ValueStore::WriteResult& result); + void SyncResultIfEnabled(const value_store::ValueStore::WriteResult& result); // Analyze the result returned by a call to the delegate, and take appropriate // measures. @@ -104,14 +107,14 @@ class SyncableSettingsStorage : public ValueStore { // Called when an Add/Update/Remove comes from sync. syncer::SyncError OnSyncAdd(const std::string& key, std::unique_ptr<base::Value> new_value, - ValueStoreChangeList* changes); + value_store::ValueStoreChangeList* changes); syncer::SyncError OnSyncUpdate(const std::string& key, std::unique_ptr<base::Value> old_value, std::unique_ptr<base::Value> new_value, - ValueStoreChangeList* changes); + value_store::ValueStoreChangeList* changes); syncer::SyncError OnSyncDelete(const std::string& key, std::unique_ptr<base::Value> old_value, - ValueStoreChangeList* changes); + value_store::ValueStoreChangeList* changes); // List of observers to settings changes. const scoped_refptr<SettingsObserverList> observers_; @@ -120,15 +123,13 @@ class SyncableSettingsStorage : public ValueStore { std::string const extension_id_; // Storage area to sync. - const std::unique_ptr<ValueStore> delegate_; + const std::unique_ptr<value_store::ValueStore> delegate_; // Object which sends changes to sync. std::unique_ptr<SettingsSyncProcessor> sync_processor_; const syncer::ModelType sync_type_; const syncer::SyncableService::StartSyncFlare flare_; - - DISALLOW_COPY_AND_ASSIGN(SyncableSettingsStorage); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc b/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc index c788b7dbcf5..e673eda29ef 100644 --- a/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc +++ b/chromium/chrome/browser/extensions/api/system_display/system_display_chromeos_apitest.cc @@ -16,16 +16,16 @@ class SystemDisplayChromeOSApiTest : public extensions::ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - SystemDisplayChromeOSApiTest() = default; + SystemDisplayChromeOSApiTest() : ExtensionApiTest(GetParam()) {} ~SystemDisplayChromeOSApiTest() override = default; + SystemDisplayChromeOSApiTest(const SystemDisplayChromeOSApiTest&) = delete; + SystemDisplayChromeOSApiTest& operator=(const SystemDisplayChromeOSApiTest&) = + delete; void SetUpDefaultCommandLine(base::CommandLine* command_line) override { command_line->AppendSwitch(ash::switches::kAshEnableTabletMode); extensions::ExtensionApiTest::SetUpDefaultCommandLine(command_line); } - - private: - DISALLOW_COPY_AND_ASSIGN(SystemDisplayChromeOSApiTest); }; INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -39,9 +39,8 @@ IN_PROC_BROWSER_TEST_P(SystemDisplayChromeOSApiTest, CheckOnDisplayChangedEvent) { ExtensionTestMessageListener listener_for_extension_ready( "ready", /*will_reply=*/false); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("system_display_chromeos"), - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker})); + ASSERT_TRUE( + LoadExtension(test_data_dir_.AppendASCII("system_display_chromeos"))); ASSERT_TRUE(listener_for_extension_ready.WaitUntilSatisfied()); // Give the mojo CrosDisplayConfig.AddObserver() call a chance to go through. base::RunLoop().RunUntilIdle(); diff --git a/chromium/chrome/browser/extensions/api/system_display/system_display_extension_apitest.cc b/chromium/chrome/browser/extensions/api/system_display/system_display_extension_apitest.cc index 04c9ed91f39..2690d52b5c9 100644 --- a/chromium/chrome/browser/extensions/api/system_display/system_display_extension_apitest.cc +++ b/chromium/chrome/browser/extensions/api/system_display/system_display_extension_apitest.cc @@ -32,7 +32,7 @@ class SystemDisplayExtensionApiTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - SystemDisplayExtensionApiTest() = default; + SystemDisplayExtensionApiTest() : ExtensionApiTest(GetParam()) {} ~SystemDisplayExtensionApiTest() override = default; SystemDisplayExtensionApiTest(const SystemDisplayExtensionApiTest&) = delete; SystemDisplayExtensionApiTest& operator=( @@ -71,10 +71,7 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, ::testing::Values(ContextType::kServiceWorker)); IN_PROC_BROWSER_TEST_P(SystemDisplayExtensionApiTest, GetDisplayInfo) { - ASSERT_TRUE(RunExtensionTest( - "system_display/info", {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker})) - << message_; + ASSERT_TRUE(RunExtensionTest("system_display/info")) << message_; } #endif // defined(OS_WIN) diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc index 4947eede0b4..e75425bddbb 100644 --- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc +++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.cc @@ -27,10 +27,10 @@ ExtensionFunction::ResponseAction SystemIndicatorSetIconFunction::Run() { EXTENSION_FUNCTION_VALIDATE(extension()); EXTENSION_FUNCTION_VALIDATE(HasSystemIndicator(*extension())); - EXTENSION_FUNCTION_VALIDATE(args_->GetList().size() == 1); - EXTENSION_FUNCTION_VALIDATE(args_->GetList()[0].is_dict()); + EXTENSION_FUNCTION_VALIDATE(args().size() == 1); + EXTENSION_FUNCTION_VALIDATE(args()[0].is_dict()); - const base::Value& set_icon_details = args_->GetList()[0]; + const base::Value& set_icon_details = args()[0]; // NOTE: For historical reasons, this code is primarily taken from // ExtensionActionSetIconFunction. diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_apitest.cc b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_apitest.cc index f8548684e89..29bdb26bfc7 100644 --- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_apitest.cc +++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_apitest.cc @@ -7,16 +7,17 @@ #include "chrome/browser/extensions/api/system_indicator/system_indicator_manager.h" #include "chrome/browser/extensions/api/system_indicator/system_indicator_manager_factory.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/lazy_background_page_test_util.h" #include "chrome/browser/ui/browser.h" #include "components/version_info/channel.h" #include "content/public/test/browser_test.h" #include "extensions/browser/extension_action.h" #include "extensions/browser/extension_action_manager.h" +#include "extensions/browser/extension_host_test_helper.h" #include "extensions/browser/process_manager.h" #include "extensions/common/extension.h" #include "extensions/common/features/feature_channel.h" #include "extensions/common/manifest_test.h" +#include "extensions/common/mojom/view_type.mojom.h" #include "extensions/test/result_catcher.h" namespace extensions { @@ -24,6 +25,10 @@ namespace extensions { class SystemIndicatorApiTest : public ExtensionApiTest { public: SystemIndicatorApiTest() : scoped_channel_(version_info::Channel::DEV) {} + + SystemIndicatorApiTest(const SystemIndicatorApiTest&) = delete; + SystemIndicatorApiTest& operator=(const SystemIndicatorApiTest&) = delete; + ~SystemIndicatorApiTest() override = default; void SetUpOnMainThread() override { @@ -35,18 +40,20 @@ class SystemIndicatorApiTest : public ExtensionApiTest { } const Extension* LoadExtensionAndWait(const std::string& test_name) { - LazyBackgroundObserver page_complete; + ExtensionHostTestHelper host_helper(profile()); + host_helper.RestrictToType(mojom::ViewType::kExtensionBackgroundPage); base::FilePath extdir = test_data_dir_.AppendASCII(test_name); const Extension* extension = LoadExtension(extdir); - if (extension) - page_complete.Wait(); + if (extension) { + // Wait for the background page to cycle. + host_helper.WaitForDocumentElementAvailable(); + host_helper.WaitForHostDestroyed(); + } return extension; } private: ScopedCurrentChannel scoped_channel_; - - DISALLOW_COPY_AND_ASSIGN(SystemIndicatorApiTest); }; // https://crbug.com/960363: Test crashes on ChromeOS. diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc index d27dc73cdf4..efafbe48376 100644 --- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc +++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.cc @@ -38,6 +38,10 @@ class ExtensionIndicatorIcon : public StatusIconObserver, const ExtensionIconSet& icon_set, Profile* profile, StatusTray* status_tray); + + ExtensionIndicatorIcon(const ExtensionIndicatorIcon&) = delete; + ExtensionIndicatorIcon& operator=(const ExtensionIndicatorIcon&) = delete; + ~ExtensionIndicatorIcon() override; // Sets the dynamic icon for the indicator. @@ -61,8 +65,6 @@ class ExtensionIndicatorIcon : public StatusIconObserver, Profile* profile_; IconImage manifest_icon_; gfx::Image dynamic_icon_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionIndicatorIcon); }; std::unique_ptr<ExtensionIndicatorIcon> ExtensionIndicatorIcon::Create( diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.h b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.h index 7a8472ea05c..1e2f514c640 100644 --- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.h +++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_manager.h @@ -34,6 +34,10 @@ class SystemIndicatorManager : public ExtensionRegistryObserver, public KeyedService { public: SystemIndicatorManager(Profile* profile, StatusTray* status_tray); + + SystemIndicatorManager(const SystemIndicatorManager&) = delete; + SystemIndicatorManager& operator=(const SystemIndicatorManager&) = delete; + ~SystemIndicatorManager() override; // Sets the icon of the system indicator for the given |extension| to @@ -53,6 +57,10 @@ class SystemIndicatorManager : public ExtensionRegistryObserver, // A structure representing the system indicator for an extension. struct SystemIndicator { SystemIndicator(); + + SystemIndicator(const SystemIndicator&) = delete; + SystemIndicator& operator=(const SystemIndicator&) = delete; + ~SystemIndicator(); // A dynamically-set icon (through systemIndicator.setIcon()). Takes @@ -63,8 +71,6 @@ class SystemIndicatorManager : public ExtensionRegistryObserver, // The system tray indicator. This is only non-null if the system indicator // is enabled. std::unique_ptr<ExtensionIndicatorIcon> system_tray_indicator; - - DISALLOW_COPY_AND_ASSIGN(SystemIndicator); }; // ExtensionRegistryObserver: @@ -87,8 +93,6 @@ class SystemIndicatorManager : public ExtensionRegistryObserver, base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(SystemIndicatorManager); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/system_private/OWNERS b/chromium/chrome/browser/extensions/api/system_private/OWNERS deleted file mode 100644 index c32e0598455..00000000000 --- a/chromium/chrome/browser/extensions/api/system_private/OWNERS +++ /dev/null @@ -1 +0,0 @@ -dmazzoni@chromium.org diff --git a/chromium/chrome/browser/extensions/api/system_private/system_private_apitest.cc b/chromium/chrome/browser/extensions/api/system_private/system_private_apitest.cc index 950b8ce62ee..6e14d2cbab7 100644 --- a/chromium/chrome/browser/extensions/api/system_private/system_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/system_private/system_private_apitest.cc @@ -36,6 +36,9 @@ class GetUpdateStatusApiTest : public ExtensionApiTest { public: GetUpdateStatusApiTest() : fake_update_engine_client_(NULL) {} + GetUpdateStatusApiTest(const GetUpdateStatusApiTest&) = delete; + GetUpdateStatusApiTest& operator=(const GetUpdateStatusApiTest&) = delete; + void SetUpInProcessBrowserTestFixture() override { ExtensionApiTest::SetUpInProcessBrowserTestFixture(); fake_update_engine_client_ = new chromeos::FakeUpdateEngineClient; @@ -49,9 +52,6 @@ class GetUpdateStatusApiTest : public ExtensionApiTest { protected: chromeos::FakeUpdateEngineClient* fake_update_engine_client_; - - private: - DISALLOW_COPY_AND_ASSIGN(GetUpdateStatusApiTest); }; IN_PROC_BROWSER_TEST_F(GetUpdateStatusApiTest, Progress) { diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc index 7b27626d07a..33af0b4b5cc 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.cc @@ -138,7 +138,7 @@ Browser* GetLastActiveBrowser(const Profile* profile, ExtensionFunction::ResponseAction TabCaptureCaptureFunction::Run() { std::unique_ptr<api::tab_capture::Capture::Params> params = - TabCapture::Capture::Params::Create(*args_); + TabCapture::Capture::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params); Profile* profile = Profile::FromBrowserContext(browser_context()); @@ -223,7 +223,7 @@ ExtensionFunction::ResponseAction TabCaptureGetCapturedTabsFunction::Run() { ExtensionFunction::ResponseAction TabCaptureGetMediaStreamIdFunction::Run() { std::unique_ptr<api::tab_capture::GetMediaStreamId::Params> params = - TabCapture::GetMediaStreamId::Params::Create(*args_); + TabCapture::GetMediaStreamId::Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params); content::WebContents* target_contents = nullptr; diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc index 94bb67ce38d..f9eb29d8b3a 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_apitest.cc @@ -23,6 +23,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model_observer.h" #include "chrome/browser/ui/tabs/tab_utils.h" #include "chrome/common/chrome_switches.h" +#include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/common/content_features.h" @@ -84,13 +85,18 @@ class TabCaptureApiPixelTest : public TabCaptureApiTest { // Tests API behaviors, including info queries, and constraints violations. IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ApiTests) { AddExtensionToCommandLineAllowlist(); - ASSERT_TRUE(RunExtensionTest("tab_capture", {.page_url = "api_tests.html"})) + ASSERT_TRUE( + RunExtensionTest("tab_capture/api_tests", {.page_url = "api_tests.html"})) << message_; } // Tests that tab capture video frames can be received in a VIDEO element. // Disabled due to flakes on multiple platforms; see https://crbug.com/1040894. -IN_PROC_BROWSER_TEST_F(TabCaptureApiPixelTest, EndToEndWithoutRemoting) { +// Disabled due to flakes on Windows GPU bots during teardown, and because +// IsTooIntensiveForThisPlatform prevents this test from actually executing +// anyways; see crbug.com/1241790. +IN_PROC_BROWSER_TEST_F(TabCaptureApiPixelTest, + DISABLED_EndToEndWithoutRemoting) { if (IsTooIntensiveForThisPlatform()) { LOG(WARNING) << "Skipping this CPU-intensive test on this platform/build."; return; @@ -102,7 +108,7 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiPixelTest, EndToEndWithoutRemoting) { // and color values can be off by a lot. That said, color accuracy is being // tested by a suite of content_browsertests. ASSERT_TRUE(RunExtensionTest( - "tab_capture", + "tab_capture/end_to_end", {.page_url = "end_to_end.html?method=local&colorDeviation=50"})) << message_; } @@ -121,7 +127,7 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiPixelTest, DISABLED_EndToEndThroughWebRTC) { // See note in EndToEndWithoutRemoting test about why |colorDeviation| is // being set so high. ASSERT_TRUE(RunExtensionTest( - "tab_capture", + "tab_capture/end_to_end", {.page_url = "end_to_end.html?method=webrtc&colorDeviation=50"})) << message_; } @@ -130,8 +136,8 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiPixelTest, DISABLED_EndToEndThroughWebRTC) { IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, GetUserMediaTest) { ExtensionTestMessageListener listener("ready", true); - ASSERT_TRUE( - RunExtensionTest("tab_capture", {.page_url = "get_user_media_test.html"})) + ASSERT_TRUE(RunExtensionTest("tab_capture/get_user_media_test", + {.page_url = "get_user_media_test.html"})) << message_; EXPECT_TRUE(listener.WaitUntilSatisfied()); @@ -160,7 +166,7 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, ActiveTabPermission) { ExtensionTestMessageListener before_open_new_tab("ready3", true); ExtensionTestMessageListener before_allowlist_extension("ready4", true); - ASSERT_TRUE(RunExtensionTest("tab_capture", + ASSERT_TRUE(RunExtensionTest("tab_capture/active_tab_permission_test", {.page_url = "active_tab_permission_test.html"})) << message_; @@ -207,8 +213,8 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, FullscreenEvents) { ExtensionTestMessageListener capture_started("tab_capture_started", false); ExtensionTestMessageListener entered_fullscreen("entered_fullscreen", false); - ASSERT_TRUE( - RunExtensionTest("tab_capture", {.page_url = "fullscreen_test.html"})) + ASSERT_TRUE(RunExtensionTest("tab_capture/fullscreen_test", + {.page_url = "fullscreen_test.html"})) << message_; EXPECT_TRUE(capture_started.WaitUntilSatisfied()); @@ -226,25 +232,20 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, FullscreenEvents) { EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } -// Make sure tabCapture API can be granted for Chrome:// pages. -// Disabled due to flakes on macOS; see https://crbug.com/1134562. -#if defined(OS_MAC) -#define MAYBE_GrantForChromePages DISABLED_GrantForChromePages -#else -#define MAYBE_GrantForChromePages GrantForChromePages -#endif -IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GrantForChromePages) { +IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, GrantForChromePages) { ExtensionTestMessageListener before_open_tab("ready1", true); - ASSERT_TRUE(RunExtensionTest("tab_capture", + ASSERT_TRUE(RunExtensionTest("tab_capture/active_tab_chrome_pages", {.page_url = "active_tab_chrome_pages.html"})) << message_; EXPECT_TRUE(before_open_tab.WaitUntilSatisfied()); // Open a tab on a chrome:// page and make sure we can capture. - content::OpenURLParams params(GURL(kValidChromeURL), content::Referrer(), - WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui::PAGE_TRANSITION_LINK, false); - content::WebContents* web_contents = browser()->OpenURL(params); + ui_test_utils::NavigateToURLWithDisposition( + browser(), GURL(kValidChromeURL), + WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); const Extension* extension = ExtensionRegistry::Get( web_contents->GetBrowserContext())->enabled_extensions().GetByID( kExtensionId); @@ -261,7 +262,7 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_GrantForChromePages) { IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, CaptureInSplitIncognitoMode) { AddExtensionToCommandLineAllowlist(); ASSERT_TRUE(RunExtensionTest( - "tab_capture", + "tab_capture/start_tab_capture", {.page_url = "start_tab_capture.html", .open_in_incognito = true}, {.allow_in_incognito = true})) << message_; @@ -271,7 +272,8 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, CaptureInSplitIncognitoMode) { // do not. IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, Constraints) { AddExtensionToCommandLineAllowlist(); - ASSERT_TRUE(RunExtensionTest("tab_capture", {.page_url = "constraints.html"})) + ASSERT_TRUE(RunExtensionTest("tab_capture/constraints", + {.page_url = "constraints.html"})) << message_; } @@ -313,8 +315,8 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, TabIndicator) { // Run an extension test that just turns on tab capture, which should cause // the indicator to turn on. AddExtensionToCommandLineAllowlist(); - ASSERT_TRUE( - RunExtensionTest("tab_capture", {.page_url = "start_tab_capture.html"})) + ASSERT_TRUE(RunExtensionTest("tab_capture/start_tab_capture", + {.page_url = "start_tab_capture.html"})) << message_; // Run the browser until the indicator turns on. diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.cc index d3be887025e..b06a4be3eec 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.cc @@ -109,9 +109,9 @@ void TabCapturePerformanceTestBase::NavigateToTestPage( const std::string& test_page_html_content) { LOG(INFO) << "Navigating to test page..."; test_page_to_serve_ = test_page_html_content; - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), - embedded_test_server()->GetURL(kTestWebPageHostname, kTestWebPagePath)); + embedded_test_server()->GetURL(kTestWebPageHostname, kTestWebPagePath))); } base::Value TabCapturePerformanceTestBase::SendMessageToExtension( diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.h b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.h index 47f2e10f696..e7fc090b509 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.h +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performance_test_base.h @@ -41,6 +41,11 @@ class HttpResponse; class TabCapturePerformanceTestBase : public InProcessBrowserTest { public: TabCapturePerformanceTestBase(); + + TabCapturePerformanceTestBase(const TabCapturePerformanceTestBase&) = delete; + TabCapturePerformanceTestBase& operator=( + const TabCapturePerformanceTestBase&) = delete; + ~TabCapturePerformanceTestBase() override; // SetUp overrides to enable pixel output, configure the embedded test server, @@ -106,14 +111,14 @@ class TabCapturePerformanceTestBase : public InProcessBrowserTest { // These are how long the browser is run with trace event recording taking // place. static constexpr base::TimeDelta kFullRunObservationPeriod = - base::TimeDelta::FromSeconds(15); + base::Seconds(15); static constexpr base::TimeDelta kQuickRunObservationPeriod = - base::TimeDelta::FromSeconds(4); + base::Seconds(4); // If sending a message to the extension fails, because the extension has not // started its message listener yet, how long before the next retry? static constexpr base::TimeDelta kSendMessageRetryPeriod = - base::TimeDelta::FromMilliseconds(250); + base::Milliseconds(250); // Note: The hostname must match the pattern found in the Extension's manifest // file, or it will not be able to send/receive messaging from the test web @@ -150,8 +155,6 @@ class TabCapturePerformanceTestBase : public InProcessBrowserTest { // Manages the Audio Service feature set, enabled for these performance tests. base::test::ScopedFeatureList feature_list_; - - DISALLOW_COPY_AND_ASSIGN(TabCapturePerformanceTestBase); }; #endif // CHROME_BROWSER_EXTENSIONS_API_TAB_CAPTURE_TAB_CAPTURE_PERFORMANCE_TEST_BASE_H_ diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc index d522b493f2b..76d6ebb8a1d 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.cc @@ -54,6 +54,9 @@ class TabCaptureRegistry::LiveRequest : public content::WebContentsObserver { DCHECK(registry_); } + LiveRequest(const LiveRequest&) = delete; + LiveRequest& operator=(const LiveRequest&) = delete; + ~LiveRequest() override {} // Accessors. @@ -115,8 +118,6 @@ class TabCaptureRegistry::LiveRequest : public content::WebContentsObserver { // calls to OnRequestUpdate() will always refer to this request by this ID. int render_process_id_; int render_frame_id_; - - DISALLOW_COPY_AND_ASSIGN(LiveRequest); }; TabCaptureRegistry::TabCaptureRegistry(content::BrowserContext* context) diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h index 4129f5c2d49..0119df8eea5 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_registry.h @@ -36,6 +36,9 @@ class TabCaptureRegistry : public BrowserContextKeyedAPI, public ExtensionRegistryObserver, public MediaCaptureDevicesDispatcher::Observer { public: + TabCaptureRegistry(const TabCaptureRegistry&) = delete; + TabCaptureRegistry& operator=(const TabCaptureRegistry&) = delete; + static TabCaptureRegistry* Get(content::BrowserContext* context); // Used by BrowserContextKeyedAPI. @@ -118,8 +121,6 @@ class TabCaptureRegistry : public BrowserContextKeyedAPI, base::ScopedObservation<ExtensionRegistry, ExtensionRegistryObserver> extension_registry_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(TabCaptureRegistry); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api.cc b/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api.cc index a094128b39a..5c163f920f4 100644 --- a/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api.cc +++ b/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api.cc @@ -69,7 +69,7 @@ bool IndexSupportsGroupMove(TabStripModel* tab_strip, ExtensionFunction::ResponseAction TabGroupsGetFunction::Run() { std::unique_ptr<api::tab_groups::Get::Params> params( - api::tab_groups::Get::Params::Create(*args_)); + api::tab_groups::Get::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int group_id = params->group_id; @@ -90,7 +90,7 @@ ExtensionFunction::ResponseAction TabGroupsGetFunction::Run() { ExtensionFunction::ResponseAction TabGroupsQueryFunction::Run() { std::unique_ptr<api::tab_groups::Query::Params> params( - api::tab_groups::Query::Params::Create(*args_)); + api::tab_groups::Query::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); base::Value result_list(base::Value::Type::LIST); @@ -158,7 +158,7 @@ ExtensionFunction::ResponseAction TabGroupsQueryFunction::Run() { ExtensionFunction::ResponseAction TabGroupsUpdateFunction::Run() { std::unique_ptr<api::tab_groups::Update::Params> params( - api::tab_groups::Update::Params::Create(*args_)); + api::tab_groups::Update::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int group_id = params->group_id; @@ -205,7 +205,7 @@ ExtensionFunction::ResponseAction TabGroupsUpdateFunction::Run() { ExtensionFunction::ResponseAction TabGroupsMoveFunction::Run() { std::unique_ptr<api::tab_groups::Move::Params> params( - api::tab_groups::Move::Params::Create(*args_)); + api::tab_groups::Move::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int group_id = params->group_id; diff --git a/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api_unittest.cc b/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api_unittest.cc index 7693e9463f0..8fea6b35baf 100644 --- a/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/tab_groups/tab_groups_api_unittest.cc @@ -190,7 +190,7 @@ TEST_F(TabGroupsApiUnitTest, TabGroupsQueryTitle) { std::unique_ptr<base::ListValue> groups_list( RunTabGroupsQueryFunction(browser(), extension.get(), kTitleQueryInfo)); ASSERT_TRUE(groups_list); - ASSERT_EQ(1u, groups_list->GetSize()); + ASSERT_EQ(1u, groups_list->GetList().size()); const base::Value& group_info = groups_list->GetList()[0]; ASSERT_EQ(base::Value::Type::DICTIONARY, group_info.type()); @@ -227,7 +227,7 @@ TEST_F(TabGroupsApiUnitTest, TabGroupsQueryColor) { std::unique_ptr<base::ListValue> groups_list( RunTabGroupsQueryFunction(browser(), extension.get(), kColorQueryInfo)); ASSERT_TRUE(groups_list); - ASSERT_EQ(1u, groups_list->GetSize()); + ASSERT_EQ(1u, groups_list->GetList().size()); const base::Value& group_info = groups_list->GetList()[0]; ASSERT_EQ(base::Value::Type::DICTIONARY, group_info.type()); diff --git a/chromium/chrome/browser/extensions/api/tabs/app_base_window.h b/chromium/chrome/browser/extensions/api/tabs/app_base_window.h index 08f4a147f98..45559878587 100644 --- a/chromium/chrome/browser/extensions/api/tabs/app_base_window.h +++ b/chromium/chrome/browser/extensions/api/tabs/app_base_window.h @@ -19,6 +19,10 @@ class NativeAppWindow; class AppBaseWindow : public ui::BaseWindow { public: explicit AppBaseWindow(AppWindow* app_window); + + AppBaseWindow(const AppBaseWindow&) = delete; + AppBaseWindow& operator=(const AppBaseWindow&) = delete; + virtual ~AppBaseWindow(); private: @@ -49,8 +53,6 @@ class AppBaseWindow : public ui::BaseWindow { NativeAppWindow* GetBaseWindow() const; AppWindow* app_window_; - - DISALLOW_COPY_AND_ASSIGN(AppBaseWindow); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h index e2a6b4944bb..85abc749703 100644 --- a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h +++ b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h @@ -24,6 +24,10 @@ class AppWindowController : public WindowController { AppWindowController(AppWindow* window, std::unique_ptr<AppBaseWindow> base_window, Profile* profile); + + AppWindowController(const AppWindowController&) = delete; + AppWindowController& operator=(const AppWindowController&) = delete; + ~AppWindowController() override; // extensions::WindowController: @@ -38,8 +42,6 @@ class AppWindowController : public WindowController { private: AppWindow* app_window_; // Owns us. std::unique_ptr<AppBaseWindow> base_window_; - - DISALLOW_COPY_AND_ASSIGN(AppWindowController); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc index 8328042d4bd..4174567e391 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -59,7 +59,7 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/tabs/tab_utils.h" #include "chrome/browser/ui/window_sizer/window_sizer.h" -#include "chrome/browser/web_applications/components/web_app_helpers.h" +#include "chrome/browser/web_applications/web_app_helpers.h" #include "chrome/common/extensions/api/tabs.h" #include "chrome/common/extensions/api/windows.h" #include "chrome/common/extensions/extension_constants.h" @@ -377,7 +377,7 @@ void ZoomModeToZoomSettings(ZoomController::ZoomMode zoom_mode, ExtensionFunction::ResponseAction WindowsGetFunction::Run() { std::unique_ptr<windows::Get::Params> params( - windows::Get::Params::Create(*args_)); + windows::Get::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::Get::Params> extractor(params.get()); @@ -401,7 +401,7 @@ ExtensionFunction::ResponseAction WindowsGetFunction::Run() { ExtensionFunction::ResponseAction WindowsGetCurrentFunction::Run() { std::unique_ptr<windows::GetCurrent::Params> params( - windows::GetCurrent::Params::Create(*args_)); + windows::GetCurrent::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::GetCurrent::Params> extractor(params.get()); @@ -425,7 +425,7 @@ ExtensionFunction::ResponseAction WindowsGetCurrentFunction::Run() { ExtensionFunction::ResponseAction WindowsGetLastFocusedFunction::Run() { std::unique_ptr<windows::GetLastFocused::Params> params( - windows::GetLastFocused::Params::Create(*args_)); + windows::GetLastFocused::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::GetLastFocused::Params> extractor( @@ -460,7 +460,7 @@ ExtensionFunction::ResponseAction WindowsGetLastFocusedFunction::Run() { ExtensionFunction::ResponseAction WindowsGetAllFunction::Run() { std::unique_ptr<windows::GetAll::Params> params( - windows::GetAll::Params::Create(*args_)); + windows::GetAll::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::GetAll::Params> extractor(params.get()); @@ -493,15 +493,18 @@ bool WindowsCreateFunction::ShouldOpenIncognitoWindow( bool incognito = false; if (create_data && create_data->incognito) { incognito = *create_data->incognito; - if (incognito && incognito_availability == IncognitoModePrefs::DISABLED) { + if (incognito && + incognito_availability == IncognitoModePrefs::Availability::kDisabled) { *error = tabs_constants::kIncognitoModeIsDisabled; return false; } - if (!incognito && incognito_availability == IncognitoModePrefs::FORCED) { + if (!incognito && + incognito_availability == IncognitoModePrefs::Availability::kForced) { *error = tabs_constants::kIncognitoModeIsForced; return false; } - } else if (incognito_availability == IncognitoModePrefs::FORCED) { + } else if (incognito_availability == + IncognitoModePrefs::Availability::kForced) { // If incognito argument is not specified explicitly, we default to // incognito when forced so by policy. incognito = true; @@ -531,7 +534,7 @@ bool WindowsCreateFunction::ShouldOpenIncognitoWindow( ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { std::unique_ptr<windows::Create::Params> params( - windows::Create::Params::Create(*args_)); + windows::Create::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); std::vector<GURL> urls; TabStripModel* source_tab_strip = NULL; @@ -731,7 +734,8 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { // (otherwise that resets the locked mode for devices in tablet mode). if (create_data && create_data->state == windows::WINDOW_STATE_LOCKED_FULLSCREEN) { - tabs_util::SetLockedFullscreenState(new_window, true); + tabs_util::SetLockedFullscreenState( + new_window, chromeos::WindowPinType::kTrustedPinned); } std::unique_ptr<base::Value> result; @@ -753,7 +757,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { std::unique_ptr<windows::Update::Params> params( - windows::Update::Params::Create(*args_)); + windows::Update::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); Browser* browser = nullptr; @@ -831,11 +835,13 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { if (is_locked_fullscreen && params->update_info.state != windows::WINDOW_STATE_LOCKED_FULLSCREEN && params->update_info.state != windows::WINDOW_STATE_NONE) { - tabs_util::SetLockedFullscreenState(browser, false); + tabs_util::SetLockedFullscreenState(browser, + chromeos::WindowPinType::kNone); } else if (!is_locked_fullscreen && params->update_info.state == windows::WINDOW_STATE_LOCKED_FULLSCREEN) { - tabs_util::SetLockedFullscreenState(browser, true); + tabs_util::SetLockedFullscreenState( + browser, chromeos::WindowPinType::kTrustedPinned); } if (show_state != ui::SHOW_STATE_FULLSCREEN && @@ -891,7 +897,7 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { ExtensionFunction::ResponseAction WindowsRemoveFunction::Run() { std::unique_ptr<windows::Remove::Params> params( - windows::Remove::Params::Create(*args_)); + windows::Remove::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); Browser* browser = nullptr; @@ -926,7 +932,7 @@ ExtensionFunction::ResponseAction TabsGetSelectedFunction::Run() { int window_id = extension_misc::kCurrentWindowId; std::unique_ptr<tabs::GetSelected::Params> params( - tabs::GetSelected::Params::Create(*args_)); + tabs::GetSelected::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (params->window_id.get()) window_id = *params->window_id; @@ -950,7 +956,7 @@ ExtensionFunction::ResponseAction TabsGetSelectedFunction::Run() { ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { std::unique_ptr<tabs::GetAllInWindow::Params> params( - tabs::GetAllInWindow::Params::Create(*args_)); + tabs::GetAllInWindow::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); // windowId defaults to "current" window. int window_id = extension_misc::kCurrentWindowId; @@ -969,7 +975,7 @@ ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { ExtensionFunction::ResponseAction TabsQueryFunction::Run() { std::unique_ptr<tabs::Query::Params> params( - tabs::Query::Params::Create(*args_)); + tabs::Query::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); bool loading_status_set = params->query_info.status != tabs::TAB_STATUS_NONE; @@ -1165,7 +1171,7 @@ ExtensionFunction::ResponseAction TabsQueryFunction::Run() { ExtensionFunction::ResponseAction TabsCreateFunction::Run() { std::unique_ptr<tabs::Create::Params> params( - tabs::Create::Params::Create(*args_)); + tabs::Create::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (!ExtensionTabUtil::IsTabStripEditable()) return RespondNow(Error(tabs_constants::kTabStripNotEditableError)); @@ -1196,7 +1202,7 @@ ExtensionFunction::ResponseAction TabsCreateFunction::Run() { ExtensionFunction::ResponseAction TabsDuplicateFunction::Run() { std::unique_ptr<tabs::Duplicate::Params> params( - tabs::Duplicate::Params::Create(*args_)); + tabs::Duplicate::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (!ExtensionTabUtil::IsTabStripEditable()) return RespondNow(Error(tabs_constants::kTabStripNotEditableError)); @@ -1235,7 +1241,7 @@ ExtensionFunction::ResponseAction TabsDuplicateFunction::Run() { } ExtensionFunction::ResponseAction TabsGetFunction::Run() { - std::unique_ptr<tabs::Get::Params> params(tabs::Get::Params::Create(*args_)); + std::unique_ptr<tabs::Get::Params> params(tabs::Get::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->tab_id; @@ -1269,7 +1275,7 @@ ExtensionFunction::ResponseAction TabsGetCurrentFunction::Run() { ExtensionFunction::ResponseAction TabsHighlightFunction::Run() { std::unique_ptr<tabs::Highlight::Params> params( - tabs::Highlight::Params::Create(*args_)); + tabs::Highlight::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); // Get the window id from the params; default to current window if omitted. @@ -1346,7 +1352,7 @@ TabsUpdateFunction::TabsUpdateFunction() : web_contents_(nullptr) {} ExtensionFunction::ResponseAction TabsUpdateFunction::Run() { std::unique_ptr<tabs::Update::Params> params( - tabs::Update::Params::Create(*args_)); + tabs::Update::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = -1; @@ -1556,7 +1562,7 @@ void TabsUpdateFunction::OnExecuteCodeFinished( ExtensionFunction::ResponseAction TabsMoveFunction::Run() { std::unique_ptr<tabs::Move::Params> params( - tabs::Move::Params::Create(*args_)); + tabs::Move::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int new_index = params->move_properties.index; @@ -1680,7 +1686,7 @@ bool TabsMoveFunction::MoveTab(int tab_id, ExtensionFunction::ResponseAction TabsReloadFunction::Run() { std::unique_ptr<tabs::Reload::Params> params( - tabs::Reload::Params::Create(*args_)); + tabs::Reload::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); bool bypass_cache = false; @@ -1725,7 +1731,7 @@ TabsRemoveFunction::~TabsRemoveFunction() = default; ExtensionFunction::ResponseAction TabsRemoveFunction::Run() { std::unique_ptr<tabs::Remove::Params> params( - tabs::Remove::Params::Create(*args_)); + tabs::Remove::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; @@ -1820,7 +1826,7 @@ class TabsRemoveFunction::WebContentsDestroyedObserver ExtensionFunction::ResponseAction TabsGroupFunction::Run() { std::unique_ptr<tabs::Group::Params> params( - tabs::Group::Params::Create(*args_)); + tabs::Group::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; @@ -1927,7 +1933,7 @@ ExtensionFunction::ResponseAction TabsGroupFunction::Run() { ExtensionFunction::ResponseAction TabsUngroupFunction::Run() { std::unique_ptr<tabs::Ungroup::Params> params( - tabs::Ungroup::Params::Create(*args_)); + tabs::Ungroup::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::vector<int> tab_ids; @@ -2023,16 +2029,15 @@ WebContents* TabsCaptureVisibleTabFunction::GetWebContentsForID( ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() { using api::extension_types::ImageDetails; - EXTENSION_FUNCTION_VALIDATE(args_); - const auto& list = args_->GetList(); + EXTENSION_FUNCTION_VALIDATE(has_args()); int context_id = extension_misc::kCurrentWindowId; - if (list.size() > 0 && list[0].is_int()) - context_id = list[0].GetInt(); + if (args().size() > 0 && args()[0].is_int()) + context_id = args()[0].GetInt(); std::unique_ptr<ImageDetails> image_details; - if (list.size() > 1) { - image_details = ImageDetails::FromValue(list[1]); + if (args().size() > 1) { + image_details = ImageDetails::FromValue(args()[1]); } std::string error; @@ -2054,7 +2059,7 @@ ExtensionFunction::ResponseAction TabsCaptureVisibleTabFunction::Run() { void TabsCaptureVisibleTabFunction::GetQuotaLimitHeuristics( QuotaLimitHeuristics* heuristics) const { - constexpr base::TimeDelta kSecond = base::TimeDelta::FromSeconds(1); + constexpr base::TimeDelta kSecond = base::Seconds(1); QuotaLimitHeuristic::Config limit = { tabs::MAX_CAPTURE_VISIBLE_TAB_CALLS_PER_SECOND, kSecond}; @@ -2134,7 +2139,7 @@ void TabsCaptureVisibleTabFunction::RegisterProfilePrefs( ExtensionFunction::ResponseAction TabsDetectLanguageFunction::Run() { std::unique_ptr<tabs::DetectLanguage::Params> params( - tabs::DetectLanguage::Params::Create(*args_)); + tabs::DetectLanguage::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = 0; @@ -2243,11 +2248,10 @@ ExecuteCodeFunction::InitResult ExecuteCodeInTabFunction::Init() { if (init_result_) return init_result_.value(); - const auto& list = args_->GetList(); - if (list.size() < 2) + if (args().size() < 2) return set_init_result(VALIDATION_FAILURE); - const auto& tab_id_value = list[0]; + const auto& tab_id_value = args()[0]; // |tab_id| is optional so it's ok if it's not there. int tab_id = -1; if (tab_id_value.is_int()) { @@ -2259,7 +2263,7 @@ ExecuteCodeFunction::InitResult ExecuteCodeInTabFunction::Init() { } // |details| are not optional. - const base::Value& details_value = list[1]; + const base::Value& details_value = args()[1]; if (!details_value.is_dict()) return set_init_result(VALIDATION_FAILURE); std::unique_ptr<InjectDetails> details(new InjectDetails()); @@ -2387,7 +2391,7 @@ bool TabsRemoveCSSFunction::ShouldRemoveCSS() const { ExtensionFunction::ResponseAction TabsSetZoomFunction::Run() { std::unique_ptr<tabs::SetZoom::Params> params( - tabs::SetZoom::Params::Create(*args_)); + tabs::SetZoom::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int tab_id = params->tab_id ? *params->tab_id : -1; @@ -2419,7 +2423,7 @@ ExtensionFunction::ResponseAction TabsSetZoomFunction::Run() { ExtensionFunction::ResponseAction TabsGetZoomFunction::Run() { std::unique_ptr<tabs::GetZoom::Params> params( - tabs::GetZoom::Params::Create(*args_)); + tabs::GetZoom::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int tab_id = params->tab_id ? *params->tab_id : -1; @@ -2440,7 +2444,7 @@ ExtensionFunction::ResponseAction TabsSetZoomSettingsFunction::Run() { using api::tabs::ZoomSettings; std::unique_ptr<tabs::SetZoomSettings::Params> params( - tabs::SetZoomSettings::Params::Create(*args_)); + tabs::SetZoomSettings::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int tab_id = params->tab_id ? *params->tab_id : -1; @@ -2490,7 +2494,7 @@ ExtensionFunction::ResponseAction TabsSetZoomSettingsFunction::Run() { ExtensionFunction::ResponseAction TabsGetZoomSettingsFunction::Run() { std::unique_ptr<tabs::GetZoomSettings::Params> params( - tabs::GetZoomSettings::Params::Create(*args_)); + tabs::GetZoomSettings::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); int tab_id = params->tab_id ? *params->tab_id : -1; @@ -2514,7 +2518,7 @@ ExtensionFunction::ResponseAction TabsGetZoomSettingsFunction::Run() { ExtensionFunction::ResponseAction TabsDiscardFunction::Run() { std::unique_ptr<tabs::Discard::Params> params( - tabs::Discard::Params::Create(*args_)); + tabs::Discard::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); WebContents* contents = nullptr; @@ -2556,7 +2560,7 @@ TabsDiscardFunction::~TabsDiscardFunction() {} ExtensionFunction::ResponseAction TabsGoForwardFunction::Run() { std::unique_ptr<tabs::GoForward::Params> params( - tabs::GoForward::Params::Create(*args_)); + tabs::GoForward::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->tab_id ? *params->tab_id : -1; @@ -2576,7 +2580,7 @@ ExtensionFunction::ResponseAction TabsGoForwardFunction::Run() { ExtensionFunction::ResponseAction TabsGoBackFunction::Run() { std::unique_ptr<tabs::GoBack::Params> params( - tabs::GoBack::Params::Create(*args_)); + tabs::GoBack::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->tab_id ? *params->tab_id : -1; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h index 2000882a82e..dc057c6ce05 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h @@ -238,6 +238,11 @@ class TabsCaptureVisibleTabFunction public ExtensionFunction { public: TabsCaptureVisibleTabFunction(); + + TabsCaptureVisibleTabFunction(const TabsCaptureVisibleTabFunction&) = delete; + TabsCaptureVisibleTabFunction& operator=( + const TabsCaptureVisibleTabFunction&) = delete; + static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); static void set_disable_throttling_for_tests( @@ -276,8 +281,6 @@ class TabsCaptureVisibleTabFunction static std::string CaptureResultToErrorMessage(CaptureResult result); static bool disable_throttling_for_test_; - - DISALLOW_COPY_AND_ASSIGN(TabsCaptureVisibleTabFunction); }; // Implement API calls tabs.executeScript, tabs.insertCSS, and tabs.removeCSS. @@ -379,13 +382,14 @@ class TabsDiscardFunction : public ExtensionFunction { TabsDiscardFunction(); + TabsDiscardFunction(const TabsDiscardFunction&) = delete; + TabsDiscardFunction& operator=(const TabsDiscardFunction&) = delete; + private: ~TabsDiscardFunction() override; // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(TabsDiscardFunction); }; class TabsGoForwardFunction : public ExtensionFunction { @@ -394,13 +398,14 @@ class TabsGoForwardFunction : public ExtensionFunction { TabsGoForwardFunction() {} + TabsGoForwardFunction(const TabsGoForwardFunction&) = delete; + TabsGoForwardFunction& operator=(const TabsGoForwardFunction&) = delete; + private: ~TabsGoForwardFunction() override {} // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(TabsGoForwardFunction); }; class TabsGoBackFunction : public ExtensionFunction { @@ -409,13 +414,14 @@ class TabsGoBackFunction : public ExtensionFunction { TabsGoBackFunction() {} + TabsGoBackFunction(const TabsGoBackFunction&) = delete; + TabsGoBackFunction& operator=(const TabsGoBackFunction&) = delete; + private: ~TabsGoBackFunction() override {} // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(TabsGoBackFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc index df436342952..9b515b503dd 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc @@ -92,6 +92,10 @@ content::WebContents* CreateAndAppendWebContentsWithHistory( } // namespace class TabsApiUnitTest : public ExtensionServiceTestBase { + public: + TabsApiUnitTest(const TabsApiUnitTest&) = delete; + TabsApiUnitTest& operator=(const TabsApiUnitTest&) = delete; + protected: TabsApiUnitTest() {} ~TabsApiUnitTest() override {} @@ -113,8 +117,6 @@ class TabsApiUnitTest : public ExtensionServiceTestBase { display::test::TestScreen test_screen_; std::unique_ptr<ScopedScreenOverride> scoped_screen_override_; - - DISALLOW_COPY_AND_ASSIGN(TabsApiUnitTest); }; void TabsApiUnitTest::SetUp() { @@ -284,7 +286,7 @@ TEST_F(TabsApiUnitTest, QueryWithoutTabsPermission) { std::unique_ptr<base::ListValue> tabs_list_without_permission( RunTabsQueryFunction(browser(), extension.get(), kTitleAndURLQueryInfo)); ASSERT_TRUE(tabs_list_without_permission); - EXPECT_EQ(0u, tabs_list_without_permission->GetSize()); + EXPECT_EQ(0u, tabs_list_without_permission->GetList().size()); // An extension with "tabs" permission however will see the third tab. scoped_refptr<const Extension> extension_with_permission = @@ -301,7 +303,7 @@ TEST_F(TabsApiUnitTest, QueryWithoutTabsPermission) { RunTabsQueryFunction(browser(), extension_with_permission.get(), kTitleAndURLQueryInfo)); ASSERT_TRUE(tabs_list_with_permission); - ASSERT_EQ(1u, tabs_list_with_permission->GetSize()); + ASSERT_EQ(1u, tabs_list_with_permission->GetList().size()); const base::DictionaryValue* third_tab_info; ASSERT_TRUE(tabs_list_with_permission->GetDictionary(0, &third_tab_info)); @@ -358,7 +360,7 @@ TEST_F(TabsApiUnitTest, QueryWithHostPermission) { RunTabsQueryFunction(browser(), extension_with_permission.get(), kTitleAndURLQueryInfo)); ASSERT_TRUE(tabs_list_with_permission); - ASSERT_EQ(1u, tabs_list_with_permission->GetSize()); + ASSERT_EQ(1u, tabs_list_with_permission->GetList().size()); const base::DictionaryValue* third_tab_info; ASSERT_TRUE(tabs_list_with_permission->GetDictionary(0, &third_tab_info)); @@ -374,7 +376,7 @@ TEST_F(TabsApiUnitTest, QueryWithHostPermission) { RunTabsQueryFunction(browser(), extension_with_permission.get(), kURLQueryInfo)); ASSERT_TRUE(tabs_list_with_permission); - ASSERT_EQ(2u, tabs_list_with_permission->GetSize()); + ASSERT_EQ(2u, tabs_list_with_permission->GetList().size()); const base::DictionaryValue* first_tab_info; const base::DictionaryValue* third_tab_info; @@ -431,10 +433,10 @@ TEST_F(TabsApiUnitTest, PDFExtensionNavigation) { scoped_refptr<TabsUpdateFunction> function = new TabsUpdateFunction(); function->set_extension(extension.get()); - std::unique_ptr<base::ListValue> args( + function->SetArgs( extension_function_test_utils::ParseList( - base::StringPrintf(R"([%d, {"url":"http://example.com"}])", tab_id))); - function->SetArgs(base::Value::FromUniquePtrValue(std::move(args))); + base::StringPrintf(R"([%d, {"url":"http://example.com"}])", tab_id)) + .value()); api_test_utils::SendResponseHelper response_helper(function.get()); function->RunWithValidation()->Execute(); @@ -1189,7 +1191,7 @@ TEST_F(TabsApiUnitTest, ScreenshotsRestricted) { policy::MockDlpContentManager mock_dlp_content_manager; policy::ScopedDlpContentManagerForTesting scoped_dlp_content_manager_( &mock_dlp_content_manager); - EXPECT_CALL(mock_dlp_content_manager, IsScreenshotRestricted(testing::_)) + EXPECT_CALL(mock_dlp_content_manager, IsScreenshotApiRestricted(testing::_)) .Times(1) .WillOnce(testing::Return(true)); diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc index 925c8b13082..185e8ecb369 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.cc @@ -129,6 +129,8 @@ const char kGroupParamsError[] = const char kCannotNavigateToDevtools[] = "Cannot navigate to a devtools:// page without either the devtools or " "debugger permission."; +const char kCannotNavigateToChromeUntrusted[] = + "Cannot navigate to a chrome-untrusted:// page."; const char kCannotHighlightTabs[] = "Cannot change tab highlight. This may be due to user dragging in " "progress."; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h index 6df59cefb74..ea67267ca06 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_constants.h @@ -112,6 +112,7 @@ extern const char kBrowserWindowNotAllowed[]; extern const char kLockedFullscreenModeNewTabError[]; extern const char kGroupParamsError[]; extern const char kCannotNavigateToDevtools[]; +extern const char kCannotNavigateToChromeUntrusted[]; extern const char kCannotHighlightTabs[]; extern const char kNotAllowedForDevToolsError[]; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc index 25cd387e94c..fc41f874cd3 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc @@ -347,7 +347,7 @@ void TabsEventRouter::DispatchTabInsertedAt(TabStripModel* tab_strip_model, int tab_id = ExtensionTabUtil::GetTabId(contents); std::unique_ptr<base::ListValue> args(new base::ListValue); - args->AppendInteger(tab_id); + args->Append(tab_id); std::unique_ptr<base::DictionaryValue> object_args( new base::DictionaryValue()); @@ -368,7 +368,7 @@ void TabsEventRouter::DispatchTabClosingAt(TabStripModel* tab_strip_model, int tab_id = ExtensionTabUtil::GetTabId(contents); std::unique_ptr<base::ListValue> args(new base::ListValue); - args->AppendInteger(tab_id); + args->Append(tab_id); std::unique_ptr<base::DictionaryValue> object_args( new base::DictionaryValue()); @@ -395,7 +395,7 @@ void TabsEventRouter::DispatchTabDetachedAt(WebContents* contents, } std::unique_ptr<base::ListValue> args(new base::ListValue); - args->AppendInteger(ExtensionTabUtil::GetTabId(contents)); + args->Append(ExtensionTabUtil::GetTabId(contents)); std::unique_ptr<base::DictionaryValue> object_args( new base::DictionaryValue()); @@ -415,7 +415,7 @@ void TabsEventRouter::DispatchActiveTabChanged(WebContents* old_contents, int index) { auto args = std::make_unique<base::ListValue>(); int tab_id = ExtensionTabUtil::GetTabId(new_contents); - args->AppendInteger(tab_id); + args->Append(tab_id); auto object_args = std::make_unique<base::DictionaryValue>(); object_args->SetKey(tabs_constants::kWindowIdKey, @@ -455,7 +455,7 @@ void TabsEventRouter::DispatchTabSelectionChanged( if (!contents) break; int tab_id = ExtensionTabUtil::GetTabId(contents); - all_tabs.AppendInteger(tab_id); + all_tabs.Append(tab_id); } std::unique_ptr<base::ListValue> args(new base::ListValue); @@ -482,7 +482,7 @@ void TabsEventRouter::DispatchTabMoved(WebContents* contents, int from_index, int to_index) { std::unique_ptr<base::ListValue> args(new base::ListValue); - args->AppendInteger(ExtensionTabUtil::GetTabId(contents)); + args->Append(ExtensionTabUtil::GetTabId(contents)); std::unique_ptr<base::DictionaryValue> object_args( new base::DictionaryValue()); @@ -505,8 +505,8 @@ void TabsEventRouter::DispatchTabReplacedAt(WebContents* old_contents, const int new_tab_id = ExtensionTabUtil::GetTabId(new_contents); const int old_tab_id = ExtensionTabUtil::GetTabId(old_contents); std::unique_ptr<base::ListValue> args(new base::ListValue); - args->AppendInteger(new_tab_id); - args->AppendInteger(old_tab_id); + args->Append(new_tab_id); + args->Append(old_tab_id); DispatchEvent(Profile::FromBrowserContext(new_contents->GetBrowserContext()), events::TABS_ON_REPLACED, api::tabs::OnReplaced::kEventName, @@ -589,7 +589,7 @@ void TabsEventRouter::DispatchTabUpdatedEvent( std::unique_ptr<base::ListValue> args_base(new base::ListValue); // First arg: The id of the tab that changed. - args_base->AppendInteger(ExtensionTabUtil::GetTabId(contents)); + args_base->Append(ExtensionTabUtil::GetTabId(contents)); // Second arg: An object containing the changes to the tab state. Filled in // by WillDispatchTabUpdatedEvent as a copy of changed_properties, if the diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h index 3dd45a26c4d..1b8bd032e8d 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.h @@ -43,6 +43,10 @@ class TabsEventRouter : public TabStripModelObserver, public resource_coordinator::TabLifecycleObserver { public: explicit TabsEventRouter(Profile* profile); + + TabsEventRouter(const TabsEventRouter&) = delete; + TabsEventRouter& operator=(const TabsEventRouter&) = delete; + ~TabsEventRouter() override; // BrowserTabStripTrackerDelegate: @@ -158,6 +162,9 @@ class TabsEventRouter : public TabStripModelObserver, // |contents|. TabEntry(TabsEventRouter* router, content::WebContents* contents); + TabEntry(const TabEntry&) = delete; + TabEntry& operator=(const TabEntry&) = delete; + // Indicate via a list of property names if a tab is loading based on its // WebContents. Whether the state has changed or not is used to determine if // events need to be sent to extensions during processing of TabChangedAt() @@ -191,8 +198,6 @@ class TabsEventRouter : public TabStripModelObserver, // Event router that the WebContents's noficiations are forwarded to. TabsEventRouter* router_; - - DISALLOW_COPY_AND_ASSIGN(TabEntry); }; // Gets the TabEntry for the given |contents|. Returns TabEntry* if found, @@ -214,8 +219,6 @@ class TabsEventRouter : public TabStripModelObserver, base::ScopedObservation<resource_coordinator::TabManager, resource_coordinator::TabLifecycleObserver> tab_manager_scoped_observation_{this}; - - DISALLOW_COPY_AND_ASSIGN(TabsEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc index 000278a7e56..b8f4c419247 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc @@ -4,20 +4,29 @@ #include <stddef.h> +#include "apps/test/app_window_waiter.h" +#include "base/run_loop.h" +#include "base/strings/pattern.h" #include "base/values.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" +#include "chrome/browser/apps/platform_apps/app_browsertest_util.h" +#include "chrome/browser/devtools/devtools_window_testing.h" #include "chrome/browser/extensions/api/tabs/tabs_api.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_commands.h" +#include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/interactive_test_utils.h" #include "content/public/test/browser_test.h" #include "extensions/browser/api_test_utils.h" #include "extensions/common/extension_builder.h" +#include "ui/views/widget/widget.h" +#include "ui/views/widget/widget_observer.h" namespace extensions { @@ -100,8 +109,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_QueryLastFocusedWindowTabs) { base::ListValue* result_tabs = result.get(); // We should have one initial tab and one added tab. - EXPECT_EQ(2u, result_tabs->GetSize()); - for (size_t i = 0; i < result_tabs->GetSize(); ++i) { + EXPECT_EQ(2u, result_tabs->GetList().size()); + for (size_t i = 0; i < result_tabs->GetList().size(); ++i) { base::DictionaryValue* result_tab = NULL; EXPECT_TRUE(result_tabs->GetDictionary(i, &result_tab)); EXPECT_EQ(focused_window_id, @@ -118,8 +127,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_QueryLastFocusedWindowTabs) { result_tabs = result.get(); // We should get one tab for each extra window and one for the initial window. - EXPECT_EQ(kExtraWindows + 1, result_tabs->GetSize()); - for (size_t i = 0; i < result_tabs->GetSize(); ++i) { + EXPECT_EQ(kExtraWindows + 1, result_tabs->GetList().size()); + for (size_t i = 0; i < result_tabs->GetList().size(); ++i) { base::DictionaryValue* result_tab = NULL; EXPECT_TRUE(result_tabs->GetDictionary(i, &result_tab)); EXPECT_NE(focused_window_id, @@ -131,19 +140,12 @@ class NonPersistentExtensionTabsTest : public ExtensionApiTest, public testing::WithParamInterface<ContextType> { public: - NonPersistentExtensionTabsTest() = default; + NonPersistentExtensionTabsTest() : ExtensionApiTest(GetParam()) {} ~NonPersistentExtensionTabsTest() override = default; NonPersistentExtensionTabsTest(const NonPersistentExtensionTabsTest&) = delete; NonPersistentExtensionTabsTest& operator=( const NonPersistentExtensionTabsTest&) = delete; - - protected: - const Extension* LoadNonPersistentExtension(const char* relative_path) { - return LoadExtension( - test_data_dir_.AppendASCII(relative_path), - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker}); - } }; // Crashes on Lacros only. http://crbug.com/1150133 @@ -160,10 +162,7 @@ class NonPersistentExtensionTabsTest // TODO(crbug.com/984350): Expand the test to verify that setSelfAsOpener // param is ignored from Service Worker extension scripts. IN_PROC_BROWSER_TEST_P(NonPersistentExtensionTabsTest, MAYBE_TabCurrentWindow) { - ASSERT_TRUE(RunExtensionTest( - "tabs/current_window", {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker})) - << message_; + ASSERT_TRUE(RunExtensionTest("tabs/current_window")) << message_; } // Crashes on Lacros and Linux-ozone-rel. http://crbug.com/1196709 @@ -176,10 +175,7 @@ IN_PROC_BROWSER_TEST_P(NonPersistentExtensionTabsTest, MAYBE_TabCurrentWindow) { // Tests chrome.windows.getLastFocused. IN_PROC_BROWSER_TEST_P(NonPersistentExtensionTabsTest, MAYBE_TabGetLastFocusedWindow) { - ASSERT_TRUE(RunExtensionTest( - "tabs/last_focused_window", {}, - {.load_as_service_worker = GetParam() == ContextType::kServiceWorker})) - << message_; + ASSERT_TRUE(RunExtensionTest("tabs/last_focused_window")) << message_; } INSTANTIATE_TEST_SUITE_P(EventPage, @@ -190,4 +186,232 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, NonPersistentExtensionTabsTest, ::testing::Values(ContextType::kServiceWorker)); +// TODO(llandwerlin): Activating a browser window and waiting for the +// action to happen requires views::Widget which is not available on +// MacOSX. Deactivate for now. +#if !defined(OS_MAC) +class ExtensionWindowLastFocusedTest : public PlatformAppBrowserTest { + public: + void SetUpOnMainThread() override; + + void ActivateBrowserWindow(Browser* browser); + + Browser* CreateBrowserWithEmptyTab(bool as_popup); + + int GetTabId(const base::DictionaryValue* value) const; + + base::Value* RunFunction(ExtensionFunction* function, + const std::string& params); + + const Extension* extension() { return extension_.get(); } + + private: + // A helper class to wait for an views::Widget to become activated. + class WidgetActivatedWaiter : public views::WidgetObserver { + public: + explicit WidgetActivatedWaiter(views::Widget* widget) + : widget_(widget), waiting_(false) { + widget_->AddObserver(this); + } + ~WidgetActivatedWaiter() override { widget_->RemoveObserver(this); } + + void ActivateAndWait() { + widget_->Activate(); + if (!widget_->IsActive()) { + waiting_ = true; + base::RunLoop nested_run_loop( + base::RunLoop::Type::kNestableTasksAllowed); + quit_closure_ = nested_run_loop.QuitWhenIdleClosure(); + nested_run_loop.Run(); + } + } + + // views::WidgetObserver: + void OnWidgetActivationChanged(views::Widget* widget, + bool active) override { + if (widget_ == widget && waiting_) { + waiting_ = false; + std::move(quit_closure_).Run(); + } + } + + private: + views::Widget* widget_; + bool waiting_; + base::RepeatingClosure quit_closure_; + }; + + scoped_refptr<const Extension> extension_; +}; + +void ExtensionWindowLastFocusedTest::SetUpOnMainThread() { + PlatformAppBrowserTest::SetUpOnMainThread(); + extension_ = ExtensionBuilder("Test").Build(); +} + +void ExtensionWindowLastFocusedTest::ActivateBrowserWindow(Browser* browser) { + BrowserView* view = BrowserView::GetBrowserViewForBrowser(browser); + EXPECT_NE(nullptr, view); + views::Widget* widget = view->frame(); + EXPECT_NE(nullptr, widget); + WidgetActivatedWaiter waiter(widget); + waiter.ActivateAndWait(); +} + +Browser* ExtensionWindowLastFocusedTest::CreateBrowserWithEmptyTab( + bool as_popup) { + Browser* new_browser; + if (as_popup) { + new_browser = Browser::Create( + Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(), true)); + } else { + new_browser = + Browser::Create(Browser::CreateParams(browser()->profile(), true)); + } + AddBlankTabAndShow(new_browser); + return new_browser; +} + +int ExtensionWindowLastFocusedTest::GetTabId( + const base::DictionaryValue* value) const { + const base::ListValue* tabs = nullptr; + if (!value->GetList(keys::kTabsKey, &tabs)) + return -2; + const base::Value* tab = nullptr; + if (!tabs->Get(0, &tab)) + return -2; + const base::DictionaryValue* tab_dict = nullptr; + if (!tab->GetAsDictionary(&tab_dict)) + return -2; + int tab_id = 0; + if (!tab_dict->GetInteger(keys::kIdKey, &tab_id)) + return -2; + return tab_id; +} + +base::Value* ExtensionWindowLastFocusedTest::RunFunction( + ExtensionFunction* function, + const std::string& params) { + function->set_extension(extension_.get()); + return utils::RunFunctionAndReturnSingleResult(function, params, browser()); +} + +IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, + NoDevtoolsAndAppWindows) { + DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( + browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); + { + int devtools_window_id = ExtensionTabUtil::GetWindowId( + DevToolsWindowTesting::Get(devtools)->browser()); + ActivateBrowserWindow(DevToolsWindowTesting::Get(devtools)->browser()); + + scoped_refptr<WindowsGetLastFocusedFunction> function = + new WindowsGetLastFocusedFunction(); + std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( + RunFunction(function.get(), "[{\"populate\": true}]"))); + EXPECT_NE(devtools_window_id, + api_test_utils::GetInteger(result.get(), "id")); + } + + AppWindow* app_window = CreateTestAppWindow( + "{\"outerBounds\": " + "{\"width\": 300, \"height\": 300," + " \"minWidth\": 200, \"minHeight\": 200," + " \"maxWidth\": 400, \"maxHeight\": 400}}"); + { + apps::AppWindowWaiter waiter(AppWindowRegistry::Get(browser()->profile()), + app_window->extension_id()); + waiter.WaitForActivated(); + + scoped_refptr<WindowsGetLastFocusedFunction> get_current_app_function = + new WindowsGetLastFocusedFunction(); + std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( + RunFunction(get_current_app_function.get(), "[{\"populate\": true}]"))); + int app_window_id = app_window->session_id().id(); + EXPECT_NE(app_window_id, api_test_utils::GetInteger(result.get(), "id")); + } + + DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); + CloseAppWindow(app_window); +} + +IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, + NoTabIdForDevToolsAndAppWindows) { + Browser* normal_browser = CreateBrowserWithEmptyTab(false); + { + ActivateBrowserWindow(normal_browser); + + scoped_refptr<WindowsGetLastFocusedFunction> function = + new WindowsGetLastFocusedFunction(); + std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( + RunFunction(function.get(), "[{\"populate\": true}]"))); + int normal_browser_window_id = + ExtensionTabUtil::GetWindowId(normal_browser); + EXPECT_EQ(normal_browser_window_id, + api_test_utils::GetInteger(result.get(), "id")); + EXPECT_NE(-1, GetTabId(result.get())); + EXPECT_EQ("normal", api_test_utils::GetString(result.get(), "type")); + } + + Browser* popup_browser = CreateBrowserWithEmptyTab(true); + { + ActivateBrowserWindow(popup_browser); + + scoped_refptr<WindowsGetLastFocusedFunction> function = + new WindowsGetLastFocusedFunction(); + std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( + RunFunction(function.get(), "[{\"populate\": true}]"))); + int popup_browser_window_id = ExtensionTabUtil::GetWindowId(popup_browser); + EXPECT_EQ(popup_browser_window_id, + api_test_utils::GetInteger(result.get(), "id")); + EXPECT_NE(-1, GetTabId(result.get())); + EXPECT_EQ("popup", api_test_utils::GetString(result.get(), "type")); + } + + DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( + browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); + { + ActivateBrowserWindow(DevToolsWindowTesting::Get(devtools)->browser()); + + scoped_refptr<WindowsGetLastFocusedFunction> function = + new WindowsGetLastFocusedFunction(); + std::unique_ptr<base::DictionaryValue> result( + utils::ToDictionary(RunFunction( + function.get(), + "[{\"populate\": true, \"windowTypes\": [ \"devtools\" ]}]"))); + int devtools_window_id = ExtensionTabUtil::GetWindowId( + DevToolsWindowTesting::Get(devtools)->browser()); + EXPECT_EQ(devtools_window_id, + api_test_utils::GetInteger(result.get(), "id")); + EXPECT_EQ(-1, GetTabId(result.get())); + EXPECT_EQ("devtools", api_test_utils::GetString(result.get(), "type")); + } + + AppWindow* app_window = CreateTestAppWindow( + "{\"outerBounds\": " + "{\"width\": 300, \"height\": 300," + " \"minWidth\": 200, \"minHeight\": 200," + " \"maxWidth\": 400, \"maxHeight\": 400}}"); + { + apps::AppWindowWaiter waiter(AppWindowRegistry::Get(browser()->profile()), + app_window->extension_id()); + waiter.WaitForActivated(); + + scoped_refptr<WindowsGetLastFocusedFunction> get_current_app_function = + new WindowsGetLastFocusedFunction(); + get_current_app_function->set_extension(extension()); + EXPECT_EQ( + tabs_constants::kNoLastFocusedWindowError, + extension_function_test_utils::RunFunctionAndReturnError( + get_current_app_function.get(), + "[{\"populate\": true, \"windowTypes\": [ \"app\" ]}]", browser())); + } + + chrome::CloseWindow(normal_browser); + chrome::CloseWindow(popup_browser); + DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); + CloseAppWindow(app_window); +} +#endif // !defined(OS_MAC) + } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc index 6d8752c6b0f..9bc679885b9 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc @@ -9,7 +9,6 @@ #include <memory> #include <string> -#include "apps/test/app_window_waiter.h" #include "base/format_macros.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" @@ -43,7 +42,6 @@ #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/zoom/chrome_zoom_level_prefs.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/ui_test_utils.h" @@ -68,8 +66,6 @@ #include "third_party/blink/public/common/page/page_zoom.h" #include "ui/base/window_open_disposition.h" #include "ui/gfx/geometry/rect.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_observer.h" #if defined(OS_MAC) #include "ui/base/test/scoped_fake_nswindow_fullscreen.h" @@ -86,8 +82,21 @@ class ExtensionTabsTest : public PlatformAppBrowserTest { public: ExtensionTabsTest() {} - private: - DISALLOW_COPY_AND_ASSIGN(ExtensionTabsTest); + ExtensionTabsTest(const ExtensionTabsTest&) = delete; + ExtensionTabsTest& operator=(const ExtensionTabsTest&) = delete; + + std::string GetWindowType(Browser* test_browser, + scoped_refptr<const Extension> extension) { + scoped_refptr<WindowsGetFunction> function = new WindowsGetFunction(); + function->set_extension(extension.get()); + std::string args = base::StringPrintf( + R"([%u, {"windowTypes": ["normal", "popup", "devtools", "app"]}])", + ExtensionTabUtil::GetWindowId(test_browser)); + std::unique_ptr<base::DictionaryValue> result( + utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( + function.get(), args, browser()))); + return api_test_utils::GetString(result.get(), "type"); + } }; class ExtensionWindowCreateTest : public InProcessBrowserTest { @@ -188,18 +197,23 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { // TODO(aa): Minimized and maximized dimensions. Is there a way to set // minimize/maximize programmatically? - // Popup. - Browser* popup_browser = Browser::Create( + // Check window type. + EXPECT_EQ("normal", GetWindowType(browser(), extension)); + Browser* test_browser = Browser::Create( Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(), true)); - function = new WindowsGetFunction(); - function->set_extension(extension.get()); - result.reset(utils::ToDictionary( - utils::RunFunctionAndReturnSingleResult( - function.get(), - base::StringPrintf( - "[%u]", ExtensionTabUtil::GetWindowId(popup_browser)), - browser()))); - EXPECT_EQ("popup", api_test_utils::GetString(result.get(), "type")); + EXPECT_EQ("popup", GetWindowType(test_browser, extension)); + DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( + browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); + EXPECT_EQ("devtools", + GetWindowType(DevToolsWindowTesting::Get(devtools)->browser(), + extension)); + DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); + test_browser = Browser::Create(Browser::CreateParams::CreateForApp( + "test-app", true, gfx::Rect(), browser()->profile(), true)); + EXPECT_EQ("app", GetWindowType(test_browser, extension)); + test_browser = Browser::Create(Browser::CreateParams::CreateForAppPopup( + "test-app-popup", true, gfx::Rect(), browser()->profile(), true)); + EXPECT_EQ("popup", GetWindowType(test_browser, extension)); // Incognito. Browser* incognito_browser = CreateIncognitoBrowser(); @@ -221,22 +235,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetWindow) { function.get(), base::StringPrintf("[%u]", incognito_window_id), browser(), api_test_utils::INCLUDE_INCOGNITO))); EXPECT_TRUE(api_test_utils::GetBoolean(result.get(), "incognito")); - - // DevTools window. - DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( - browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); - - function = new WindowsGetFunction(); - function->set_extension(extension.get()); - result.reset(utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( - function.get(), - base::StringPrintf("[%u, {\"windowTypes\": [\"devtools\"]}]", - ExtensionTabUtil::GetWindowId( - DevToolsWindowTesting::Get(devtools)->browser())), - browser(), api_test_utils::INCLUDE_INCOGNITO))); - EXPECT_EQ("devtools", api_test_utils::GetString(result.get(), "type")); - - DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); } IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetCurrentWindow) { @@ -307,8 +305,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) { "[]", browser()))); base::ListValue* windows = result.get(); - EXPECT_EQ(window_ids.size(), windows->GetSize()); - for (size_t i = 0; i < windows->GetSize(); ++i) { + EXPECT_EQ(window_ids.size(), windows->GetList().size()); + for (size_t i = 0; i < windows->GetList().size(); ++i) { base::DictionaryValue* result_window = nullptr; EXPECT_TRUE(windows->GetDictionary(i, &result_window)); result_ids.insert(GetWindowId(result_window)); @@ -329,8 +327,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) { browser()))); windows = result.get(); - EXPECT_EQ(window_ids.size(), windows->GetSize()); - for (size_t i = 0; i < windows->GetSize(); ++i) { + EXPECT_EQ(window_ids.size(), windows->GetList().size()); + for (size_t i = 0; i < windows->GetList().size(); ++i) { base::DictionaryValue* result_window = nullptr; EXPECT_TRUE(windows->GetDictionary(i, &result_window)); result_ids.insert(GetWindowId(result_window)); @@ -381,8 +379,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindowsAllTypes) { browser()))); base::ListValue* windows = result.get(); - EXPECT_EQ(window_ids.size(), windows->GetSize()); - for (size_t i = 0; i < windows->GetSize(); ++i) { + EXPECT_EQ(window_ids.size(), windows->GetList().size()); + for (size_t i = 0; i < windows->GetList().size(); ++i) { base::DictionaryValue* result_window = nullptr; EXPECT_TRUE(windows->GetDictionary(i, &result_window)); result_ids.insert(GetWindowId(result_window)); @@ -404,8 +402,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindowsAllTypes) { browser()))); windows = result.get(); - EXPECT_EQ(window_ids.size(), windows->GetSize()); - for (size_t i = 0; i < windows->GetSize(); ++i) { + EXPECT_EQ(window_ids.size(), windows->GetList().size()); + for (size_t i = 0; i < windows->GetList().size(); ++i) { base::DictionaryValue* result_window = nullptr; EXPECT_TRUE(windows->GetDictionary(i, &result_window)); result_ids.insert(GetWindowId(result_window)); @@ -475,8 +473,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DefaultToIncognitoWhenItIsForced) { static const char kArgsWithoutExplicitIncognitoParam[] = "[{\"url\": \"about:blank\"}]"; // Force Incognito mode. - IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), - IncognitoModePrefs::FORCED); + IncognitoModePrefs::SetAvailability( + browser()->profile()->GetPrefs(), + IncognitoModePrefs::Availability::kForced); // Run without an explicit "incognito" param. scoped_refptr<WindowsCreateFunction> function(new WindowsCreateFunction()); function->SetRenderFrameHost( @@ -515,8 +514,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DefaultToIncognitoWhenItIsForcedAndNoArgs) { static const char kEmptyArgs[] = "[]"; // Force Incognito mode. - IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), - IncognitoModePrefs::FORCED); + IncognitoModePrefs::SetAvailability( + browser()->profile()->GetPrefs(), + IncognitoModePrefs::Availability::kForced); // Run without an explicit "incognito" param. scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction(); scoped_refptr<const Extension> extension(ExtensionBuilder("Test").Build()); @@ -552,8 +552,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, static const char kArgsWithExplicitIncognitoParam[] = "[{\"url\": \"about:blank\", \"incognito\": false }]"; // Force Incognito mode. - IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), - IncognitoModePrefs::FORCED); + IncognitoModePrefs::SetAvailability( + browser()->profile()->GetPrefs(), + IncognitoModePrefs::Availability::kForced); // Run with an explicit "incognito" param. scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction(); @@ -582,8 +583,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, Browser* incognito_browser = CreateIncognitoBrowser(); // Disable Incognito mode. - IncognitoModePrefs::SetAvailability(browser()->profile()->GetPrefs(), - IncognitoModePrefs::DISABLED); + IncognitoModePrefs::SetAvailability( + browser()->profile()->GetPrefs(), + IncognitoModePrefs::Availability::kDisabled); // Run in normal window. scoped_refptr<WindowsCreateFunction> function = new WindowsCreateFunction(); scoped_refptr<const Extension> extension(ExtensionBuilder("Test").Build()); @@ -618,8 +620,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryCurrentWindowTabs) { base::ListValue* result_tabs = result.get(); // We should have one initial tab and one added tab. - EXPECT_EQ(2u, result_tabs->GetSize()); - for (size_t i = 0; i < result_tabs->GetSize(); ++i) { + EXPECT_EQ(2u, result_tabs->GetList().size()); + for (size_t i = 0; i < result_tabs->GetList().size(); ++i) { base::DictionaryValue* result_tab = nullptr; EXPECT_TRUE(result_tabs->GetDictionary(i, &result_tab)); EXPECT_EQ(window_id, GetTabWindowId(result_tab)); @@ -635,7 +637,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryCurrentWindowTabs) { result_tabs = result.get(); // We should have one tab for each extra window. - EXPECT_EQ(kExtraWindows, result_tabs->GetSize()); + EXPECT_EQ(kExtraWindows, result_tabs->GetList().size()); for (size_t i = 0; i < kExtraWindows; ++i) { base::DictionaryValue* result_tab = nullptr; EXPECT_TRUE(result_tabs->GetDictionary(i, &result_tab)); @@ -666,8 +668,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryAllTabsWithDevTools) { std::set<int> result_ids; base::ListValue* result_tabs = result.get(); // We should have one tab per browser except for DevTools. - EXPECT_EQ(kNumWindows, result_tabs->GetSize()); - for (size_t i = 0; i < result_tabs->GetSize(); ++i) { + EXPECT_EQ(kNumWindows, result_tabs->GetList().size()); + for (size_t i = 0; i < result_tabs->GetList().size(); ++i) { base::DictionaryValue* result_tab = nullptr; EXPECT_TRUE(result_tabs->GetDictionary(i, &result_tab)); result_ids.insert(GetTabWindowId(result_tab)); @@ -694,7 +696,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryTabGroups) { utils::ToList(utils::RunFunctionAndReturnSingleResult(function.get(), args, browser()))); - EXPECT_EQ(2u, result.get()->GetSize()); + EXPECT_EQ(2u, result.get()->GetList().size()); } IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DontCreateTabInClosingPopupWindow) { @@ -805,123 +807,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateDevToolsWindow) { DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); } -// TODO(llandwerlin): Activating a browser window and waiting for the -// action to happen requires views::Widget which is not available on -// MacOSX. Deactivate for now. -// TODO(warx): Move ExtensionWindowLastFocusedTest to interactive -// uitest as it triggers native widget activation. -#if !defined(OS_MAC) -class ExtensionWindowLastFocusedTest : public ExtensionTabsTest { - public: - void SetUpOnMainThread() override; - - void ActivateBrowserWindow(Browser* browser); - - Browser* CreateBrowserWithEmptyTab(bool as_popup); - - int GetTabId(const base::DictionaryValue* value) const; - - base::Value* RunFunction(ExtensionFunction* function, - const std::string& params); - - const Extension* extension() { return extension_.get(); } - - private: - // A helper class to wait for an views::Widget to become activated. - class WidgetActivatedWaiter : public views::WidgetObserver { - public: - explicit WidgetActivatedWaiter(views::Widget* widget) - : widget_(widget), waiting_(false) { - widget_->AddObserver(this); - } - ~WidgetActivatedWaiter() override { widget_->RemoveObserver(this); } - - void ActivateAndWait() { - widget_->Activate(); - if (!widget_->IsActive()) { - waiting_ = true; - content::RunMessageLoop(); - } - } - - // views::WidgetObserver: - void OnWidgetActivationChanged(views::Widget* widget, - bool active) override { - if (widget_ == widget && waiting_) { - base::RunLoop::QuitCurrentWhenIdleDeprecated(); - waiting_ = false; - } - } - - private: - views::Widget* widget_; - bool waiting_; - }; - - scoped_refptr<const Extension> extension_; -}; - -void ExtensionWindowLastFocusedTest::SetUpOnMainThread() { - ExtensionTabsTest::SetUpOnMainThread(); - extension_ = ExtensionBuilder("Test").Build(); -} - -void ExtensionWindowLastFocusedTest::ActivateBrowserWindow(Browser* browser) { - BrowserView* view = BrowserView::GetBrowserViewForBrowser(browser); - EXPECT_NE(nullptr, view); - views::Widget* widget = view->frame(); - EXPECT_NE(nullptr, widget); - WidgetActivatedWaiter waiter(widget); - waiter.ActivateAndWait(); -} - -Browser* ExtensionWindowLastFocusedTest::CreateBrowserWithEmptyTab( - bool as_popup) { - Browser* new_browser; - if (as_popup) - new_browser = Browser::Create( - Browser::CreateParams(Browser::TYPE_POPUP, browser()->profile(), true)); - else - new_browser = - Browser::Create(Browser::CreateParams(browser()->profile(), true)); - AddBlankTabAndShow(new_browser); - return new_browser; -} - -int ExtensionWindowLastFocusedTest::GetTabId( - const base::DictionaryValue* value) const { - const base::ListValue* tabs = NULL; - if (!value->GetList(keys::kTabsKey, &tabs)) - return -2; - const base::Value* tab = NULL; - if (!tabs->Get(0, &tab)) - return -2; - const base::DictionaryValue* tab_dict = NULL; - if (!tab->GetAsDictionary(&tab_dict)) - return -2; - int tab_id = 0; - if (!tab_dict->GetInteger(keys::kIdKey, &tab_id)) - return -2; - return tab_id; -} - -base::Value* ExtensionWindowLastFocusedTest::RunFunction( - ExtensionFunction* function, - const std::string& params) { - function->set_extension(extension_.get()); - return utils::RunFunctionAndReturnSingleResult(function, params, browser()); -} - -IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, - ExtensionAPICannotNavigateDevtools) { +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, ExtensionAPICannotNavigateDevtools) { scoped_refptr<const Extension> extension = ExtensionBuilder("Test").AddPermission("tabs").Build(); DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); - scoped_refptr<TabsUpdateFunction> function = - new TabsUpdateFunction(); + scoped_refptr<TabsUpdateFunction> function = new TabsUpdateFunction(); function->set_extension(extension.get()); EXPECT_TRUE(base::MatchPattern( @@ -937,126 +830,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); } -// Flaky. https://crbug.com/1035622 -IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, - DISABLED_NoDevtoolsAndAppWindows) { - DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( - browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); - { - int devtools_window_id = ExtensionTabUtil::GetWindowId( - DevToolsWindowTesting::Get(devtools)->browser()); - ActivateBrowserWindow(DevToolsWindowTesting::Get(devtools)->browser()); - - scoped_refptr<WindowsGetLastFocusedFunction> function = - new WindowsGetLastFocusedFunction(); - std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( - RunFunction(function.get(), "[{\"populate\": true}]"))); - EXPECT_NE(devtools_window_id, - api_test_utils::GetInteger(result.get(), "id")); - } - - AppWindow* app_window = CreateTestAppWindow( - "{\"outerBounds\": " - "{\"width\": 300, \"height\": 300," - " \"minWidth\": 200, \"minHeight\": 200," - " \"maxWidth\": 400, \"maxHeight\": 400}}"); - { - apps::AppWindowWaiter waiter(AppWindowRegistry::Get(browser()->profile()), - app_window->extension_id()); - waiter.WaitForActivated(); - - scoped_refptr<WindowsGetLastFocusedFunction> get_current_app_function = - new WindowsGetLastFocusedFunction(); - std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( - RunFunction(get_current_app_function.get(), "[{\"populate\": true}]"))); - int app_window_id = app_window->session_id().id(); - EXPECT_NE(app_window_id, api_test_utils::GetInteger(result.get(), "id")); - } - - DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); - CloseAppWindow(app_window); -} - -// https://crbug.com/956870 -IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, - DISABLED_NoTabIdForDevToolsAndAppWindows) { - Browser* normal_browser = CreateBrowserWithEmptyTab(false); - { - ActivateBrowserWindow(normal_browser); - - scoped_refptr<WindowsGetLastFocusedFunction> function = - new WindowsGetLastFocusedFunction(); - std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( - RunFunction(function.get(), "[{\"populate\": true}]"))); - int normal_browser_window_id = - ExtensionTabUtil::GetWindowId(normal_browser); - EXPECT_EQ(normal_browser_window_id, - api_test_utils::GetInteger(result.get(), "id")); - EXPECT_NE(-1, GetTabId(result.get())); - EXPECT_EQ("normal", api_test_utils::GetString(result.get(), "type")); - } - - Browser* popup_browser = CreateBrowserWithEmptyTab(true); - { - ActivateBrowserWindow(popup_browser); - - scoped_refptr<WindowsGetLastFocusedFunction> function = - new WindowsGetLastFocusedFunction(); - std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( - RunFunction(function.get(), "[{\"populate\": true}]"))); - int popup_browser_window_id = ExtensionTabUtil::GetWindowId(popup_browser); - EXPECT_EQ(popup_browser_window_id, - api_test_utils::GetInteger(result.get(), "id")); - EXPECT_NE(-1, GetTabId(result.get())); - EXPECT_EQ("popup", api_test_utils::GetString(result.get(), "type")); - } - - DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( - browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); - { - ActivateBrowserWindow(DevToolsWindowTesting::Get(devtools)->browser()); - - scoped_refptr<WindowsGetLastFocusedFunction> function = - new WindowsGetLastFocusedFunction(); - std::unique_ptr<base::DictionaryValue> result( - utils::ToDictionary(RunFunction( - function.get(), - "[{\"populate\": true, \"windowTypes\": [ \"devtools\" ]}]"))); - int devtools_window_id = ExtensionTabUtil::GetWindowId( - DevToolsWindowTesting::Get(devtools)->browser()); - EXPECT_EQ(devtools_window_id, - api_test_utils::GetInteger(result.get(), "id")); - EXPECT_EQ(-1, GetTabId(result.get())); - EXPECT_EQ("devtools", api_test_utils::GetString(result.get(), "type")); - } - - AppWindow* app_window = CreateTestAppWindow( - "{\"outerBounds\": " - "{\"width\": 300, \"height\": 300," - " \"minWidth\": 200, \"minHeight\": 200," - " \"maxWidth\": 400, \"maxHeight\": 400}}"); - { - apps::AppWindowWaiter waiter(AppWindowRegistry::Get(browser()->profile()), - app_window->extension_id()); - waiter.WaitForActivated(); - - scoped_refptr<WindowsGetLastFocusedFunction> get_current_app_function = - new WindowsGetLastFocusedFunction(); - get_current_app_function->set_extension(extension()); - EXPECT_EQ( - tabs_constants::kNoLastFocusedWindowError, - extension_function_test_utils::RunFunctionAndReturnError( - get_current_app_function.get(), - "[{\"populate\": true, \"windowTypes\": [ \"app\" ]}]", browser())); - } - - chrome::CloseWindow(normal_browser); - chrome::CloseWindow(popup_browser); - DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); - CloseAppWindow(app_window); -} -#endif // !defined(OS_MAC) - #if defined(OS_MAC) // https://crbug.com/836327 #define MAYBE_AcceptState DISABLED_AcceptState @@ -1309,6 +1082,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, OnBoundsChanged) { ASSERT_TRUE(catcher.GetNextResult()); } +IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, WindowsCreate) { + ASSERT_TRUE(RunExtensionTest("api_test/windows/create")) << message_; +} + IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, ExecuteScriptOnDevTools) { scoped_refptr<const Extension> extension = ExtensionBuilder("Test").AddPermission("tabs").Build(); @@ -1363,14 +1140,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { RunQueryFunction("[{\"discarded\": false}]")); // The two created plus the default tab. - EXPECT_EQ(3u, result->GetSize()); + EXPECT_EQ(3u, result->GetList().size()); } // Get discarded tabs. { std::unique_ptr<base::ListValue> result( RunQueryFunction("[{\"discarded\": true}]")); - EXPECT_EQ(0u, result->GetSize()); + EXPECT_EQ(0u, result->GetList().size()); } TabStripModel* tab_strip_model = browser()->tab_strip_model(); @@ -1394,14 +1171,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { { std::unique_ptr<base::ListValue> result( RunQueryFunction("[{\"discarded\": false}]")); - EXPECT_EQ(2u, result->GetSize()); + EXPECT_EQ(2u, result->GetList().size()); } // Get discarded tabs after discarding one tab. { std::unique_ptr<base::ListValue> result( RunQueryFunction("[{\"discarded\": true}]")); - EXPECT_EQ(1u, result->GetSize()); + EXPECT_EQ(1u, result->GetList().size()); // Make sure the returned tab is the correct one. int tab_id_a = ExtensionTabUtil::GetTabId(web_contents_a); @@ -1421,7 +1198,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { { std::unique_ptr<base::ListValue> result( RunQueryFunction("[{\"discarded\": false}]")); - EXPECT_EQ(1u, result->GetSize()); + EXPECT_EQ(1u, result->GetList().size()); // Make sure the returned tab is the correct one. int tab_id_c = @@ -1439,7 +1216,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { { std::unique_ptr<base::ListValue> result( RunQueryFunction("[{\"discarded\": true}]")); - EXPECT_EQ(2u, result->GetSize()); + EXPECT_EQ(2u, result->GetList().size()); } // Activates the first created tab. @@ -1449,14 +1226,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { { std::unique_ptr<base::ListValue> result( RunQueryFunction("[{\"discarded\": false}]")); - EXPECT_EQ(2u, result->GetSize()); + EXPECT_EQ(2u, result->GetList().size()); } // Get discarded tabs after activating a discarded tab. { std::unique_ptr<base::ListValue> result( RunQueryFunction("[{\"discarded\": true}]")); - EXPECT_EQ(1u, result->GetSize()); + EXPECT_EQ(1u, result->GetList().size()); } } @@ -1610,11 +1387,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { // Get auto-discardable tabs. Returns all since tabs are auto-discardable // by default. query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); - EXPECT_EQ(3u, query_result->GetSize()); + EXPECT_EQ(3u, query_result->GetList().size()); // Get non auto-discardable tabs. query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); - EXPECT_EQ(0u, query_result->GetSize()); + EXPECT_EQ(0u, query_result->GetList().size()); // Update the auto-discardable state of web contents A. int tab_id_a = ExtensionTabUtil::GetTabId(web_contents_a); @@ -1631,11 +1408,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { // Get auto-discardable tabs after changing the status of web contents A. query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); - EXPECT_EQ(2u, query_result->GetSize()); + EXPECT_EQ(2u, query_result->GetList().size()); // Get non auto-discardable tabs after changing the status of web contents A. query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); - EXPECT_EQ(1u, query_result->GetSize()); + EXPECT_EQ(1u, query_result->GetList().size()); // Make sure the returned tab is the correct one. int id = -1; @@ -1654,7 +1431,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { // Get auto-discardable tabs after changing the status of both created tabs. query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); - EXPECT_EQ(1u, query_result->GetSize()); + EXPECT_EQ(1u, query_result->GetList().size()); // Make sure the returned tab is the correct one. id = -1; @@ -1666,7 +1443,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { // Get auto-discardable tabs after changing the status of both created tabs. query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); - EXPECT_EQ(2u, query_result->GetSize()); + EXPECT_EQ(2u, query_result->GetList().size()); // Resets the first tab back to auto-discardable. update_result.reset(RunUpdateFunction( @@ -1677,11 +1454,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { // Get auto-discardable tabs after resetting the status of web contents A. query_result.reset(RunQueryFunction(kAutoDiscardableQueryInfo)); - EXPECT_EQ(2u, query_result->GetSize()); + EXPECT_EQ(2u, query_result->GetList().size()); // Get non auto-discardable tabs after resetting the status of web contents A. query_result.reset(RunQueryFunction(kNonAutoDiscardableQueryInfo)); - EXPECT_EQ(1u, query_result->GetSize()); + EXPECT_EQ(1u, query_result->GetList().size()); } // Tester class for the tabs.zoom* api functions. @@ -1824,11 +1601,13 @@ testing::AssertionResult ExtensionTabsZoomTest::RunGetDefaultZoom( if (!get_zoom_settings_result) return testing::AssertionFailure() << "no result"; - if (!get_zoom_settings_result->GetDouble("defaultZoomFactor", - default_zoom_factor)) { + absl::optional<double> default_zoom_factor_setting = + get_zoom_settings_result->FindDoubleKey("defaultZoomFactor"); + if (!default_zoom_factor_setting) { return testing::AssertionFailure() << "default zoom factor not found in result"; } + *default_zoom_factor = *default_zoom_factor_setting; return testing::AssertionSuccess(); } @@ -2178,7 +1957,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowsCreate_WithOpener) { // Navigate a tab to an extension page. GURL extension_url = extension->GetResourceURL("file.html"); - ui_test_utils::NavigateToURL(browser(), extension_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), extension_url)); content::WebContents* old_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -2253,7 +2032,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowsCreate_NoOpener) { // Navigate a tab to an extension page. GURL extension_url = extension->GetResourceURL("file.html"); - ui_test_utils::NavigateToURL(browser(), extension_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), extension_url)); content::WebContents* old_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -2296,7 +2075,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowsCreate_OpenerAndOrigin) { // Navigate a tab to an extension page. GURL extension_url = extension->GetResourceURL("file.html"); - ui_test_utils::NavigateToURL(browser(), extension_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), extension_url)); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -2386,7 +2165,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsUpdate_WebToAboutBlank) { GURL about_blank_url = GURL(url::kAboutBlankURL); // Navigate a tab to an extension page. - ui_test_utils::NavigateToURL(browser(), extension_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), extension_url)); content::WebContents* extension_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(extension_origin, @@ -2451,7 +2230,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsUpdate_WebToAboutNewTab) { GURL chrome_newtab_url = GURL("chrome://new-tab-page/"); // Navigate a tab to an extension page. - ui_test_utils::NavigateToURL(browser(), extension_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), extension_url)); content::WebContents* extension_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(extension_origin, @@ -2504,7 +2283,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabsUpdate_WebToNonWAR) { GURL non_war_url = extension_url; // Navigate a tab to an extension page. - ui_test_utils::NavigateToURL(browser(), extension_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), extension_url)); content::WebContents* extension_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(extension_origin, diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_util.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_util.cc index f4da46bff85..bf9778a53b4 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_util.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_util.cc @@ -3,11 +3,16 @@ // found in the LICENSE file. #include "chrome/browser/extensions/api/tabs/tabs_util.h" +#include "chromeos/ui/base/window_pin_type.h" namespace extensions { namespace tabs_util { -void SetLockedFullscreenState(Browser* browser, bool locked) {} +void SetLockedFullscreenState(Browser* browser, chromeos::WindowPinType style) { +} + +void SetLockedFullscreenStateFromExo(aura::Window* window, + chromeos::WindowPinType type) {} bool IsScreenshotRestricted(content::WebContents* web_contents) { return false; diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_util.h b/chromium/chrome/browser/extensions/api/tabs/tabs_util.h index 95de5f5eb56..9979f44dac9 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_util.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_util.h @@ -9,8 +9,14 @@ // then define an empty implementation in tabs_util.cc, and put the actual code // in eg. tabs_util_chromeos.cc. +#include "chromeos/ui/base/window_pin_type.h" + class Browser; +namespace aura { +class Window; +} + namespace content { class WebContents; } @@ -20,7 +26,12 @@ namespace tabs_util { // Set up the browser in the locked fullscreen state, and do any additional // necessary adjustments. -void SetLockedFullscreenState(Browser* browser, bool locked); +void SetLockedFullscreenState(Browser* browser, chromeos::WindowPinType type); + +// A call from a wayland/Exo client (ARC++, Lacros) is asking to put the system +// into a locked fullscreen state. +void SetLockedFullscreenStateFromExo(aura::Window* window, + chromeos::WindowPinType type); // Checks whether screenshot of |web_contents| is restricted due to Data Leak // Prevention policy. diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc index b737203127f..17e02f6b840 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc @@ -4,18 +4,10 @@ #include "chrome/browser/extensions/api/tabs/tabs_util.h" -#include "ash/public/cpp/assistant/assistant_state.h" -#include "base/metrics/histogram_macros.h" -#include "chrome/browser/ash/accessibility/accessibility_manager.h" -#include "chrome/browser/ash/arc/arc_util.h" -#include "chrome/browser/ash/arc/session/arc_session_manager.h" -#include "chrome/browser/ash/assistant/assistant_util.h" -#include "chrome/browser/ash/policy/dlp/dlp_content_manager.h" -#include "chrome/browser/ui/ash/chrome_capture_mode_delegate.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_command_controller.h" #include "chrome/browser/ui/browser_window.h" -#include "chromeos/ui/base/window_pin_type.h" #include "chromeos/ui/base/window_properties.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/web_contents.h" @@ -23,35 +15,79 @@ #include "ui/base/clipboard/clipboard.h" #include "ui/base/clipboard/clipboard_buffer.h" -namespace extensions { -namespace tabs_util { +#if !BUILDFLAG(IS_CHROMEOS_LACROS) +#include "ash/public/cpp/assistant/assistant_state.h" +#include "chrome/browser/ash/accessibility/accessibility_manager.h" +#include "chrome/browser/ash/arc/arc_util.h" +#include "chrome/browser/ash/arc/session/arc_session_manager.h" +#include "chrome/browser/ash/assistant/assistant_util.h" +#include "chrome/browser/ash/policy/dlp/dlp_content_manager.h" +#include "chrome/browser/ui/ash/capture_mode/chrome_capture_mode_delegate.h" +#else +#include "ui/platform_window/extensions/pinned_mode_extension.h" +#include "ui/views/widget/desktop_aura/desktop_window_tree_host_linux.h" +#endif -void SetLockedFullscreenState(Browser* browser, bool locked) { - UMA_HISTOGRAM_BOOLEAN("Extensions.LockedFullscreenStateRequest", locked); +namespace { - aura::Window* window = browser->window()->GetNativeWindow(); - // TRUSTED_PINNED is used here because that one locks the window fullscreen - // without allowing the user to exit (as opposed to regular PINNED). - window->SetProperty(chromeos::kWindowPinTypeKey, - locked ? chromeos::WindowPinType::kTrustedPinned - : chromeos::WindowPinType::kNone); +// This is the common code for either of the two SetLockedFullscreenState calls. +// It will make sure that all the non browser related tasks will be turned off/ +// cleared when the lock mode starts (or ends). +void SetLockedFullscreenStateCommon(Browser* browser, + aura::Window* window, + Profile* const profile, + chromeos::WindowPinType new_type) { + DCHECK(window); + const chromeos::WindowPinType previous_type = + window->GetProperty(chromeos::kWindowPinTypeKey); + // As this gets triggered from extensions, we might encounter this case. + if (previous_type == new_type) + return; - // Update the set of available browser commands. - browser->command_controller()->LockedFullscreenStateChanged(); + window->SetProperty(chromeos::kWindowPinTypeKey, new_type); - // Disable both screenshots and video screen captures via the capture mode - // feature. - ChromeCaptureModeDelegate::Get()->SetIsScreenCaptureLocked(locked); + if (browser) { + // This should only be called when called from inside the browser and not + // when called through Exo. +#if BUILDFLAG(IS_CHROMEOS_LACROS) + auto* pinned_mode_extension = + views::DesktopWindowTreeHostLinux::From(window->GetHost()) + ->GetPinnedModeExtension(); + if (new_type != chromeos::WindowPinType::kNone) { + pinned_mode_extension->Pin(/*trusted=*/ + new_type == + chromeos::WindowPinType::kTrustedPinned); + } else { + pinned_mode_extension->Unpin(); + } +#endif + + // Update the set of available browser commands. + browser->command_controller()->LockedFullscreenStateChanged(); + } + + const bool locked = new_type == chromeos::WindowPinType::kTrustedPinned; + const bool previous_locked = + previous_type == chromeos::WindowPinType::kTrustedPinned; + // Make sure that we only proceed if we switch from locked to unlocked or + // vice versa. + if (locked == previous_locked) + return; // Reset the clipboard and kill dev tools when entering or exiting locked // fullscreen (security concerns). ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); content::DevToolsAgentHost::DetachAllClients(); +#if !BUILDFLAG(IS_CHROMEOS_LACROS) + // TODO(crbug/1243104): This might be interesting for DLP to change. + // Disable both screenshots and video screen captures via the capture mode + // feature. + ChromeCaptureModeDelegate::Get()->SetIsScreenCaptureLocked(locked); + // Disable ARC while in the locked fullscreen mode. arc::ArcSessionManager* const arc_session_manager = arc::ArcSessionManager::Get(); - Profile* const profile = browser->profile(); if (arc_session_manager && arc::IsArcAllowedForProfile(profile)) { if (locked) { // Disable ARC, preserve data. @@ -67,11 +103,33 @@ void SetLockedFullscreenState(Browser* browser, bool locked) { chromeos::assistant::AssistantAllowedState::ALLOWED) { ash::AssistantState::Get()->NotifyLockedFullScreenStateChanged(locked); } +#endif +} + +} // namespace + +namespace extensions { +namespace tabs_util { + +void SetLockedFullscreenStateFromExo(aura::Window* window, + chromeos::WindowPinType type) { + SetLockedFullscreenStateCommon(nullptr, window, + ProfileManager::GetPrimaryUserProfile(), type); +} + +void SetLockedFullscreenState(Browser* browser, chromeos::WindowPinType type) { + SetLockedFullscreenStateCommon(browser, browser->window()->GetNativeWindow(), + browser->profile(), type); } bool IsScreenshotRestricted(content::WebContents* web_contents) { - return policy::DlpContentManager::Get()->IsScreenshotRestricted( +#if BUILDFLAG(IS_CHROMEOS_LACROS) + // TODO(crbug/1243104): This might be interesting for DLP to change. + return false; +#else + return policy::DlpContentManager::Get()->IsScreenshotApiRestricted( ScreenshotArea::CreateForWindow(web_contents->GetNativeView())); +#endif } } // namespace tabs_util diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc index cf013b6dfcc..a40c7a4a60d 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc @@ -134,10 +134,10 @@ bool WillDispatchWindowFocusedEvent( if (cant_cross_incognito || !visible_to_listener) { event->event_args->ClearList(); - event->event_args->AppendInteger(extension_misc::kUnknownWindowId); + event->event_args->Append(extension_misc::kUnknownWindowId); } else { event->event_args->ClearList(); - event->event_args->AppendInteger(window_id); + event->event_args->Append(window_id); } return true; } @@ -234,7 +234,7 @@ void WindowsEventRouter::OnWindowControllerRemoved( int window_id = window_controller->GetWindowId(); std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->AppendInteger(window_id); + args->Append(window_id); DispatchEvent(events::WINDOWS_ON_REMOVED, windows::OnRemoved::kEventName, window_controller, std::move(args)); } diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h index 71a694ef414..f214a5dfa7f 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h +++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.h @@ -49,6 +49,10 @@ class WindowsEventRouter : public AppWindowRegistry::Observer, public WindowControllerListObserver { public: explicit WindowsEventRouter(Profile* profile); + + WindowsEventRouter(const WindowsEventRouter&) = delete; + WindowsEventRouter& operator=(const WindowsEventRouter&) = delete; + ~WindowsEventRouter() override; // |window_controller| is NULL to indicate a focused window has lost focus. @@ -109,8 +113,6 @@ class WindowsEventRouter : public AppWindowRegistry::Observer, base::ScopedObservation<KeyWindowNotifier, KeyWindowNotifier::Observer> observed_key_window_notifier_{this}; #endif - - DISALLOW_COPY_AND_ASSIGN(WindowsEventRouter); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc index 3c28b910af9..dccf12ef235 100644 --- a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc +++ b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.cc @@ -100,7 +100,7 @@ void CrostiniStartupStatus::OnCrostiniConnected( void CrostiniStartupStatus::ShowProgressAtInterval() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); show_progress_timer_ = std::make_unique<base::RepeatingTimer>(); - show_progress_timer_->Start(FROM_HERE, base::TimeDelta::FromMilliseconds(300), + show_progress_timer_->Start(FROM_HERE, base::Milliseconds(300), base::BindRepeating( [](CrostiniStartupStatus* self) { self->spinner_index_++; @@ -111,9 +111,6 @@ void CrostiniStartupStatus::ShowProgressAtInterval() { void CrostiniStartupStatus::OnStageStarted(InstallerState stage) { stage_index_ = static_cast<int>(stage) + 1; - if (!verbose_) { - return; - } static base::NoDestructor<base::flat_map<InstallerState, std::string>> kStartStrings({ {InstallerState::kStart, @@ -139,7 +136,8 @@ void CrostiniStartupStatus::OnStageStarted(InstallerState stage) { l10n_util::GetStringUTF8( IDS_CROSTINI_TERMINAL_STATUS_START_CONTAINER)}, }); - const std::string& stage_string = (*kStartStrings)[stage]; + const std::string& stage_string = + verbose_ ? (*kStartStrings)[stage] : std::string(); PrintStage(kColor3Yellow, stage_string); } diff --git a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.h b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.h index 608e5e3ef1e..f2a0508b26e 100644 --- a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.h +++ b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status.h @@ -8,6 +8,7 @@ #include <string> #include "base/bind.h" +#include "base/gtest_prod_util.h" #include "base/memory/weak_ptr.h" #include "base/timer/timer.h" #include "chrome/browser/ash/crostini/crostini_manager.h" diff --git a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status_unittest.cc b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status_unittest.cc index f045fb597e6..8136589317d 100644 --- a/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status_unittest.cc +++ b/chromium/chrome/browser/extensions/api/terminal/crostini_startup_status_unittest.cc @@ -46,9 +46,18 @@ TEST_F(CrostiniStartupStatusTest, TestNotVerbose) { startup_status->OnCrostiniRestarted(crostini::CrostiniResult::SUCCESS); startup_status->OnCrostiniConnected(crostini::CrostiniResult::SUCCESS); - ASSERT_EQ(output_.size(), 1u); + ASSERT_EQ(output_.size(), 4u); + // Hide cursor, init progress. + EXPECT_EQ(output_[0], "\x1b[?25l\x1b[35m[ ] "); + + // CR, purple, forward 12, yellow, empty-stage. + EXPECT_EQ(output_[1], "\r\x1b[35m[\x1b[12C\x1b[K\x1b[33m "); + + // CR, purple, progress, forward 11, erase, yellow, empty-stage. + EXPECT_EQ(output_[2], "\r\x1b[35m[=\x1b[11C\x1b[K\x1b[33m "); + // CR, delete line, default color, show cursor. - EXPECT_EQ(output_[0], "\r\x1b[K\x1b[0m\x1b[?25h"); + EXPECT_EQ(output_[3], "\r\x1b[K\x1b[0m\x1b[?25h"); histogram_tester_.ExpectBucketCount("Crostini.AppLaunchResult", crostini::CrostiniResult::SUCCESS, 1); diff --git a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc index caf011ded9e..50e6a9f92c1 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc @@ -137,7 +137,7 @@ class TerminalTabHelper base::flat_set<std::string> terminal_ids_; }; -WEB_CONTENTS_USER_DATA_KEY_IMPL(TerminalTabHelper) +WEB_CONTENTS_USER_DATA_KEY_IMPL(TerminalTabHelper); // Copies the value of |switch_name| if present from |src| to |dst|. If not // present, uses |default_value| if nonempty. Returns the value set into |dst|. @@ -239,7 +239,7 @@ TerminalPrivateOpenTerminalProcessFunction:: ExtensionFunction::ResponseAction TerminalPrivateOpenTerminalProcessFunction::Run() { std::unique_ptr<OpenTerminalProcess::Params> params( - OpenTerminalProcess::Params::Create(*args_)); + OpenTerminalProcess::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); return OpenProcess(params->process_name, std::move(params->args)); @@ -454,7 +454,7 @@ TerminalPrivateOpenVmshellProcessFunction:: ExtensionFunction::ResponseAction TerminalPrivateOpenVmshellProcessFunction::Run() { std::unique_ptr<OpenVmshellProcess::Params> params( - OpenVmshellProcess::Params::Create(*args_)); + OpenVmshellProcess::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); // Only opens 'vmshell'. @@ -464,7 +464,7 @@ TerminalPrivateOpenVmshellProcessFunction::Run() { TerminalPrivateSendInputFunction::~TerminalPrivateSendInputFunction() = default; ExtensionFunction::ResponseAction TerminalPrivateSendInputFunction::Run() { - std::unique_ptr<SendInput::Params> params(SendInput::Params::Create(*args_)); + std::unique_ptr<SendInput::Params> params(SendInput::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (!TerminalTabHelper::ValidateTerminalId(GetSenderWebContents(), @@ -505,7 +505,7 @@ TerminalPrivateCloseTerminalProcessFunction:: ExtensionFunction::ResponseAction TerminalPrivateCloseTerminalProcessFunction::Run() { std::unique_ptr<CloseTerminalProcess::Params> params( - CloseTerminalProcess::Params::Create(*args_)); + CloseTerminalProcess::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (!TerminalTabHelper::ValidateTerminalId(GetSenderWebContents(), @@ -536,7 +536,7 @@ TerminalPrivateOnTerminalResizeFunction:: ExtensionFunction::ResponseAction TerminalPrivateOnTerminalResizeFunction::Run() { std::unique_ptr<OnTerminalResize::Params> params( - OnTerminalResize::Params::Create(*args_)); + OnTerminalResize::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (!TerminalTabHelper::ValidateTerminalId(GetSenderWebContents(), @@ -576,7 +576,7 @@ void TerminalPrivateOnTerminalResizeFunction::RespondOnUIThread(bool success) { TerminalPrivateAckOutputFunction::~TerminalPrivateAckOutputFunction() = default; ExtensionFunction::ResponseAction TerminalPrivateAckOutputFunction::Run() { - std::unique_ptr<AckOutput::Params> params(AckOutput::Params::Create(*args_)); + std::unique_ptr<AckOutput::Params> params(AckOutput::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); // Every running terminal page will call ackOutput(), but we should only react @@ -635,7 +635,7 @@ TerminalPrivateSetSettingsFunction::~TerminalPrivateSetSettingsFunction() = ExtensionFunction::ResponseAction TerminalPrivateSetSettingsFunction::Run() { std::unique_ptr<SetSettings::Params> params( - SetSettings::Params::Create(*args_)); + SetSettings::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); PrefService* service = diff --git a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h index 286f39e13ba..a249356d8b2 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h @@ -11,9 +11,9 @@ #include "chrome/browser/ash/crostini/crostini_simple_types.h" #include "chrome/browser/profiles/profile.h" +#include "components/value_store/value_store.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/extension_function.h" -#include "extensions/browser/value_store/value_store.h" class PrefChangeRegistrar; @@ -24,6 +24,10 @@ class CrostiniStartupStatus; class TerminalPrivateAPI : public BrowserContextKeyedAPI { public: explicit TerminalPrivateAPI(content::BrowserContext* context); + + TerminalPrivateAPI(const TerminalPrivateAPI&) = delete; + TerminalPrivateAPI& operator=(const TerminalPrivateAPI&) = delete; + ~TerminalPrivateAPI() override; // BrowserContextKeyedAPI implementation. @@ -38,8 +42,6 @@ class TerminalPrivateAPI : public BrowserContextKeyedAPI { content::BrowserContext* const context_; std::unique_ptr<PrefChangeRegistrar> pref_change_registrar_; - - DISALLOW_COPY_AND_ASSIGN(TerminalPrivateAPI); }; // Opens new terminal process. Returns the new terminal id. diff --git a/chromium/chrome/browser/extensions/api/terminal/terminal_private_browsertest.cc b/chromium/chrome/browser/extensions/api/terminal/terminal_private_browsertest.cc index 5602ebbe899..011d9573e0f 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_browsertest.cc @@ -17,6 +17,11 @@ namespace extensions { class TerminalPrivateBrowserTest : public InProcessBrowserTest { + public: + TerminalPrivateBrowserTest(const TerminalPrivateBrowserTest&) = delete; + TerminalPrivateBrowserTest& operator=(const TerminalPrivateBrowserTest&) = + delete; + protected: TerminalPrivateBrowserTest() = default; @@ -28,14 +33,11 @@ class TerminalPrivateBrowserTest : public InProcessBrowserTest { /*world_id=*/1); EXPECT_EQ(eval_result.value.GetString(), expected); } - - private: - DISALLOW_COPY_AND_ASSIGN(TerminalPrivateBrowserTest); }; IN_PROC_BROWSER_TEST_F(TerminalPrivateBrowserTest, OpenTerminalProcessChecks) { - ui_test_utils::NavigateToURL( - browser(), GURL("chrome-untrusted://terminal/html/terminal.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL("chrome-untrusted://terminal/html/terminal.html"))); const std::string script = R"(new Promise((resolve) => { chrome.terminalPrivate.openVmshellProcess([], () => { diff --git a/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc b/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc index b885e0bfe6e..c672b319172 100644 --- a/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc +++ b/chromium/chrome/browser/extensions/api/top_sites/top_sites_apitest.cc @@ -79,9 +79,8 @@ IN_PROC_BROWSER_TEST_F(TopSitesExtensionTest, GetTopSites) { std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( get_top_sites_function.get(), "[]", browser())); - base::ListValue* list; - ASSERT_TRUE(result->GetAsList(&list)); - EXPECT_GE(list->GetSize(), top_sites_prepopulated_pages_size()); + ASSERT_TRUE(result->is_list()); + EXPECT_GE(result->GetList().size(), top_sites_prepopulated_pages_size()); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/video_capture/video_capture_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/video_capture/video_capture_apitest_chromeos.cc new file mode 100644 index 00000000000..8ba2af40f6d --- /dev/null +++ b/chromium/chrome/browser/extensions/api/video_capture/video_capture_apitest_chromeos.cc @@ -0,0 +1,107 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include <memory> + +#include "base/command_line.h" +#include "base/memory/ptr_util.h" +#include "chrome/browser/apps/platform_apps/app_browsertest_util.h" +#include "chrome/browser/ash/app_mode/kiosk_app_manager.h" +#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h" +#include "chrome/browser/ash/ownership/fake_owner_settings_service.h" +#include "chrome/browser/ash/settings/scoped_cros_settings_test_helper.h" +#include "chrome/browser/extensions/extension_apitest.h" +#include "components/account_id/account_id.h" +#include "components/user_manager/scoped_user_manager.h" +#include "content/public/test/browser_test.h" +#include "media/base/media_switches.h" +#include "testing/gmock/include/gmock/gmock.h" + +namespace { +const char kTestingAppId[] = "lplgglkemdojicmnmlcfoaokgcobcpei"; +} // namespace + +namespace extensions { +namespace { + +// This class contains API tests related to the "videoCapture" permission. +class VideoCaptureApiTestChromeOs : public PlatformAppBrowserTest { + public: + VideoCaptureApiTestChromeOs() : settings_helper_(false) {} + ~VideoCaptureApiTestChromeOs() override {} + + void SetUpOnMainThread() override { + PlatformAppBrowserTest::SetUpOnMainThread(); + settings_helper_.ReplaceDeviceSettingsProviderWithStub(); + owner_settings_service_ = + settings_helper_.CreateOwnerSettingsService(browser()->profile()); + // Verify fake devices are enabled. This is necessary to make sure there is + // at least one device in the system. Otherwise, this test would fail on + // machines without physical media devices since getUserMedia fails early in + // those cases. + EXPECT_TRUE(base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kUseFakeDeviceForMediaStream)); + } + + void TearDownOnMainThread() override { + owner_settings_service_.reset(); + settings_helper_.RestoreRealDeviceSettingsProvider(); + user_manager_enabler_.reset(); + PlatformAppBrowserTest::TearDownOnMainThread(); + } + + protected: + void EnterKioskSession() { + auto fake_user_manager = std::make_unique<ash::FakeChromeUserManager>(); + auto* fake_user_manager_ptr = fake_user_manager.get(); + user_manager_enabler_ = std::make_unique<user_manager::ScopedUserManager>( + std::move(fake_user_manager)); + const AccountId kiosk_account_id( + AccountId::FromUserEmail("kiosk@foobar.com")); + fake_user_manager_ptr->AddKioskAppUser(kiosk_account_id); + fake_user_manager_ptr->LoginUser(kiosk_account_id); + } + + void SetAutoLaunchApp() { + manager()->AddApp(kTestingAppId, owner_settings_service_.get()); + manager()->SetAutoLaunchApp(kTestingAppId, owner_settings_service_.get()); + manager()->SetAppWasAutoLaunchedWithZeroDelay(kTestingAppId); + } + + ash::KioskAppManager* manager() const { return ash::KioskAppManager::Get(); } + + std::unique_ptr<user_manager::ScopedUserManager> user_manager_enabler_; + + ash::ScopedCrosSettingsTestHelper settings_helper_; + std::unique_ptr<chromeos::FakeOwnerSettingsService> owner_settings_service_; +}; + +IN_PROC_BROWSER_TEST_F(VideoCaptureApiTestChromeOs, + CameraPanTiltZoom_NoKioskSession) { + ASSERT_TRUE(RunExtensionTest( + "api_test/video_capture/camera_pan_tilt_zoom_no_kiosk_session", + {.launch_as_platform_app = true})) + << message_; +} + +IN_PROC_BROWSER_TEST_F(VideoCaptureApiTestChromeOs, + CameraPanTiltZoom_KioskSessionOnly) { + EnterKioskSession(); + ASSERT_TRUE( + RunExtensionTest("api_test/video_capture/" + "camera_pan_tilt_zoom_kiosk_session_only", + {.launch_as_platform_app = true})) + << message_; +} + +IN_PROC_BROWSER_TEST_F(VideoCaptureApiTestChromeOs, CameraPanTiltZoom) { + EnterKioskSession(); + SetAutoLaunchApp(); + ASSERT_TRUE(RunExtensionTest("api_test/video_capture/camera_pan_tilt_zoom", + {.launch_as_platform_app = true})) + << message_; +} + +} // namespace +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc index 9458bffed5b..30608b00c99 100644 --- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc +++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.cc @@ -35,7 +35,7 @@ #include "media/audio/audio_system.h" #include "ui/aura/event_injector.h" #include "ui/aura/window_tree_host.h" -#include "ui/base/ime/chromeos/ime_bridge.h" +#include "ui/base/ime/ash/ime_bridge.h" #include "ui/base/ime/constants.h" #include "ui/base/ime/input_method.h" #include "ui/base/ime/text_input_client.h" @@ -554,6 +554,12 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices( "assistiveAutoCorrect", base::FeatureList::IsEnabled(chromeos::features::kAssistAutoCorrect))); features.Append(GenerateFeatureFlag( + "systemchinesephysicaltyping", + chromeos::features::IsSystemChinesePhysicalTypingEnabled())); + features.Append(GenerateFeatureFlag( + "systemkoreanphysicaltyping", + chromeos::features::IsSystemKoreanPhysicalTypingEnabled())); + features.Append(GenerateFeatureFlag( "systemlatinphysicaltyping", chromeos::features::IsSystemLatinPhysicalTypingEnabled())); features.Append(GenerateFeatureFlag( @@ -566,6 +572,9 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices( "multipaste-suggestion", base::FeatureList::IsEnabled( chromeos::features::kVirtualKeyboardMultipasteSuggestion))); + features.Append(GenerateFeatureFlag( + "imeoptionsinsettings", + base::FeatureList::IsEnabled(chromeos::features::kImeOptionsInSettings))); results->SetKey("features", std::move(features)); diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h index ebc19270f15..6ac71268597 100644 --- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h +++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/chrome_virtual_keyboard_delegate.h @@ -27,6 +27,11 @@ class ChromeVirtualKeyboardDelegate public: explicit ChromeVirtualKeyboardDelegate( content::BrowserContext* browser_context); + + ChromeVirtualKeyboardDelegate(const ChromeVirtualKeyboardDelegate&) = delete; + ChromeVirtualKeyboardDelegate& operator=( + const ChromeVirtualKeyboardDelegate&) = delete; + ~ChromeVirtualKeyboardDelegate() override; // TODO(oka): Create ChromeVirtualKeyboardPrivateDelegate class and move all @@ -81,7 +86,6 @@ class ChromeVirtualKeyboardDelegate std::unique_ptr<media::AudioSystem> audio_system_; base::WeakPtr<ChromeVirtualKeyboardDelegate> weak_this_; base::WeakPtrFactory<ChromeVirtualKeyboardDelegate> weak_factory_{this}; - DISALLOW_COPY_AND_ASSIGN(ChromeVirtualKeyboardDelegate); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/virtual_keyboard_private_apitest.cc b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/virtual_keyboard_private_apitest.cc index ca27eb21c88..899c6f755a8 100644 --- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/virtual_keyboard_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/virtual_keyboard_private_apitest.cc @@ -63,8 +63,8 @@ class VirtualKeyboardPrivateApiTest : public extensions::ExtensionApiTest { protected: void CopyHtmlItem() { // Load the web page which contains images and text. - ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("/image-and-text.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/image-and-text.html"))); // Select one part of the web page. Wait until the selection region updates. // Then copy the selected part to clipboard. diff --git a/chromium/chrome/browser/extensions/api/web_authentication_proxy/OWNERS b/chromium/chrome/browser/extensions/api/web_authentication_proxy/OWNERS new file mode 100644 index 00000000000..dd5ad77ad56 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/web_authentication_proxy/OWNERS @@ -0,0 +1 @@ +file://device/fido/OWNERS diff --git a/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_api.cc b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_api.cc new file mode 100644 index 00000000000..b45670b9096 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_api.cc @@ -0,0 +1,33 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_api.h" + +#include "chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.h" +#include "chrome/common/extensions/api/web_authentication_proxy.h" + +namespace extensions { + +WebAuthenticationProxyCompleteIsUvpaaRequestFunction:: + WebAuthenticationProxyCompleteIsUvpaaRequestFunction() = default; +WebAuthenticationProxyCompleteIsUvpaaRequestFunction:: + ~WebAuthenticationProxyCompleteIsUvpaaRequestFunction() = default; + +ExtensionFunction::ResponseAction +WebAuthenticationProxyCompleteIsUvpaaRequestFunction::Run() { + auto params = + api::web_authentication_proxy::CompleteIsUvpaaRequest::Params::Create( + args()); + EXTENSION_FUNCTION_VALIDATE(params.get()); + WebAuthenticationProxyService* proxy_service = + WebAuthenticationProxyServiceFactory::GetForBrowserContext( + browser_context()); + if (!proxy_service->CompleteIsUvpaaRequest(params->details.request_id, + params->details.is_uvpaa)) { + return RespondNow(Error("Invalid request id")); + } + return RespondNow(NoArguments()); +} + +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_api.h b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_api.h new file mode 100644 index 00000000000..a9b5311247c --- /dev/null +++ b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_api.h @@ -0,0 +1,30 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_EXTENSIONS_API_WEB_AUTHENTICATION_PROXY_WEB_AUTHENTICATION_PROXY_API_H_ +#define CHROME_BROWSER_EXTENSIONS_API_WEB_AUTHENTICATION_PROXY_WEB_AUTHENTICATION_PROXY_API_H_ + +#include "extensions/browser/extension_function.h" + +namespace extensions { + +// WebAuthenticationProxyCompleteIsUvpaaRequestFunction implements +// the chrome.webAuthenticationProxy.completeIsUvpaaRequest() API. +class WebAuthenticationProxyCompleteIsUvpaaRequestFunction + : public ExtensionFunction { + public: + WebAuthenticationProxyCompleteIsUvpaaRequestFunction(); + + protected: + ~WebAuthenticationProxyCompleteIsUvpaaRequestFunction() override; + + // ExtensionFunction: + ResponseAction Run() override; + DECLARE_EXTENSION_FUNCTION("webAuthenticationProxy.completeIsUvpaaRequest", + WEB_AUTHENTICATION_PROXY_COMPLETE_ISUVPAA_REQUEST) +}; + +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_WEB_AUTHENTICATION_PROXY_WEB_AUTHENTICATION_PROXY_API_H_ diff --git a/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_apitest.cc b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_apitest.cc new file mode 100644 index 00000000000..425ed6652c1 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_apitest.cc @@ -0,0 +1,59 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/extensions/extension_apitest.h" +#include "chrome/test/base/ui_test_utils.h" +#include "content/public/test/browser_test.h" +#include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/result_catcher.h" +#include "net/test/embedded_test_server/embedded_test_server.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace extensions { +namespace { + +class WebAuthenticationProxyApiTest : public ExtensionApiTest { + protected: + void SetUpOnMainThread() override { + ExtensionApiTest::SetUpOnMainThread(); + test_data_dir_ = test_data_dir_.AppendASCII("web_authentication_proxy"); + https_test_server_.ServeFilesFromDirectory(test_data_dir_); + ASSERT_TRUE(https_test_server_.Start()); + } + + net::EmbeddedTestServer https_test_server_{ + net::EmbeddedTestServer::TYPE_HTTPS}; +}; + +IN_PROC_BROWSER_TEST_F(WebAuthenticationProxyApiTest, IsUVPAA) { + // Load the extension and wait for its proxy event handler to be installed. + ExtensionTestMessageListener ready_listener("ready", false); + ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("is_uvpaa"))) + << message_; + ASSERT_TRUE(ready_listener.WaitUntilSatisfied()); + + // Navigate to a new URL and check that the proxying works. + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), https_test_server_.GetURL("/is_uvpaa/page.html"))); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + ASSERT_TRUE(web_contents); + + // The extension sets the result for isUvpaa to `false` and `true` for + // two different requests. + for (const bool expected : {false, true}) { + // The extension verifies it receives the proper requests. + ResultCatcher result_catcher; + bool is_uvpaa = + content::EvalJs(web_contents, + "PublicKeyCredential." + "isUserVerifyingPlatformAuthenticatorAvailable();") + .ExtractBool(); + EXPECT_EQ(is_uvpaa, expected); + EXPECT_TRUE(result_catcher.GetNextResult()) << result_catcher.message(); + } +} + +} // namespace +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.cc b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.cc new file mode 100644 index 00000000000..b7086c7df7e --- /dev/null +++ b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.cc @@ -0,0 +1,104 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.h" + +#include <limits> + +#include "base/rand_util.h" +#include "chrome/common/extensions/api/web_authentication_proxy.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "extensions/browser/event_router.h" +#include "extensions/browser/event_router_factory.h" +#include "extensions/browser/extension_event_histogram_value.h" +#include "extensions/browser/extension_function.h" +#include "extensions/browser/extension_function_histogram_value.h" + +namespace extensions { + +namespace { +int32_t NewRequestId() { + return base::RandGenerator(std::numeric_limits<uint32_t>::max()) + 1; +} +} // namespace + +WebAuthenticationProxyService::WebAuthenticationProxyService( + content::BrowserContext* browser_context) + : event_router_(EventRouter::Get(browser_context)) {} + +WebAuthenticationProxyService::~WebAuthenticationProxyService() = default; + +bool WebAuthenticationProxyService::CompleteIsUvpaaRequest(EventId event_id, + bool is_uvpaa) { + auto callback_it = pending_is_uvpaa_callbacks_.find(event_id); + if (callback_it == pending_is_uvpaa_callbacks_.end()) { + return false; + } + IsUvpaaCallback callback = std::move(callback_it->second); + pending_is_uvpaa_callbacks_.erase(callback_it); + std::move(callback).Run(is_uvpaa); + return true; +} + +bool WebAuthenticationProxyService::IsActive() { + return event_router_->HasEventListener( + api::web_authentication_proxy::OnIsUvpaaRequest::kEventName); +} + +void WebAuthenticationProxyService::SignalIsUvpaaRequest( + IsUvpaaCallback callback) { + int32_t request_id = NewRequestId(); + // Technically, this could spin forever if there are 4 billion active + // requests. However, there's no real risk to this happening (no security or + // DOS concerns). + while (pending_is_uvpaa_callbacks_.find(request_id) != + pending_is_uvpaa_callbacks_.end()) { + request_id = NewRequestId(); + } + pending_is_uvpaa_callbacks_.emplace(request_id, std::move(callback)); + base::Value args(base::Value::Type::LIST); + args.Append(request_id); + event_router_->BroadcastEvent(std::make_unique<Event>( + events::WEB_AUTHENTICATION_PROXY_ON_ISUVPAA_REQUEST, + api::web_authentication_proxy::OnIsUvpaaRequest::kEventName, + std::move(args).TakeList())); +} + +WebAuthenticationProxyServiceFactory* +WebAuthenticationProxyServiceFactory::GetInstance() { + static base::NoDestructor<WebAuthenticationProxyServiceFactory> instance; + return instance.get(); +} + +WebAuthenticationProxyServiceFactory::WebAuthenticationProxyServiceFactory() + : BrowserContextKeyedServiceFactory( + "WebAuthentcationProxyService", + BrowserContextDependencyManager::GetInstance()) { + DependsOn(EventRouterFactory::GetInstance()); +} + +WebAuthenticationProxyServiceFactory::~WebAuthenticationProxyServiceFactory() = + default; + +WebAuthenticationProxyService* +WebAuthenticationProxyServiceFactory::GetForBrowserContext( + content::BrowserContext* context) { + return static_cast<WebAuthenticationProxyService*>( + WebAuthenticationProxyServiceFactory::GetInstance() + ->GetServiceForBrowserContext(context, true)); +} + +KeyedService* WebAuthenticationProxyServiceFactory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + return new WebAuthenticationProxyService(context); +} + +content::BrowserContext* +WebAuthenticationProxyServiceFactory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return context; +} + +} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.h b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.h new file mode 100644 index 00000000000..df7238cfea1 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/web_authentication_proxy/web_authentication_proxy_service.h @@ -0,0 +1,78 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_EXTENSIONS_API_WEB_AUTHENTICATION_PROXY_WEB_AUTHENTICATION_PROXY_SERVICE_H_ +#define CHROME_BROWSER_EXTENSIONS_API_WEB_AUTHENTICATION_PROXY_WEB_AUTHENTICATION_PROXY_SERVICE_H_ + +#include "base/no_destructor.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/core/keyed_service.h" +#include "content/public/browser/web_authentication_request_proxy.h" + +namespace content { +class BrowserContext; +} // namespace content + +namespace extensions { + +class EventRouter; + +// WebAuthenticationProxyService is an implementation of the +// content::WebAuthenticationRequestProxy interface that integrates Chrome's Web +// Authentication API with the webAuthenticationProxy extension API. +class WebAuthenticationProxyService + : public content::WebAuthenticationRequestProxy, + public KeyedService { + public: + using EventId = int32_t; + + // CompleteIsUvpaaRequest injects the result for the + // `events::WEB_AUTHENTICATION_PROXY_ON_ISUVPAA_REQUEST` event with + // `event_id`. `is_uvpaa` is the result to be returned to the original caller + // of the PublicKeyCredential.IsUserPlatformAuthenticatorAvailable(). + // + // Returns whether an event matching `event_id` was found. + bool CompleteIsUvpaaRequest(EventId event_id, bool is_uvpaa); + + private: + friend class WebAuthenticationProxyServiceFactory; + + explicit WebAuthenticationProxyService( + content::BrowserContext* browser_context); + ~WebAuthenticationProxyService() override; + + // content::WebAuthnRequestProxy: + bool IsActive() override; + void SignalIsUvpaaRequest(IsUvpaaCallback callback) override; + + EventRouter* event_router_ = nullptr; + std::map<EventId, IsUvpaaCallback> pending_is_uvpaa_callbacks_; +}; + +// WebAuthenticationProxyServiceFactory creates instances of +// WebAuthenticationProxyService for a given BrowserContext. +class WebAuthenticationProxyServiceFactory + : public BrowserContextKeyedServiceFactory { + public: + static WebAuthenticationProxyServiceFactory* GetInstance(); + + static WebAuthenticationProxyService* GetForBrowserContext( + content::BrowserContext* context); + + private: + friend class base::NoDestructor<WebAuthenticationProxyServiceFactory>; + + WebAuthenticationProxyServiceFactory(); + ~WebAuthenticationProxyServiceFactory() override; + + // BrowserContextKeyedServiceFactory: + KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const override; + content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const override; +}; + +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_WEB_AUTHENTICATION_PROXY_WEB_AUTHENTICATION_PROXY_SERVICE_H_ diff --git a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc index 7155e368be1..01db3e0d633 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.cc @@ -32,9 +32,10 @@ const char* const kValidSchemes[] = { // static bool FrameNavigationState::allow_extension_scheme_ = false; -RENDER_DOCUMENT_HOST_USER_DATA_KEY_IMPL(FrameNavigationState) +RENDER_DOCUMENT_HOST_USER_DATA_KEY_IMPL(FrameNavigationState); -FrameNavigationState::FrameNavigationState(content::RenderFrameHost*) {} +FrameNavigationState::FrameNavigationState(content::RenderFrameHost* rfh) + : content::RenderDocumentHostUserData<FrameNavigationState>(rfh) {} FrameNavigationState::~FrameNavigationState() = default; // static diff --git a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h index 0c3d8a38756..fcb47a5ff44 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h +++ b/chromium/chrome/browser/extensions/api/web_navigation/frame_navigation_state.h @@ -24,6 +24,9 @@ namespace extensions { class FrameNavigationState : public content::RenderDocumentHostUserData<FrameNavigationState> { public: + FrameNavigationState(const FrameNavigationState&) = delete; + FrameNavigationState& operator=(const FrameNavigationState&) = delete; + ~FrameNavigationState() override; // True if in general webNavigation events may be sent for the given URL. @@ -82,8 +85,6 @@ class FrameNavigationState // If true, also allow events from chrome-extension:// URLs. static bool allow_extension_scheme_; - - DISALLOW_COPY_AND_ASSIGN(FrameNavigationState); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc index d75cdafc6c3..d18d496e962 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.cc @@ -435,21 +435,21 @@ void WebNavigationTabObserver::RenderFrameHostPendingDeletion( // The |pending_delete_rfh| and its children are now pending deletion. // Stop tracking them. - web_contents()->ForEachFrame(base::BindRepeating( - [](content::RenderFrameHost* pending_delete_rfh, - WebNavigationTabObserver* observer, + pending_delete_rfh->ForEachRenderFrameHost(base::BindRepeating( + [](WebNavigationTabObserver* observer, content::RenderFrameHost* render_frame_host) { - if (render_frame_host == pending_delete_rfh || - render_frame_host->IsDescendantOf(pending_delete_rfh)) { + auto* navigation_state = + FrameNavigationState::GetForCurrentDocument(render_frame_host); + if (navigation_state) { observer->RenderFrameDeleted(render_frame_host); FrameNavigationState::DeleteForCurrentDocument(render_frame_host); } }, - pending_delete_rfh, this)); + this)); } ExtensionFunction::ResponseAction WebNavigationGetFrameFunction::Run() { - std::unique_ptr<GetFrame::Params> params(GetFrame::Params::Create(*args_)); + std::unique_ptr<GetFrame::Params> params(GetFrame::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->details.tab_id; int frame_id = params->details.frame_id; @@ -492,7 +492,7 @@ ExtensionFunction::ResponseAction WebNavigationGetFrameFunction::Run() { ExtensionFunction::ResponseAction WebNavigationGetAllFramesFunction::Run() { std::unique_ptr<GetAllFrames::Params> params( - GetAllFrames::Params::Create(*args_)); + GetAllFrames::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); int tab_id = params->details.tab_id; @@ -577,6 +577,6 @@ void WebNavigationAPI::OnListenerAdded(const EventListenerInfo& details) { EventRouter::Get(browser_context_)->UnregisterObserver(this); } -WEB_CONTENTS_USER_DATA_KEY_IMPL(WebNavigationTabObserver) +WEB_CONTENTS_USER_DATA_KEY_IMPL(WebNavigationTabObserver); } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h index 19fc05175fb..16295ecba5a 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api.h @@ -33,6 +33,9 @@ class WebNavigationTabObserver : public content::WebContentsObserver, public content::WebContentsUserData<WebNavigationTabObserver> { public: + WebNavigationTabObserver(const WebNavigationTabObserver&) = delete; + WebNavigationTabObserver& operator=(const WebNavigationTabObserver&) = delete; + ~WebNavigationTabObserver() override; // Returns the object for the given |web_contents|. @@ -86,8 +89,6 @@ class WebNavigationTabObserver std::unique_ptr<Event> pending_on_before_navigate_event_; WEB_CONTENTS_USER_DATA_KEY_DECL(); - - DISALLOW_COPY_AND_ASSIGN(WebNavigationTabObserver); }; // Tracks new tab navigations and routes them as events to the extension system. @@ -95,6 +96,10 @@ class WebNavigationEventRouter : public TabStripModelObserver, public BrowserTabStripTrackerDelegate { public: explicit WebNavigationEventRouter(Profile* profile); + + WebNavigationEventRouter(const WebNavigationEventRouter&) = delete; + WebNavigationEventRouter& operator=(const WebNavigationEventRouter&) = delete; + ~WebNavigationEventRouter() override; // Router level handler for the creation of WebContents. Stores information @@ -114,6 +119,10 @@ class WebNavigationEventRouter : public TabStripModelObserver, class PendingWebContents : public content::WebContentsObserver { public: PendingWebContents(); + + PendingWebContents(const PendingWebContents&) = delete; + PendingWebContents& operator=(const PendingWebContents&) = delete; + ~PendingWebContents() override; void Set(int source_tab_id, @@ -144,8 +153,6 @@ class WebNavigationEventRouter : public TabStripModelObserver, content::WebContents* target_web_contents_ = nullptr; GURL target_url_; base::OnceCallback<void(content::WebContents*)> on_destroy_; - - DISALLOW_COPY_AND_ASSIGN(PendingWebContents); }; // BrowserTabStripTrackerDelegate implementation. @@ -172,8 +179,6 @@ class WebNavigationEventRouter : public TabStripModelObserver, Profile* profile_; BrowserTabStripTracker browser_tab_strip_tracker_; - - DISALLOW_COPY_AND_ASSIGN(WebNavigationEventRouter); }; // API function that returns the state of a given frame. @@ -195,6 +200,10 @@ class WebNavigationAPI : public BrowserContextKeyedAPI, public extensions::EventRouter::Observer { public: explicit WebNavigationAPI(content::BrowserContext* context); + + WebNavigationAPI(const WebNavigationAPI&) = delete; + WebNavigationAPI& operator=(const WebNavigationAPI&) = delete; + ~WebNavigationAPI() override; // KeyedService implementation. @@ -221,8 +230,6 @@ class WebNavigationAPI : public BrowserContextKeyedAPI, // Created lazily upon OnListenerAdded. std::unique_ptr<WebNavigationEventRouter> web_navigation_event_router_; - - DISALLOW_COPY_AND_ASSIGN(WebNavigationAPI); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc index c242c31064d..04630f3016e 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_apitest.cc @@ -81,6 +81,11 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, browser->tab_strip_model()->AddObserver(this); } + DelayLoadStartAndExecuteJavascript( + const DelayLoadStartAndExecuteJavascript&) = delete; + DelayLoadStartAndExecuteJavascript& operator=( + const DelayLoadStartAndExecuteJavascript&) = delete; + ~DelayLoadStartAndExecuteJavascript() override {} // TabStripModelObserver: @@ -173,8 +178,6 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, bool has_user_gesture_ = false; bool script_was_executed_ = false; content::RenderFrameHost* rfh_ = nullptr; - - DISALLOW_COPY_AND_ASSIGN(DelayLoadStartAndExecuteJavascript); }; // Handles requests for URLs with paths of "/test*" sent to the test server, so @@ -195,7 +198,8 @@ std::unique_ptr<net::test_server::HttpResponse> HandleTestRequest( class WebNavigationApiTest : public ExtensionApiTest { public: - WebNavigationApiTest() { + explicit WebNavigationApiTest(ContextType context_type = ContextType::kNone) + : ExtensionApiTest(context_type) { embedded_test_server()->RegisterRequestHandler( base::BindRepeating(&HandleTestRequest)); } @@ -240,7 +244,7 @@ class WebNavigationApiTestWithContextType : public WebNavigationApiTest, public testing::WithParamInterface<ContextType> { public: - WebNavigationApiTestWithContextType() = default; + WebNavigationApiTestWithContextType() : WebNavigationApiTest(GetParam()) {} ~WebNavigationApiTestWithContextType() override = default; WebNavigationApiTestWithContextType( const WebNavigationApiTestWithContextType&) = delete; @@ -250,19 +254,17 @@ class WebNavigationApiTestWithContextType protected: bool RunTest(const char* name, bool allow_in_incognito = false) WARN_UNUSED_RESULT { - return RunExtensionTest( - name, {}, - {.allow_in_incognito = allow_in_incognito, - .load_as_service_worker = GetParam() == ContextType::kServiceWorker}); + return RunExtensionTest(name, {}, + {.allow_in_incognito = allow_in_incognito}); } }; IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, Api) { - ASSERT_TRUE(RunTest("webnavigation/api")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/api")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, GetFrame) { - ASSERT_TRUE(RunTest("webnavigation/getFrame")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/getFrame")) << message_; } INSTANTIATE_TEST_SUITE_P(PersistentBackground, @@ -273,20 +275,27 @@ INSTANTIATE_TEST_SUITE_P(ServiceWorker, testing::Values(ContextType::kServiceWorker)); IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, ClientRedirect) { - ASSERT_TRUE(RunTest("webnavigation/clientRedirect")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/clientRedirect")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, ServerRedirect) { ASSERT_TRUE(StartEmbeddedTestServer()); - ASSERT_TRUE(RunTest("webnavigation/serverRedirect")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/serverRedirect")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, FormSubmission) { ASSERT_TRUE(StartEmbeddedTestServer()); - ASSERT_TRUE(RunTest("webnavigation/formSubmission")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/formSubmission")) << message_; } -IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, Download) { +// TODO(https://crbug.com/1250311): +// WebNavigationApiTestWithContextType.Download test is flaky. +#if defined(OS_WIN) +#define MAYBE_Download DISABLED_Download +#else +#define MAYBE_Download Download +#endif +IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, MAYBE_Download) { ASSERT_TRUE(StartEmbeddedTestServer()); content::DownloadManager* download_manager = browser()->profile()->GetDownloadManager(); @@ -306,7 +315,8 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, content::RenderProcessHost::SetMaxRendererProcessCount(1); // Wait for the extension to set itself up and return control to us. - ASSERT_TRUE(RunTest("webnavigation/serverRedirectSingleProcess")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/serverRedirectSingleProcess")) + << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(tab)); @@ -317,13 +327,13 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, "webnavigation/serverRedirectSingleProcess/a.html", embedded_test_server()->port())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); url = GURL(base::StringPrintf( "http://www.b.com:%u/server-redirect?http://www.b.com:%u/test", embedded_test_server()->port(), embedded_test_server()->port())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } @@ -344,31 +354,31 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiBackForwardCacheTest, ForwardBack) { #define MAYBE_IFrame IFrame #endif IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, MAYBE_IFrame) { - ASSERT_TRUE(RunTest("webnavigation/iframe")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/iframe")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, SrcDoc) { - ASSERT_TRUE(RunTest("webnavigation/srcdoc")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/srcdoc")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, OpenTab) { - ASSERT_TRUE(RunTest("webnavigation/openTab")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/openTab")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, ReferenceFragment) { - ASSERT_TRUE(RunTest("webnavigation/referenceFragment")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/referenceFragment")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, SimpleLoad) { - ASSERT_TRUE(RunTest("webnavigation/simpleLoad")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/simpleLoad")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, Failures) { - ASSERT_TRUE(RunTest("webnavigation/failures")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/failures")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, FilteredTest) { - ASSERT_TRUE(RunTest("webnavigation/filtered")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/filtered")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, UserAction) { @@ -376,7 +386,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, UserAction) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. - ASSERT_TRUE(RunTest("webnavigation/userAction")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/userAction")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(tab)); @@ -389,7 +399,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, UserAction) { GURL url = extension->GetResourceURL( "a.html?" + base::NumberToString(embedded_test_server()->port())); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // This corresponds to "Open link in new tab". content::ContextMenuParams params; @@ -400,11 +410,10 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, UserAction) { // Get the child frame, which will be the one associated with the context // menu. - std::vector<content::RenderFrameHost*> frames = tab->GetAllFrames(); - EXPECT_EQ(2UL, frames.size()); - EXPECT_TRUE(frames[1]->GetParent()); + content::RenderFrameHost* child_frame = ChildFrameAt(tab, 0); + ASSERT_TRUE(child_frame); - TestRenderViewContextMenu menu(frames[1], params); + TestRenderViewContextMenu menu(child_frame, params); menu.Init(); menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB, 0); @@ -413,7 +422,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, UserAction) { IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, RequestOpenTab) { // Wait for the extension to set itself up and return control to us. - ASSERT_TRUE(RunTest("webnavigation/requestOpenTab")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/requestOpenTab")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(tab)); @@ -425,7 +434,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, RequestOpenTab) { ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL("a.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // There's a link on a.html. Middle-click on it to open it in a new tab. blink::WebMouseEvent mouse_event( @@ -448,7 +457,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, TargetBlank) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. - ASSERT_TRUE(RunTest("webnavigation/targetBlank")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/targetBlank")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(tab)); @@ -484,7 +493,9 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. - ASSERT_TRUE(RunTest("webnavigation/targetBlank", true)) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/targetBlank", {}, + {.allow_in_incognito = true})) + << message_; ResultCatcher catcher; @@ -513,10 +524,10 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, History) { - ASSERT_TRUE(RunTest("webnavigation/history")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/history")) << message_; } -IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, CrossProcess) { +IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, CrossProcess) { ASSERT_TRUE(StartEmbeddedTestServer()); LoadExtension(test_data_dir_.AppendASCII("webnavigation").AppendASCII("app")); @@ -531,7 +542,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, CrossProcess) { "empty.html"); call_script_user_gesture.set_has_user_gesture(true); - ASSERT_TRUE(RunTest("webnavigation/crossProcess")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcess")) << message_; } // crbug.com/708139. @@ -571,20 +582,21 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, browser(), embedded_test_server()->GetURL("/test6"), "updateHistory()", "empty.html"); - ASSERT_TRUE(RunTest("webnavigation/crossProcessHistory")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessHistory")) + << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, CrossProcessIframe) { content::IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess()); ASSERT_TRUE(StartEmbeddedTestServer()); - ASSERT_TRUE(RunTest("webnavigation/crossProcessIframe")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/crossProcessIframe")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, PendingDeletion) { content::IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess()); ASSERT_TRUE(StartEmbeddedTestServer()); - ASSERT_TRUE(RunTest("webnavigation/pendingDeletion")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/pendingDeletion")) << message_; } IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, Crash) { @@ -592,7 +604,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, Crash) { ASSERT_TRUE(StartEmbeddedTestServer()); // Wait for the extension to set itself up and return control to us. - ASSERT_TRUE(RunTest("webnavigation/crash")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/crash")) << message_; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_TRUE(content::WaitForLoadStop(tab)); @@ -601,16 +613,17 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, Crash) { GURL url(embedded_test_server()->GetURL( "www.a.com", "/extensions/api_test/webnavigation/crash/a.html")); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); content::RenderProcessHostWatcher process_watcher( tab, content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT); - ui_test_utils::NavigateToURL(browser(), GURL(blink::kChromeUICrashURL)); + ASSERT_TRUE( + ui_test_utils::NavigateToURL(browser(), GURL(blink::kChromeUICrashURL))); process_watcher.Wait(); url = GURL(embedded_test_server()->GetURL( "www.a.com", "/extensions/api_test/webnavigation/crash/b.html")); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } @@ -624,7 +637,7 @@ IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, Crash) { IN_PROC_BROWSER_TEST_P(WebNavigationApiTestWithContextType, MAYBE_Xslt) { content::IsolateAllSitesForTesting(base::CommandLine::ForCurrentProcess()); ASSERT_TRUE(StartEmbeddedTestServer()); - ASSERT_TRUE(RunTest("webnavigation/xslt")) << message_; + ASSERT_TRUE(RunExtensionTest("webnavigation/xslt")) << message_; } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/web_request/DIR_METADATA b/chromium/chrome/browser/extensions/api/web_request/DIR_METADATA index 637eb4dc771..ab135564d46 100644 --- a/chromium/chrome/browser/extensions/api/web_request/DIR_METADATA +++ b/chromium/chrome/browser/extensions/api/web_request/DIR_METADATA @@ -1,3 +1 @@ -monorail { - component: "Platform>Extensions>API" -} +mixins: "//extensions/browser/api/web_request/COMMON_METADATA" diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc index e661551dce7..bb12cc0e145 100644 --- a/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/web_request/web_request_api_unittest.cc @@ -72,7 +72,6 @@ namespace web_request = extensions::api::web_request; using base::DictionaryValue; using base::ListValue; using base::Time; -using base::TimeDelta; using base::Value; using helpers::CalculateOnAuthRequiredDelta; using helpers::CalculateOnBeforeRequestDelta; @@ -142,7 +141,7 @@ bool GenerateInfoSpec(content::BrowserContext* browser_context, for (const std::string& cur : base::SplitString(values, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) - list_value.AppendString(cur); + list_value.Append(cur); return ExtraInfoSpec::InitFromValue(browser_context, list_value, result); } @@ -1118,7 +1117,7 @@ std::string GetCookieExpirationDate(int delta_secs) { }; Time::Exploded exploded_time; - (Time::Now() + TimeDelta::FromSeconds(delta_secs)).UTCExplode(&exploded_time); + (Time::Now() + base::Seconds(delta_secs)).UTCExplode(&exploded_time); return base::StringPrintf("%s, %d %s %d %.2d:%.2d:%.2d GMT", kWeekDays[exploded_time.day_of_week], @@ -1181,7 +1180,7 @@ TEST(ExtensionWebRequestHelpersTest, edit_cookie.filter.emplace(); edit_cookie.filter->name = "name2"; edit_cookie.modification.emplace(); - edit_cookie.modification->value = "new value"; + edit_cookie.modification->value = "newvalue"; ResponseCookieModification edit_cookie_2; edit_cookie_2.type = helpers::EDIT; @@ -1259,9 +1258,9 @@ TEST(ExtensionWebRequestHelpersTest, edit_cookie_9.type = helpers::EDIT; edit_cookie_9.filter.emplace(); edit_cookie_9.filter->name = "uBound4"; - edit_cookie_9.filter->age_upper_bound = 2501; + edit_cookie_9.filter->age_upper_bound = 2499; edit_cookie_9.modification.emplace(); - edit_cookie_9.modification->value = "Will not change"; + edit_cookie_9.modification->value = "Willnotchange"; // Tests 'ageUpperBound' filter when both 'max-age' and 'expires' cookie // attributes are provided. 'expires' value matches the filter, however @@ -1271,9 +1270,9 @@ TEST(ExtensionWebRequestHelpersTest, edit_cookie_10.type = helpers::EDIT; edit_cookie_10.filter.emplace(); edit_cookie_10.filter->name = "uBound5"; - edit_cookie_10.filter->age_upper_bound = 800; + edit_cookie_10.filter->age_upper_bound = 599; edit_cookie_10.modification.emplace(); - edit_cookie_10.modification->value = "Will not change"; + edit_cookie_10.modification->value = "Willnotchange"; ResponseCookieModification remove_cookie; remove_cookie.type = helpers::REMOVE; @@ -1323,7 +1322,7 @@ TEST(ExtensionWebRequestHelpersTest, std::string cookie_string; std::set<std::string> expected_cookies; expected_cookies.insert("name=value; domain=google.com; secure"); - expected_cookies.insert("name2=value2; secure"); + expected_cookies.insert("name2=newvalue; secure"); expected_cookies.insert("name4=\"value4\"; secure"); expected_cookies.insert( "lBound1=greater_1; expires=" + cookie_expiration + "; secure"); diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc index afa9ea1a228..c752dfd5828 100644 --- a/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc +++ b/chromium/chrome/browser/extensions/api/web_request/web_request_apitest.cc @@ -91,6 +91,7 @@ #include "content/public/test/simple_url_loader_test_helper.h" #include "content/public/test/url_loader_interceptor.h" #include "content/public/test/url_loader_monitor.h" +#include "content/public/test/web_transport_simple_test_server.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/blocked_action_type.h" #include "extensions/browser/extension_prefs.h" @@ -151,6 +152,9 @@ class CancelLoginDialog : public content::NotificationObserver { content::NotificationService::AllSources()); } + CancelLoginDialog(const CancelLoginDialog&) = delete; + CancelLoginDialog& operator=(const CancelLoginDialog&) = delete; + ~CancelLoginDialog() override {} void Observe(int type, @@ -163,8 +167,6 @@ class CancelLoginDialog : public content::NotificationObserver { private: content::NotificationRegistrar registrar_; - - DISALLOW_COPY_AND_ASSIGN(CancelLoginDialog); }; // Observer that listens for messages from chrome.test.sendMessage to allow them @@ -703,8 +705,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, GURL url = https_test_server.GetURL("/webrequest/simulate_click.html"); base::ListValue custom_args; - custom_args.AppendString(url.spec()); - custom_args.AppendString(insecure_destination.spec()); + custom_args.Append(url.spec()); + custom_args.Append(insecure_destination.spec()); std::string config_string; base::JSONWriter::Write(custom_args, &config_string); @@ -747,7 +749,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestNewTab) { last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL("newTab/a.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // There's a link on a.html with target=_blank. Click on it to open it in a // new tab. @@ -815,9 +817,8 @@ void ExtensionWebRequestApiTest::RunPermissionTest( EXPECT_TRUE(listener.WaitUntilSatisfied()); // This navigation should be redirected. - ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("/extensions/test_file.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/extensions/test_file.html"))); std::string body; WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); @@ -836,9 +837,9 @@ void ExtensionWebRequestApiTest::RunPermissionTest( // This navigation should be redirected if // load_extension_with_incognito_permission is true. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( otr_browser, - embedded_test_server()->GetURL("/extensions/test_file.html")); + embedded_test_server()->GetURL("/extensions/test_file.html"))); body.clear(); WebContents* otr_tab = otr_browser->tab_strip_model()->GetActiveWebContents(); @@ -956,8 +957,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ExtensionRequests) { // Load a page, a content script from "webrequest_extensions/extension" will // ping us when it is ready. ExtensionTestMessageListener listener_pageready("contentscript_ready", true); - ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL( - "/extensions/test_file.html?match_webrequest_test")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL( + "/extensions/test_file.html?match_webrequest_test"))); EXPECT_TRUE(listener_pageready.WaitUntilSatisfied()); // The extension and app-generated requests should not have triggered any @@ -1025,7 +1027,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, HostedAppRequest) { ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("webrequest_hosted_app"))); - ui_test_utils::NavigateToURL(browser(), hosted_app_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), hosted_app_url)); EXPECT_TRUE(listener1.WaitUntilSatisfied()); EXPECT_TRUE(listener2.WaitUntilSatisfied()); @@ -1062,50 +1064,45 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ExtensionActionRunner::GetForWebContents(web_contents); ASSERT_TRUE(runner); - // The extension shouldn't have currently received any webRequest events, - // since it doesn't have any permissions. - EXPECT_EQ(0, GetWebRequestCountFromBackgroundPage(extension, profile())); - - auto get_main_and_child_frame = [](content::WebContents* web_contents, - content::RenderFrameHost** main_frame, - content::RenderFrameHost** child_frame) { - *child_frame = nullptr; - *main_frame = web_contents->GetMainFrame(); - std::vector<content::RenderFrameHost*> all_frames = - web_contents->GetAllFrames(); - ASSERT_EQ(3u, all_frames.size()); - *child_frame = all_frames[0] == *main_frame ? all_frames[1] : all_frames[0]; - ASSERT_TRUE(*child_frame); - }; - - content::RenderFrameHost* main_frame = nullptr; - content::RenderFrameHost* child_frame = nullptr; - get_main_and_child_frame(web_contents, &main_frame, &child_frame); - const std::string kMainHost = main_frame->GetLastCommittedURL().host(); - const std::string kChildHost = child_frame->GetLastCommittedURL().host(); - int port = embedded_test_server()->port(); const std::string kXhrPath = "simple.html"; - // The extension shouldn't be able to intercept the xhr requests since it - // doesn't have any permissions. - PerformXhrInFrame(main_frame, kHost, port, kXhrPath); - PerformXhrInFrame(child_frame, kChildHost, port, kXhrPath); - EXPECT_EQ(0, GetWebRequestCountFromBackgroundPage(extension, profile())); - EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner->GetBlockedActions(extension)); - - // Grant activeTab permission. - runner->set_default_bubble_close_action_for_testing( - base::WrapUnique(new ToolbarActionsBarBubbleDelegate::CloseAction( - ToolbarActionsBarBubbleDelegate::CLOSE_EXECUTE))); - runner->RunAction(extension, true); - base::RunLoop().RunUntilIdle(); - EXPECT_TRUE(content::WaitForLoadStop(web_contents)); + // The extension shouldn't have currently received any webRequest events, + // since it doesn't have any permissions. + { + EXPECT_EQ(0, GetWebRequestCountFromBackgroundPage(extension, profile())); + + content::RenderFrameHostWrapper main_frame(web_contents->GetMainFrame()); + content::RenderFrameHostWrapper child_frame( + ChildFrameAt(main_frame.get(), 0)); + ASSERT_TRUE(child_frame); + const std::string kChildHost = child_frame->GetLastCommittedURL().host(); + + // The extension shouldn't be able to intercept the xhr requests since it + // doesn't have any permissions. + PerformXhrInFrame(main_frame.get(), kHost, port, kXhrPath); + PerformXhrInFrame(child_frame.get(), kChildHost, port, kXhrPath); + EXPECT_EQ(0, GetWebRequestCountFromBackgroundPage(extension, profile())); + EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner->GetBlockedActions(extension)); + + // Grant activeTab permission. + runner->set_default_bubble_close_action_for_testing( + base::WrapUnique(new ToolbarActionsBarBubbleDelegate::CloseAction( + ToolbarActionsBarBubbleDelegate::CLOSE_EXECUTE))); + runner->RunAction(extension, true); + base::RunLoop().RunUntilIdle(); + EXPECT_TRUE(content::WaitForLoadStop(web_contents)); + } // The runner will have refreshed the page, and the extension will have // received access to the main-frame ("a.com"). It should still not be able to // intercept the cross-origin sub-frame requests to "b.com" and "c.com". - get_main_and_child_frame(web_contents, &main_frame, &child_frame); + content::RenderFrameHostWrapper main_frame(web_contents->GetMainFrame()); + content::RenderFrameHostWrapper child_frame( + ChildFrameAt(main_frame.get(), 0)); + const std::string kChildHost = child_frame->GetLastCommittedURL().host(); + + ASSERT_TRUE(child_frame); EXPECT_TRUE(HasSeenWebRequestInBackgroundPage(extension, profile(), "a.com")); EXPECT_FALSE( HasSeenWebRequestInBackgroundPage(extension, profile(), "b.com")); @@ -1119,14 +1116,14 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, GetWebRequestCountFromBackgroundPage(extension, profile()); // ... and the extension should receive future events. - PerformXhrInFrame(main_frame, kHost, port, kXhrPath); + PerformXhrInFrame(main_frame.get(), kHost, port, kXhrPath); ++request_count; EXPECT_EQ(request_count, GetWebRequestCountFromBackgroundPage(extension, profile())); // However, activeTab only grants access to the main frame, not to child // frames. As such, trying to XHR in the child frame should still fail. - PerformXhrInFrame(child_frame, kChildHost, port, kXhrPath); + PerformXhrInFrame(child_frame.get(), kChildHost, port, kXhrPath); EXPECT_EQ(request_count, GetWebRequestCountFromBackgroundPage(extension, profile())); // But since there's no way for the user to currently grant access to child @@ -1145,7 +1142,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, // badge UI. TestExtensionActionAPIObserver action_updated_waiter(profile(), extension->id()); - PerformXhrInFrame(main_frame, kHost, port, kXhrPath); + PerformXhrInFrame(main_frame.get(), kHost, port, kXhrPath); action_updated_waiter.Wait(); EXPECT_EQ(web_contents, action_updated_waiter.last_web_contents()); @@ -1171,9 +1168,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, .SetWithholdHostPermissions(true); EXPECT_TRUE(listener.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( - "a.com", "/extensions/cross_site_script.html")); + "a.com", "/extensions/cross_site_script.html"))); const std::string kCrossSiteHost("b.com"); EXPECT_FALSE( @@ -1244,9 +1241,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, EXPECT_TRUE(listener.WaitUntilSatisfied()); // Navigate to example.com, which has a cross-site script to b.com. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( - "example.com", "/extensions/cross_site_script.html")); + "example.com", "/extensions/cross_site_script.html"))); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -1263,9 +1260,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, // Navigating to b.com (so that the script is hosted on the same origin as // the WebContents) should show the extension wants to run. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( - "b.com", "/extensions/cross_site_script.html")); + "b.com", "/extensions/cross_site_script.html"))); EXPECT_EQ(BLOCKED_ACTION_WEB_REQUEST, runner->GetBlockedActions(extension)); } @@ -1389,8 +1386,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ->FlushProxyConfigMonitorForTesting(); // Navigate to a page. The URL doesn't matter. - ui_test_utils::NavigateToURL( - browser(), GURL("http://does.not.resolve.test/title2.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), GURL("http://does.not.resolve.test/title2.html"))); // The extension should not have seen the PAC request. EXPECT_EQ(0, GetCountFromBackgroundPage(extension, profile(), @@ -1478,7 +1475,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, // Navigate to the Gaia URL intercepted by the extension. GURL url = embedded_test_server()->GetURL("gaia.com", "/extensions/dice.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Check that the Dice header was not changed by the extension. EXPECT_TRUE(test_webcontents_observer.did_finish_navigation_called()); @@ -1498,7 +1495,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, // Navigate to a non-Gaia URL intercepted by the extension. test_webcontents_observer.Clear(); url = embedded_test_server()->GetURL("example.com", "/extensions/dice.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Check that the Dice header was changed by the extension. EXPECT_TRUE(test_webcontents_observer.did_finish_navigation_called()); @@ -1560,6 +1557,47 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebSocketCleanClose) { << message_; } +class ExtensionWebRequestApiWebTransportTest + : public ExtensionWebRequestApiTest { + public: + ExtensionWebRequestApiWebTransportTest() { server_.Start(); } + + void SetUpCommandLine(base::CommandLine* command_line) override { + ExtensionWebRequestApiTest::SetUpCommandLine(command_line); + server_.SetUpCommandLine(command_line); + } + + void SetUpOnMainThread() override { + ExtensionWebRequestApiTest::SetUpOnMainThread(); + ASSERT_TRUE(StartEmbeddedTestServer()); + GetTestConfig()->SetInteger("testWebTransportPort", + server_.server_address().port()); + } + + protected: + bool RunTest(const char* page_url) { + return RunExtensionTest("webrequest", {.page_url = page_url}); + } + + content::WebTransportSimpleTestServer server_; +}; + +// Test that the webRequest events are dispatched for the WebTransport +// handshake. +IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiWebTransportTest, Main) { + ASSERT_TRUE(RunTest("test_webtransport.html")) << message_; +} + +// Test that the webRequest events are dispatched for the WebTransport +// handshake in a dedicated worker. +IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiWebTransportTest, + DedicaterWorker) { + ASSERT_TRUE(RunTest("test_webtransport_dedicated_worker.html")) << message_; +} + +// TODO(crbug.com/1240935): Add test for this OnBeforeRequest reject case. +// TODO(crbug.com/1240935): Add test for dedicated worker. + // Test behavior when intercepting requests from a browser-initiated url fetch. IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestURLLoaderInterception) { @@ -1625,7 +1663,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, // is working correctly. content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL(browser(), google_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), google_url)); EXPECT_EQ(google_url, web_contents->GetLastCommittedURL()); { // google.com should succeed. @@ -1640,7 +1678,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, GURL example_url = embedded_test_server()->GetURL("example.com", "/extensions/body2.html"); - ui_test_utils::NavigateToURL(browser(), example_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), example_url)); { // example.com should fail. content::NavigationEntry* nav_entry = @@ -1760,9 +1798,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, InitiatorAccessRequired) { ":" + testcase.expected_initiator); ExtensionTestMessageListener initiator_listener(false); initiator_listener.set_extension_id(extension->id()); - ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL( - testcase.navigate_before_start, - "/extensions/body1.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), + embedded_test_server()->GetURL(testcase.navigate_before_start, + "/extensions/body1.html"))); PerformXhrInFrame(web_contents->GetMainFrame(), testcase.xhr_domain, port, "extensions/api_test/webrequest/xhr/data.json"); @@ -1895,6 +1934,11 @@ class NTPInterceptionWebRequestAPITest : public ExtensionApiTest { NTPInterceptionWebRequestAPITest() : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} + NTPInterceptionWebRequestAPITest(const NTPInterceptionWebRequestAPITest&) = + delete; + NTPInterceptionWebRequestAPITest& operator=( + const NTPInterceptionWebRequestAPITest&) = delete; + // ExtensionApiTest override: void SetUpOnMainThread() override { ExtensionApiTest::SetUpOnMainThread(); @@ -1914,7 +1958,6 @@ class NTPInterceptionWebRequestAPITest : public ExtensionApiTest { private: net::EmbeddedTestServer https_test_server_; - DISALLOW_COPY_AND_ASSIGN(NTPInterceptionWebRequestAPITest); }; // Ensures that requests made by the NTP Instant renderer are hidden from the @@ -1961,15 +2004,16 @@ IN_PROC_BROWSER_TEST_F(NTPInterceptionWebRequestAPITest, // Navigate to the NTP. The request for "fake_ntp_script.js" should not have // reached the extension, since it was made by the instant NTP renderer, which // is semi-privileged. - ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), + GURL(chrome::kChromeUINewTabURL))); EXPECT_TRUE(was_ntp_script_loaded(web_contents)); ASSERT_TRUE(search::IsInstantNTP(web_contents)); EXPECT_FALSE(was_script_request_intercepted(extension->id())); // However, when a normal webpage requests the same script, the request should // be seen by the extension. - ui_test_utils::NavigateToURL( - browser(), https_test_server()->GetURL("/page_with_ntp_script.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), https_test_server()->GetURL("/page_with_ntp_script.html"))); EXPECT_TRUE(was_ntp_script_loaded(web_contents)); ASSERT_FALSE(search::IsInstantNTP(web_contents)); EXPECT_TRUE(was_script_request_intercepted(extension->id())); @@ -1984,6 +2028,11 @@ class WebUiNtpInterceptionWebRequestAPITest WebUiNtpInterceptionWebRequestAPITest() : https_test_server_(net::EmbeddedTestServer::TYPE_HTTPS) {} + WebUiNtpInterceptionWebRequestAPITest( + const WebUiNtpInterceptionWebRequestAPITest&) = delete; + WebUiNtpInterceptionWebRequestAPITest& operator=( + const WebUiNtpInterceptionWebRequestAPITest&) = delete; + // ExtensionApiTest override: void SetUp() override { https_test_server_.RegisterRequestMonitor(base::BindRepeating( @@ -2053,8 +2102,6 @@ class WebUiNtpInterceptionWebRequestAPITest bool one_google_bar_request_seen_ = false; base::Lock lock_; - - DISALLOW_COPY_AND_ASSIGN(WebUiNtpInterceptionWebRequestAPITest); }; IN_PROC_BROWSER_TEST_F(WebUiNtpInterceptionWebRequestAPITest, @@ -2083,7 +2130,8 @@ IN_PROC_BROWSER_TEST_F(WebUiNtpInterceptionWebRequestAPITest, }; ASSERT_FALSE(GetAndResetOneGoogleBarRequestSeen()); - ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), + GURL(chrome::kChromeUINewTabURL))); ASSERT_EQ(ntp_test_utils::GetFinalNtpUrl(browser()->profile()), browser() ->tab_strip_model() @@ -2097,7 +2145,7 @@ IN_PROC_BROWSER_TEST_F(WebUiNtpInterceptionWebRequestAPITest, // A normal request to |one_google_bar_url()| (i.e. not made by // OneGoogleBarFetcher) should be intercepted by extensions. - ui_test_utils::NavigateToURL(browser(), one_google_bar_url()); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), one_google_bar_url())); EXPECT_TRUE(was_script_request_intercepted(extension->id())); ASSERT_TRUE(GetAndResetOneGoogleBarRequestSeen()); } @@ -2318,15 +2366,19 @@ class ExtensionWebRequestMockedClockTest : public ExtensionWebRequestApiTest { nullptr, nullptr) {} + ExtensionWebRequestMockedClockTest( + const ExtensionWebRequestMockedClockTest&) = delete; + ExtensionWebRequestMockedClockTest& operator=( + const ExtensionWebRequestMockedClockTest&) = delete; + private: static base::Time Now() { static base::Time now_time = base::Time::UnixEpoch(); - now_time += base::TimeDelta::FromMilliseconds(1); + now_time += base::Milliseconds(1); return now_time; } base::subtle::ScopedTimeClockOverrides scoped_time_clock_override_; - DISALLOW_COPY_AND_ASSIGN(ExtensionWebRequestMockedClockTest); }; // Tests that we correctly dispatch the OnActionIgnored event on an extension @@ -2375,7 +2427,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestMockedClockTest, const GURL expected_redirect_url_2 = embedded_test_server()->GetURL("foo.com", "/simple.html"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -2402,7 +2454,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestMockedClockTest, redirect_ignored_listener.Reset(); redirect_successful_listener.Reset(); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // The first extension is the latest installed, hence it's redirect url // should take precedence. @@ -2479,8 +2531,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, StaleHeadersAfterRedirect) { ASSERT_TRUE(embedded_test_server()->Start()); // Navigate to a basic page so XHR requests work. - ui_test_utils::NavigateToURL(browser(), - embedded_test_server()->GetURL("/echo")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/echo"))); // Make a XHR request which redirects. The final response should not include // the Location header. @@ -2553,9 +2605,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ChangeHeaderUMAs) { EXPECT_TRUE(listener.WaitUntilSatisfied()); base::HistogramTester tester; - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), - embedded_test_server()->GetURL("/set-cookie?key1=val1&key2=val2")); + embedded_test_server()->GetURL("/set-cookie?key1=val1&key2=val2"))); // Changed histograms should record kUserAgent request header along with // kSetCookie and kContentLength response headers. @@ -2641,8 +2693,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, RemoveHeaderUMAs) { EXPECT_TRUE(listener.WaitUntilSatisfied()); base::HistogramTester tester; - ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("/set-cookie?Foo=Bar")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/set-cookie?Foo=Bar"))); // Histograms for removed headers should record kUserAgent and kSetCookie. tester.ExpectUniqueSample("Extensions.WebRequest.RequestHeaderRemoved", @@ -2787,8 +2839,8 @@ IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, RegisterServiceWorker("/fetch_event_passthrough.js", "/echoheader"); // Make sure the request is intercepted with no redirect. - ui_test_utils::NavigateToURL( - browser(), embedded_test_server()->GetURL("/echoheader?foo")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/echoheader?foo"))); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ("bar", EvalJs(web_contents, "document.body.textContent;")); @@ -2797,7 +2849,7 @@ IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, GURL redirect_url = embedded_test_server()->GetURL( "/server-redirect?" + embedded_test_server()->GetURL("/echoheader?foo").spec()); - ui_test_utils::NavigateToURL(browser(), redirect_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), redirect_url)); EXPECT_EQ("bar", EvalJs(web_contents, "document.body.textContent;")); } @@ -3035,7 +3087,7 @@ IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, // the page. GURL url = embedded_test_server()->GetURL( "/echoheader?frameId&resourceType&service-worker-navigation-preload"); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); @@ -3111,13 +3163,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, window.initiators = []; )"; - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); EXPECT_EQ(base::StringPrintf("[\"%s\"]", url_origin.c_str()), ExecuteScriptInBackgroundPage(extension_id, kScript)); // The extension isn't enabled in incognito. Se we shouldn't intercept the // request to |url|. - ui_test_utils::NavigateToURL(incognito_browser, url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, url)); EXPECT_EQ("[]", ExecuteScriptInBackgroundPage(extension_id, kScript)); // Now enable the extension in incognito. @@ -3127,7 +3179,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, EXPECT_TRUE(ready_listener.WaitUntilSatisfied()); // Now we should be able to intercept the incognito request. - ui_test_utils::NavigateToURL(incognito_browser, url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, url)); EXPECT_EQ(base::StringPrintf("[\"%s\"]", url_origin.c_str()), ExecuteScriptInBackgroundPage(extension_id, kScript)); } @@ -3168,8 +3220,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, Initiator_SplitIncognito) { window.initiators = []; )"; - ui_test_utils::NavigateToURL(browser(), url_normal); - ui_test_utils::NavigateToURL(incognito_browser, url_incognito); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url_normal)); + ASSERT_TRUE(ui_test_utils::NavigateToURL(incognito_browser, url_incognito)); EXPECT_EQ(base::StringPrintf("[\"%s\"]", origin_normal.c_str()), browsertest_util::ExecuteScriptInBackgroundPage( profile(), extension->id(), kScript)); @@ -3220,15 +3272,15 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ASSERT_TRUE(extension); EXPECT_TRUE(listener.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL(browser(), https_test_server.GetURL("/echo")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), + https_test_server.GetURL("/echo"))); content::StoragePartition* partition = profile()->GetDefaultStoragePartition(); base::RunLoop run_loop; partition->GetNetworkContext()->AddHSTS( https_test_server.host_port_pair().host(), - base::Time::Now() + base::TimeDelta::FromDays(100), true, - run_loop.QuitClosure()); + base::Time::Now() + base::Days(100), true, run_loop.QuitClosure()); run_loop.Run(); PerformXhrInFrame( @@ -3240,59 +3292,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, 0); } -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, AppCacheRequests) { - std::string origin = "http://127.0.0.1:8080"; - std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor = - content::URLLoaderInterceptor::ServeFilesFromDirectoryAtOrigin( - "content/test/data", GURL(origin)); - GURL main_url(origin + "/appcache/simple_page_with_manifest.html"); - - std::u16string expected_title = u"AppCache updated"; - - // Load the main page first to make sure it is cached. After the first - // navigation, load the extension, then navigate again. - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url)); - content::TitleWatcher title_watcher( - browser()->tab_strip_model()->GetActiveWebContents(), expected_title); - EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); - - TestExtensionDir test_dir; - test_dir.WriteManifest(R"({ - "name": "Web Request Appcache Test", - "manifest_version": 2, - "version": "0.1", - "background": { "scripts": ["background.js"] }, - "permissions": ["<all_urls>", "webRequest"] - })"); - test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"( - window.numMainResourceRequests = 0; - window.numSubresourceRequests = 0; - chrome.webRequest.onBeforeRequest.addListener(function(details) { - if (details.url.includes('logo.png')) - window.numSubresourceRequests++; - else if (details.url.includes('simple_page_with_manifest.html')) - window.numMainResourceRequests++; - }, {urls: ['<all_urls>']}, []); - - chrome.test.sendMessage('ready'); - )"); - - ExtensionTestMessageListener listener("ready", false); - const Extension* extension = LoadExtension(test_dir.UnpackedPath()); - ASSERT_TRUE(extension); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - // This navigation should go through appcache. - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url)); - - EXPECT_EQ(GetCountFromBackgroundPage(extension, profile(), - "window.numSubresourceRequests"), - 1); - EXPECT_EQ(GetCountFromBackgroundPage(extension, profile(), - "window.numMainResourceRequests"), - 1); -} - // Ensure that when an extension blocks a main-frame request, the resultant // error page attributes this to an extension. IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, @@ -3313,69 +3312,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, EXPECT_TRUE(base::Contains(body, "Try disabling your extensions.")); } -// Regression test for http://crbug.com/996940. Requests that redirected to an -// appcache handled URL could have request ID collisions. -// This test is flaky on Linux and Mac: https://crbug.com/1094834. -// TODO(crbug.com/1052397): Revisit once build flag switch of lacros-chrome is -// complete. -#if defined(OS_LINUX) || defined(OS_MAC) || BUILDFLAG(IS_CHROMEOS_LACROS) -#define MAYBE_RedirectToAppCacheRequest DISABLED_RedirectToAppCacheRequest -#else -#define MAYBE_RedirectToAppCacheRequest RedirectToAppCacheRequest -#endif -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, - MAYBE_RedirectToAppCacheRequest) { - // Use the embedded test server to support server-redirect, but serve - // appcache from a fixed port using the url loader interceptor below - // so that the appcache origin trial works. - ASSERT_TRUE(StartEmbeddedTestServer()); - - std::string origin = "http://127.0.0.1:8080"; - auto interceptor = - content::URLLoaderInterceptor::ServeFilesFromDirectoryAtOrigin( - "content/test/data", GURL(origin)); - GURL main_url(origin + "/appcache/simple_page_with_manifest.html"); - - std::u16string expected_title = u"AppCache updated"; - - // Load the main page first to make sure it is cached. After the first - // navigation, load the extension, then navigate again. - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), main_url)); - content::TitleWatcher title_watcher( - browser()->tab_strip_model()->GetActiveWebContents(), expected_title); - EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); - - TestExtensionDir test_dir; - test_dir.WriteManifest(R"({ - "name": "Web Request Appcache Redirect Test", - "manifest_version": 2, - "version": "0.1", - "background": { "scripts": ["background.js"] }, - "permissions": ["<all_urls>", "webRequest"] - })"); - test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"( - window.numErrors = 0; - chrome.webRequest.onErrorOccurred.addListener(function(details) { - window.numErrors++; - }, {urls: ['<all_urls>']}); - - chrome.test.sendMessage('ready'); - )"); - - ExtensionTestMessageListener listener("ready", false); - const Extension* extension = LoadExtension(test_dir.UnpackedPath()); - ASSERT_TRUE(extension); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - - // This navigation should go through appcache. - EXPECT_TRUE(ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("/server-redirect?" + main_url.spec()))); - - EXPECT_EQ( - GetCountFromBackgroundPage(extension, profile(), "window.numErrors"), 0); -} - // Regression test for https://crbug.com/1019614. IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, HSTSUpgradeAfterRedirect) { net::EmbeddedTestServer https_test_server( @@ -3410,9 +3346,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, HSTSUpgradeAfterRedirect) { content::StoragePartition* partition = profile()->GetDefaultStoragePartition(); base::RunLoop run_loop; - partition->GetNetworkContext()->AddHSTS( - "hsts.com", base::Time::Now() + base::TimeDelta::FromDays(100), true, - run_loop.QuitClosure()); + partition->GetNetworkContext()->AddHSTS("hsts.com", + base::Time::Now() + base::Days(100), + true, run_loop.QuitClosure()); run_loop.Run(); GURL final_url = https_test_server.GetURL("hsts.com", "/echo"); @@ -3422,7 +3358,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, HSTSUpgradeAfterRedirect) { std::string redirect_path = base::StringPrintf("/server-redirect?%s", http_url.spec().c_str()); GURL redirect_url = embedded_test_server()->GetURL("test.com", redirect_path); - ui_test_utils::NavigateToURL(browser(), redirect_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), redirect_url)); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(final_url, web_contents->GetLastCommittedURL()); @@ -3473,6 +3409,31 @@ class SubresourceWebBundlesWebRequestApiTest return success; } + bool TryLoadBundle(const std::string& href, const std::string& resources) { + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + bool success = false; + std::string script = base::StringPrintf(R"( + (() => { + const link = document.createElement('link'); + link.rel = 'webbundle'; + link.addEventListener('load', () => { + window.domAutomationController.send(true); + }); + link.addEventListener('error', () => { + window.domAutomationController.send(false); + }); + link.href = '%s'; + link.resources = '%s'; + document.body.appendChild(link); + })(); + )", + href.c_str(), resources.c_str()); + EXPECT_TRUE(ExecuteScriptAndExtractBool(web_contents->GetMainFrame(), + script, &success)); + return success; + } + // Registers a request handler for static content. void RegisterRequestHandler(const std::string& relative_url, const std::string& content_type, @@ -3630,7 +3591,7 @@ IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, browser()->tab_strip_model()->GetActiveWebContents(); std::u16string expected_title = u"ScriptDone:UrnUUIDScriptDone"; content::TitleWatcher title_watcher(web_contents, expected_title); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); // Check that the scripts in the web bundle are correctly loaded even when the // extension intercepted the request. @@ -3758,7 +3719,7 @@ IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, GURL page_url = embedded_test_server()->GetURL("/test.html"); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); std::u16string expected_title1 = u"script loaded"; @@ -3876,7 +3837,7 @@ IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, ChangeHeader) { content::TitleWatcher title_watcher( browser()->tab_strip_model()->GetActiveWebContents(), expected_title); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); @@ -3979,7 +3940,7 @@ IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, content::TitleWatcher title_watcher( browser()->tab_strip_model()->GetActiveWebContents(), expected_title); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); @@ -4105,7 +4066,7 @@ IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, GURL page_url = embedded_test_server()->GetURL("/test.html"); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); - ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), page_url)); EXPECT_EQ(page_url, web_contents->GetLastCommittedURL()); { std::u16string expected_title = u"redirected"; @@ -4127,6 +4088,69 @@ IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, EXPECT_FALSE(TryLoadScript("redirect_to_server.js")); } +// Ensure that request to Subresource WebBundle fails if it is redirected by web +// request API. +IN_PROC_BROWSER_TEST_P(SubresourceWebBundlesWebRequestApiTest, + WebBundleRequestRedirected) { + // Create an extension that redirects "redirect.wbn" to "redirected.wbn". + TestExtensionDir test_dir; + test_dir.WriteManifest(R"({ + "name": "Web Request Subresource Web Bundles Test", + "manifest_version": 2, + "version": "0.1", + "background": { "scripts": ["background.js"] }, + "permissions": ["<all_urls>", "webRequest", "webRequestBlocking"] + })"); + std::string opt_extra_info_spec = "'blocking'"; + if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) + opt_extra_info_spec += ", 'extraHeaders'"; + test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), + base::StringPrintf(R"( + chrome.webRequest.onBeforeRequest.addListener(function(details) { + if (!details.url.includes('redirect.wbn')) + return; + const redirectUrl = + details.url.replace('redirect.wbn', 'redirected.wbn'); + return {redirectUrl}; + }, {urls: ['<all_urls>']}, [%s]); + + chrome.test.sendMessage('ready'); + )", + opt_extra_info_spec.c_str())); + const Extension* extension = nullptr; + { + ExtensionTestMessageListener listener("ready", false); + extension = LoadExtension(test_dir.UnpackedPath()); + ASSERT_TRUE(extension); + EXPECT_TRUE(listener.WaitUntilSatisfied()); + } + + std::string web_bundle; + RegisterWebBundleRequestHandler("/redirect.wbn", &web_bundle); + RegisterWebBundleRequestHandler("/redirected.wbn", &web_bundle); + ASSERT_TRUE(StartEmbeddedTestServer()); + + // Create a web bundle. + std::string js_url_str = embedded_test_server()->GetURL("/script.js").spec(); + web_package::test::WebBundleBuilder builder(js_url_str, ""); + builder.AddExchange( + js_url_str, + {{":status", "200"}, {"content-type", "application/javascript"}}, + "document.title = 'script loaded';"); + std::vector<uint8_t> bundle = builder.CreateBundle(); + web_bundle = std::string(bundle.begin(), bundle.end()); + + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/empty.html"))); + + // In the current implementation, extensions can't redirect requests to + // Subresource WebBundles. + EXPECT_FALSE(TryLoadBundle("redirect.wbn", js_url_str)); + + // Without redirection, bundle load should succeed. + EXPECT_TRUE(TryLoadBundle("redirected.wbn", js_url_str)); +} + // TODO(crbug.com/1082020) When we implement variant matching of subresource // web bundles, we should add test for request header modification. @@ -4246,14 +4270,13 @@ IN_PROC_BROWSER_TEST_P(RedirectInfoWebRequestApiTest, ASSERT_TRUE(web_contents); EXPECT_EQ(page_with_iframe_url, web_contents->GetLastCommittedURL()); - // Since frames are returned in breadth first order, and there's only one - // iframe, the iframe should be the second frame in this vector. - std::vector<content::RenderFrameHost*> all_frames = - web_contents->GetAllFrames(); - ASSERT_EQ(2u, all_frames.size()); + content::RenderFrameHostWrapper child_frame( + ChildFrameAt(web_contents->GetMainFrame(), 0)); + ASSERT_TRUE(child_frame); + GURL redirected_url = embedded_test_server()->GetURL("redirected.test", "/hello.html"); - ASSERT_EQ(redirected_url, all_frames[1]->GetLastCommittedURL()); + ASSERT_EQ(redirected_url, child_frame->GetLastCommittedURL()); // Check the parameters passed to the URLLoaderFactory. absl::optional<network::ResourceRequest> resource_request = @@ -4379,7 +4402,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiIdentifiabilityTest, identifiability_metrics_test_helper_.PrepareForTest(&run_loop); ASSERT_TRUE(StartEmbeddedTestServer()); - ui_test_utils::NavigateToURL(browser(), GURL("about:blank")); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), GURL("about:blank"))); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); identifiability_metrics_test_helper_.EnsureIdentifiabilityEventGenerated( @@ -4543,8 +4566,8 @@ IN_PROC_BROWSER_TEST_F(ProxyCORSWebRequestApiTest, LoadExtension(test_data_dir_.AppendASCII("webrequest_cors_preflight")); ASSERT_TRUE(extension) << message_; ASSERT_TRUE(ready_listener.WaitUntilSatisfied()); - ui_test_utils::NavigateToURL(browser(), - embedded_test_server()->GetURL("/empty.html")); + ASSERT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL("/empty.html"))); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(web_contents); diff --git a/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.cc b/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.cc index 5babb5433aa..cb6cc4e6e49 100644 --- a/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.cc +++ b/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.cc @@ -23,7 +23,7 @@ namespace extensions { ExtensionFunction::ResponseAction ChromeWebViewInternalContextMenusCreateFunction::Run() { std::unique_ptr<webview::ContextMenusCreate::Params> params( - webview::ContextMenusCreate::Params::Create(*args_)); + webview::ContextMenusCreate::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); MenuItem::Id id( @@ -37,10 +37,13 @@ ChromeWebViewInternalContextMenusCreateFunction::Run() { id.string_uid = *params->create_properties.id; } else { // The Generated Id is added by web_view_internal_custom_bindings.js. - base::DictionaryValue* properties = NULL; - EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(1, &properties)); - EXTENSION_FUNCTION_VALIDATE(properties->GetInteger( - extensions::context_menus_api_helpers::kGeneratedIdKey, &id.uid)); + EXTENSION_FUNCTION_VALIDATE(args().size() >= 2); + EXTENSION_FUNCTION_VALIDATE(args()[1].is_dict()); + const base::Value& properties = args()[1]; + absl::optional<int> result = properties.FindIntKey( + extensions::context_menus_api_helpers::kGeneratedIdKey); + EXTENSION_FUNCTION_VALIDATE(result); + id.uid = *result; } std::string error; @@ -53,7 +56,7 @@ ChromeWebViewInternalContextMenusCreateFunction::Run() { ExtensionFunction::ResponseAction ChromeWebViewInternalContextMenusUpdateFunction::Run() { std::unique_ptr<webview::ContextMenusUpdate::Params> params( - webview::ContextMenusUpdate::Params::Create(*args_)); + webview::ContextMenusUpdate::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); Profile* profile = Profile::FromBrowserContext(browser_context()); @@ -81,7 +84,7 @@ ChromeWebViewInternalContextMenusUpdateFunction::Run() { ExtensionFunction::ResponseAction ChromeWebViewInternalContextMenusRemoveFunction::Run() { std::unique_ptr<webview::ContextMenusRemove::Params> params( - webview::ContextMenusRemove::Params::Create(*args_)); + webview::ContextMenusRemove::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); MenuManager* menu_manager = @@ -118,7 +121,7 @@ ChromeWebViewInternalContextMenusRemoveFunction::Run() { ExtensionFunction::ResponseAction ChromeWebViewInternalContextMenusRemoveAllFunction::Run() { std::unique_ptr<webview::ContextMenusRemoveAll::Params> params( - webview::ContextMenusRemoveAll::Params::Create(*args_)); + webview::ContextMenusRemoveAll::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); MenuManager* menu_manager = @@ -142,7 +145,7 @@ ChromeWebViewInternalShowContextMenuFunction:: ExtensionFunction::ResponseAction ChromeWebViewInternalShowContextMenuFunction::Run() { std::unique_ptr<webview::ShowContextMenu::Params> params( - webview::ShowContextMenu::Params::Create(*args_)); + webview::ShowContextMenu::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); // TODO(lazyboy): Actually implement filtering menu items. diff --git a/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h b/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h index b9f63549d5a..f9a4f9f1d06 100644 --- a/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h +++ b/chromium/chrome/browser/extensions/api/web_view/chrome_web_view_internal_api.h @@ -23,14 +23,16 @@ class ChromeWebViewInternalContextMenusCreateFunction WEBVIEWINTERNAL_CONTEXTMENUSCREATE) ChromeWebViewInternalContextMenusCreateFunction() {} + ChromeWebViewInternalContextMenusCreateFunction( + const ChromeWebViewInternalContextMenusCreateFunction&) = delete; + ChromeWebViewInternalContextMenusCreateFunction& operator=( + const ChromeWebViewInternalContextMenusCreateFunction&) = delete; + protected: ~ChromeWebViewInternalContextMenusCreateFunction() override {} // ExtensionFunction implementation. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeWebViewInternalContextMenusCreateFunction); }; class ChromeWebViewInternalContextMenusUpdateFunction @@ -40,14 +42,16 @@ class ChromeWebViewInternalContextMenusUpdateFunction WEBVIEWINTERNAL_CONTEXTMENUSUPDATE) ChromeWebViewInternalContextMenusUpdateFunction() {} + ChromeWebViewInternalContextMenusUpdateFunction( + const ChromeWebViewInternalContextMenusUpdateFunction&) = delete; + ChromeWebViewInternalContextMenusUpdateFunction& operator=( + const ChromeWebViewInternalContextMenusUpdateFunction&) = delete; + protected: ~ChromeWebViewInternalContextMenusUpdateFunction() override {} // ExtensionFunction implementation. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeWebViewInternalContextMenusUpdateFunction); }; class ChromeWebViewInternalContextMenusRemoveFunction @@ -57,14 +61,16 @@ class ChromeWebViewInternalContextMenusRemoveFunction WEBVIEWINTERNAL_CONTEXTMENUSREMOVE) ChromeWebViewInternalContextMenusRemoveFunction() {} + ChromeWebViewInternalContextMenusRemoveFunction( + const ChromeWebViewInternalContextMenusRemoveFunction&) = delete; + ChromeWebViewInternalContextMenusRemoveFunction& operator=( + const ChromeWebViewInternalContextMenusRemoveFunction&) = delete; + protected: ~ChromeWebViewInternalContextMenusRemoveFunction() override {} // ExtensionFunction implementation. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeWebViewInternalContextMenusRemoveFunction); }; class ChromeWebViewInternalContextMenusRemoveAllFunction @@ -74,14 +80,16 @@ class ChromeWebViewInternalContextMenusRemoveAllFunction WEBVIEWINTERNAL_CONTEXTMENUSREMOVEALL) ChromeWebViewInternalContextMenusRemoveAllFunction() {} + ChromeWebViewInternalContextMenusRemoveAllFunction( + const ChromeWebViewInternalContextMenusRemoveAllFunction&) = delete; + ChromeWebViewInternalContextMenusRemoveAllFunction& operator=( + const ChromeWebViewInternalContextMenusRemoveAllFunction&) = delete; + protected: ~ChromeWebViewInternalContextMenusRemoveAllFunction() override {} // ExtensionFunction implementation. ResponseAction Run() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ChromeWebViewInternalContextMenusRemoveAllFunction); }; class ChromeWebViewInternalShowContextMenuFunction @@ -92,11 +100,14 @@ class ChromeWebViewInternalShowContextMenuFunction ChromeWebViewInternalShowContextMenuFunction(); + ChromeWebViewInternalShowContextMenuFunction( + const ChromeWebViewInternalShowContextMenuFunction&) = delete; + ChromeWebViewInternalShowContextMenuFunction& operator=( + const ChromeWebViewInternalShowContextMenuFunction&) = delete; + protected: ~ChromeWebViewInternalShowContextMenuFunction() override; ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(ChromeWebViewInternalShowContextMenuFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc index e601a2b5c01..03c371db566 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc @@ -169,7 +169,7 @@ WebrtcAudioPrivateGetAssociatedSinkFunction:: ExtensionFunction::ResponseAction WebrtcAudioPrivateGetAssociatedSinkFunction::Run() { - params_ = wap::GetAssociatedSink::Params::Create(*args_); + params_ = wap::GetAssociatedSink::Params::Create(args()); DCHECK_CURRENTLY_ON(BrowserThread::UI); EXTENSION_FUNCTION_VALIDATE(params_.get()); InitDeviceIDSalt(); diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h index a994de22183..dbb944e2fd7 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h @@ -55,6 +55,11 @@ class WebrtcAudioPrivateEventService class WebrtcAudioPrivateFunction : public ExtensionFunction { protected: WebrtcAudioPrivateFunction(); + + WebrtcAudioPrivateFunction(const WebrtcAudioPrivateFunction&) = delete; + WebrtcAudioPrivateFunction& operator=(const WebrtcAudioPrivateFunction&) = + delete; + ~WebrtcAudioPrivateFunction() override; protected: @@ -74,8 +79,6 @@ class WebrtcAudioPrivateFunction : public ExtensionFunction { private: std::string device_id_salt_; std::unique_ptr<media::AudioSystem> audio_system_; - - DISALLOW_COPY_AND_ASSIGN(WebrtcAudioPrivateFunction); }; class WebrtcAudioPrivateGetSinksFunction : public WebrtcAudioPrivateFunction { diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc index 9111dde312e..6a0f53046f0 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc @@ -98,7 +98,7 @@ class AudioWaitingExtensionTest : public ExtensionApiTest { base::RunLoop().RunUntilIdle(); if (audio_playing) break; - base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100)); + base::PlatformThread::Sleep(base::Milliseconds(100)); } if (!audio_playing) FAIL() << "Audio did not start playing within ~5 seconds."; @@ -123,14 +123,13 @@ class WebrtcAudioPrivateTest : public AudioWaitingExtensionTest { params->Append(std::move(request_info)); } - std::unique_ptr<base::Value> InvokeGetSinks(base::ListValue** sink_list) { + std::unique_ptr<base::Value> InvokeGetSinks() { scoped_refptr<WebrtcAudioPrivateGetSinksFunction> function = new WebrtcAudioPrivateGetSinksFunction(); function->set_source_url(source_url_); std::unique_ptr<base::Value> result( RunFunctionAndReturnSingleResult(function.get(), "[]", browser())); - result->GetAsList(sink_list); return result; } @@ -143,23 +142,22 @@ IN_PROC_BROWSER_TEST_F(WebrtcAudioPrivateTest, GetSinks) { AudioDeviceDescriptions devices; GetAudioDeviceDescriptions(false, &devices); - base::ListValue* sink_list = NULL; - std::unique_ptr<base::Value> result = InvokeGetSinks(&sink_list); + std::unique_ptr<base::Value> result = InvokeGetSinks(); + const base::ListValue& sink_list = base::Value::AsListValue(*result); std::string result_string; JSONWriter::Write(*result, &result_string); VLOG(2) << result_string; - EXPECT_EQ(devices.size(), sink_list->GetSize()); + EXPECT_EQ(devices.size(), sink_list.GetList().size()); // Iterate through both lists in lockstep and compare. The order // should be identical. size_t ix = 0; AudioDeviceDescriptions::const_iterator it = devices.begin(); - for (; ix < sink_list->GetSize() && it != devices.end(); - ++ix, ++it) { - base::DictionaryValue* dict = NULL; - sink_list->GetDictionary(ix, &dict); + for (; ix < sink_list.GetList().size() && it != devices.end(); ++ix, ++it) { + const base::DictionaryValue* dict = NULL; + sink_list.GetDictionary(ix, &dict); std::string sink_id; dict->GetString("sinkId", &sink_id); @@ -205,8 +203,8 @@ IN_PROC_BROWSER_TEST_F(WebrtcAudioPrivateTest, GetAssociatedSink) { raw_device_id); base::ListValue parameters; - parameters.AppendString(origin.spec()); - parameters.AppendString(source_id_in_origin); + parameters.Append(origin.spec()); + parameters.Append(source_id_in_origin); std::string parameter_string; JSONWriter::Write(parameters, ¶meter_string); @@ -292,10 +290,10 @@ IN_PROC_BROWSER_TEST_F(HangoutServicesBrowserTest, // This runs the end-to-end JavaScript test for the Hangout Services // component extension, which uses the webrtcAudioPrivate API among // others. - ui_test_utils::NavigateToURL( + ASSERT_TRUE(ui_test_utils::NavigateToURL( browser(), https_server().GetURL("any-subdomain.google.com", - "/extensions/hangout_services_test.html")); + "/extensions/hangout_services_test.html"))); WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); WaitUntilAudioIsPlaying(tab); diff --git a/chromium/chrome/browser/extensions/api/webrtc_desktop_capture_private/webrtc_desktop_capture_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_desktop_capture_private/webrtc_desktop_capture_private_api.cc index 8cc5270d16a..74788f71e6a 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_desktop_capture_private/webrtc_desktop_capture_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_desktop_capture_private/webrtc_desktop_capture_private_api.cc @@ -38,17 +38,16 @@ WebrtcDesktopCapturePrivateChooseDesktopMediaFunction::Run() { using Params = extensions::api::webrtc_desktop_capture_private::ChooseDesktopMedia ::Params; - const auto& list = args_->GetList(); - EXTENSION_FUNCTION_VALIDATE(list.size() > 0); - const auto& request_id_value = list[0]; + EXTENSION_FUNCTION_VALIDATE(args().size() > 0); + const auto& request_id_value = args()[0]; EXTENSION_FUNCTION_VALIDATE(request_id_value.is_int()); request_id_ = request_id_value.GetInt(); DesktopCaptureRequestsRegistry::GetInstance()->AddRequest(source_process_id(), request_id_, this); - args_->EraseListIter(list.begin()); + mutable_args().erase(args().begin()); - std::unique_ptr<Params> params = Params::Create(*args_); + std::unique_ptr<Params> params = Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params.get()); content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( diff --git a/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc index ee09eff01ca..27d539809b2 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_from_web_accessible_resource_browsertest.cc @@ -19,6 +19,12 @@ namespace extensions { class WebRtcFromWebAccessibleResourceTest : public ExtensionApiTest { public: WebRtcFromWebAccessibleResourceTest() {} + + WebRtcFromWebAccessibleResourceTest( + const WebRtcFromWebAccessibleResourceTest&) = delete; + WebRtcFromWebAccessibleResourceTest& operator=( + const WebRtcFromWebAccessibleResourceTest&) = delete; + ~WebRtcFromWebAccessibleResourceTest() override {} // InProcessBrowserTest: @@ -43,9 +49,6 @@ class WebRtcFromWebAccessibleResourceTest : public ExtensionApiTest { ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( "webrtc_from_web_accessible_resource"))); } - - private: - DISALLOW_COPY_AND_ASSIGN(WebRtcFromWebAccessibleResourceTest); }; // Verify that a chrome-extension:// web accessible URL can successfully access @@ -65,7 +68,7 @@ IN_PROC_BROWSER_TEST_F(WebRtcFromWebAccessibleResourceTest, permissions::PermissionRequestObserver permission_request_observer( web_contents); extensions::ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_TRUE(catcher.GetNextResult()); EXPECT_TRUE(permission_request_observer.request_shown()); @@ -89,7 +92,7 @@ IN_PROC_BROWSER_TEST_F(WebRtcFromWebAccessibleResourceTest, permissions::PermissionRequestObserver permission_request_observer( web_contents); extensions::ResultCatcher catcher; - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); ASSERT_TRUE(catcher.GetNextResult()); EXPECT_TRUE(permission_request_observer.request_shown()); diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/OWNERS b/chromium/chrome/browser/extensions/api/webrtc_logging_private/OWNERS index c954e4277f5..e5e4f93daa3 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/OWNERS +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/OWNERS @@ -1,3 +1,2 @@ eladalon@chromium.org -grunell@chromium.org guidou@chromium.org diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc index 9a5fc00d8b8..9fe68cb5364 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.cc @@ -255,7 +255,7 @@ void WebrtcLoggingPrivateFunctionWithRecordingDoneCallback::FireCallback( ExtensionFunction::ResponseAction WebrtcLoggingPrivateSetMetaDataFunction::Run() { std::unique_ptr<SetMetaData::Params> params( - SetMetaData::Params::Create(*args_)); + SetMetaData::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); WebRtcLoggingController::GenericDoneCallback callback; @@ -275,7 +275,7 @@ WebrtcLoggingPrivateSetMetaDataFunction::Run() { } ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartFunction::Run() { - std::unique_ptr<Start::Params> params(Start::Params::Create(*args_)); + std::unique_ptr<Start::Params> params(Start::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); WebRtcLoggingController::GenericDoneCallback callback; @@ -292,7 +292,7 @@ ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartFunction::Run() { ExtensionFunction::ResponseAction WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::Run() { std::unique_ptr<SetUploadOnRenderClose::Params> params( - SetUploadOnRenderClose::Params::Create(*args_)); + SetUploadOnRenderClose::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; @@ -309,7 +309,7 @@ WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::Run() { } ExtensionFunction::ResponseAction WebrtcLoggingPrivateStopFunction::Run() { - std::unique_ptr<Stop::Params> params(Stop::Params::Create(*args_)); + std::unique_ptr<Stop::Params> params(Stop::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); WebRtcLoggingController::GenericDoneCallback callback; @@ -324,7 +324,7 @@ ExtensionFunction::ResponseAction WebrtcLoggingPrivateStopFunction::Run() { } ExtensionFunction::ResponseAction WebrtcLoggingPrivateStoreFunction::Run() { - std::unique_ptr<Store::Params> params(Store::Params::Create(*args_)); + std::unique_ptr<Store::Params> params(Store::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); WebRtcLoggingController::GenericDoneCallback callback; @@ -344,7 +344,7 @@ ExtensionFunction::ResponseAction WebrtcLoggingPrivateStoreFunction::Run() { ExtensionFunction::ResponseAction WebrtcLoggingPrivateUploadStoredFunction::Run() { std::unique_ptr<UploadStored::Params> params( - UploadStored::Params::Create(*args_)); + UploadStored::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; @@ -364,7 +364,7 @@ WebrtcLoggingPrivateUploadStoredFunction::Run() { } ExtensionFunction::ResponseAction WebrtcLoggingPrivateUploadFunction::Run() { - std::unique_ptr<Upload::Params> params(Upload::Params::Create(*args_)); + std::unique_ptr<Upload::Params> params(Upload::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; @@ -381,7 +381,7 @@ ExtensionFunction::ResponseAction WebrtcLoggingPrivateUploadFunction::Run() { } ExtensionFunction::ResponseAction WebrtcLoggingPrivateDiscardFunction::Run() { - std::unique_ptr<Discard::Params> params(Discard::Params::Create(*args_)); + std::unique_ptr<Discard::Params> params(Discard::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); WebRtcLoggingController::GenericDoneCallback callback; @@ -398,7 +398,7 @@ ExtensionFunction::ResponseAction WebrtcLoggingPrivateDiscardFunction::Run() { ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartRtpDumpFunction::Run() { std::unique_ptr<StartRtpDump::Params> params( - StartRtpDump::Params::Create(*args_)); + StartRtpDump::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (!params->incoming && !params->outgoing) { @@ -431,7 +431,7 @@ WebrtcLoggingPrivateStartRtpDumpFunction::Run() { ExtensionFunction::ResponseAction WebrtcLoggingPrivateStopRtpDumpFunction::Run() { std::unique_ptr<StopRtpDump::Params> params( - StopRtpDump::Params::Create(*args_)); + StopRtpDump::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (!params->incoming && !params->outgoing) { @@ -468,7 +468,7 @@ WebrtcLoggingPrivateStartAudioDebugRecordingsFunction::Run() { } std::unique_ptr<StartAudioDebugRecordings::Params> params( - StartAudioDebugRecordings::Params::Create(*args_)); + StartAudioDebugRecordings::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); if (params->seconds < 0) { @@ -488,7 +488,7 @@ WebrtcLoggingPrivateStartAudioDebugRecordingsFunction::Run() { host, AudioDebugRecordingsHandler::kAudioDebugRecordingsHandlerKey)); audio_debug_recordings_handler->StartAudioDebugRecordings( - host, base::TimeDelta::FromSeconds(params->seconds), + host, base::Seconds(params->seconds), base::BindOnce( &WebrtcLoggingPrivateStartAudioDebugRecordingsFunction::FireCallback, this), @@ -505,7 +505,7 @@ WebrtcLoggingPrivateStopAudioDebugRecordingsFunction::Run() { } std::unique_ptr<StopAudioDebugRecordings::Params> params( - StopAudioDebugRecordings::Params::Create(*args_)); + StopAudioDebugRecordings::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; @@ -533,7 +533,7 @@ WebrtcLoggingPrivateStopAudioDebugRecordingsFunction::Run() { ExtensionFunction::ResponseAction WebrtcLoggingPrivateStartEventLoggingFunction::Run() { std::unique_ptr<StartEventLogging::Params> params( - StartEventLogging::Params::Create(*args_)); + StartEventLogging::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params.get()); std::string error; diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc index 2203169188c..2fe49c7561f 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_apitest.cc @@ -152,7 +152,7 @@ class WebrtcLoggingPrivateApiTest : public extensions::ExtensionApiTest { request_info->SetInteger( "tabId", extensions::ExtensionTabUtil::GetTabId(web_contents())); parameters->Append(std::move(request_info)); - parameters->AppendString( + parameters->Append( web_contents()->GetLastCommittedURL().GetOrigin().spec()); } @@ -263,8 +263,8 @@ class WebrtcLoggingPrivateApiTest : public extensions::ExtensionApiTest { bool StartRtpDump(bool incoming, bool outgoing) { base::ListValue params; AppendTabIdAndUrl(¶ms); - params.AppendBoolean(incoming); - params.AppendBoolean(outgoing); + params.Append(incoming); + params.Append(outgoing); constexpr bool value_expected = false; std::unique_ptr<base::Value> value = RunFunction<WebrtcLoggingPrivateStartRtpDumpFunction>(params); @@ -279,8 +279,8 @@ class WebrtcLoggingPrivateApiTest : public extensions::ExtensionApiTest { bool StopRtpDump(bool incoming, bool outgoing) { base::ListValue params; AppendTabIdAndUrl(¶ms); - params.AppendBoolean(incoming); - params.AppendBoolean(outgoing); + params.Append(incoming); + params.Append(outgoing); constexpr bool value_expected = false; std::unique_ptr<base::Value> value = RunFunction<WebrtcLoggingPrivateStopRtpDumpFunction>(params); @@ -295,7 +295,7 @@ class WebrtcLoggingPrivateApiTest : public extensions::ExtensionApiTest { bool StoreLog(const std::string& log_id) { base::ListValue params; AppendTabIdAndUrl(¶ms); - params.AppendString(log_id); + params.Append(log_id); constexpr bool value_expected = false; std::unique_ptr<base::Value> value = RunFunction<WebrtcLoggingPrivateStoreFunction>(params); @@ -310,7 +310,7 @@ class WebrtcLoggingPrivateApiTest : public extensions::ExtensionApiTest { bool UploadStoredLog(const std::string& log_id, std::string* report_id) { base::ListValue params; AppendTabIdAndUrl(¶ms); - params.AppendString(log_id); + params.Append(log_id); constexpr bool value_expected = true; std::unique_ptr<base::Value> value = RunFunction<WebrtcLoggingPrivateUploadStoredFunction>(params); @@ -328,7 +328,7 @@ class WebrtcLoggingPrivateApiTest : public extensions::ExtensionApiTest { bool StartAudioDebugRecordings(int seconds) { base::ListValue params; AppendTabIdAndUrl(¶ms); - params.AppendInteger(seconds); + params.Append(seconds); constexpr bool value_expected = true; std::unique_ptr<base::Value> value = RunFunction<WebrtcLoggingPrivateStartAudioDebugRecordingsFunction>( @@ -365,10 +365,10 @@ class WebrtcLoggingPrivateApiTest : public extensions::ExtensionApiTest { base::ListValue params; AppendTabIdAndUrl(¶ms); - params.AppendString(session_id); - params.AppendInteger(max_log_size_bytes); - params.AppendInteger(output_period_ms); - params.AppendInteger(web_app_id); + params.Append(session_id); + params.Append(max_log_size_bytes); + params.Append(output_period_ms); + params.Append(web_app_id); if (expect_success) { scoped_refptr<WebrtcLoggingPrivateStartEventLoggingFunction> function( @@ -581,7 +581,7 @@ IN_PROC_BROWSER_TEST_F(WebrtcLoggingPrivateApiTest, TestStartStopRtpDump) { IN_PROC_BROWSER_TEST_F(WebrtcLoggingPrivateApiTest, TestStoreWithoutLog) { base::ListValue parameters; AppendTabIdAndUrl(¶meters); - parameters.AppendString("MyLogId"); + parameters.Append("MyLogId"); scoped_refptr<WebrtcLoggingPrivateStoreFunction> store( CreateFunction<WebrtcLoggingPrivateStoreFunction>()); const std::string error = utils::RunFunctionAndReturnError( diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc index b74cae30d3e..7522c34be60 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc @@ -15,15 +15,18 @@ class WebrtcLoggingPrivateApiBrowserTest : public extensions::PlatformAppBrowserTest { public: WebrtcLoggingPrivateApiBrowserTest() = default; + + WebrtcLoggingPrivateApiBrowserTest( + const WebrtcLoggingPrivateApiBrowserTest&) = delete; + WebrtcLoggingPrivateApiBrowserTest& operator=( + const WebrtcLoggingPrivateApiBrowserTest&) = delete; + ~WebrtcLoggingPrivateApiBrowserTest() override = default; base::FilePath webrtc_logs_path() { return webrtc_logging::TextLogList:: GetWebRtcLogDirectoryForBrowserContextPath(profile()->GetPath()); } - - private: - DISALLOW_COPY_AND_ASSIGN(WebrtcLoggingPrivateApiBrowserTest); }; #if defined(OS_LINUX) || defined(OS_CHROMEOS) diff --git a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc index 28c444906c8..44fb1f598d5 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc +++ b/chromium/chrome/browser/extensions/api/webstore_private/extension_install_status_unittest.cc @@ -52,6 +52,10 @@ class ExtensionInstallStatusTest : public BrowserWithTestWindowTest { public: ExtensionInstallStatusTest() = default; + ExtensionInstallStatusTest(const ExtensionInstallStatusTest&) = delete; + ExtensionInstallStatusTest& operator=(const ExtensionInstallStatusTest&) = + delete; + std::string GenerateArgs(const char* id) { return base::StringPrintf(R"(["%s"])", id); } @@ -86,9 +90,6 @@ class ExtensionInstallStatusTest : public BrowserWithTestWindowTest { profile()->GetTestingPrefService()->SetUserPref( prefs::kCloudExtensionRequestIds, std::move(id_values)); } - - private: - DISALLOW_COPY_AND_ASSIGN(ExtensionInstallStatusTest); }; TEST_F(ExtensionInstallStatusTest, ExtensionEnabled) { diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc index af9b07fdefd..c681f487239 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.cc @@ -44,8 +44,8 @@ #include "components/crx_file/id_util.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" -#include "components/safe_browsing/content/browser/safe_browsing_metrics_collector.h" #include "components/safe_browsing/content/browser/safe_browsing_navigation_observer_manager.h" +#include "components/safe_browsing/core/browser/safe_browsing_metrics_collector.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/gpu_feature_checker.h" #include "content/public/browser/storage_partition.h" @@ -97,6 +97,10 @@ namespace { class PendingApprovals { public: PendingApprovals(); + + PendingApprovals(const PendingApprovals&) = delete; + PendingApprovals& operator=(const PendingApprovals&) = delete; + ~PendingApprovals(); void PushApproval(std::unique_ptr<WebstoreInstaller::Approval> approval); @@ -110,8 +114,6 @@ class PendingApprovals { std::vector<std::unique_ptr<WebstoreInstaller::Approval>>; ApprovalList approvals_; - - DISALLOW_COPY_AND_ASSIGN(PendingApprovals); }; PendingApprovals::PendingApprovals() {} @@ -410,7 +412,7 @@ std::u16string WebstorePrivateBeginInstallWithManifest3Function:: ExtensionFunction::ResponseAction WebstorePrivateBeginInstallWithManifest3Function::Run() { - params_ = Params::Create(*args_); + params_ = Params::Create(args()); EXTENSION_FUNCTION_VALIDATE(params_); profile_ = Profile::FromBrowserContext(browser_context()); @@ -907,7 +909,7 @@ WebstorePrivateCompleteInstallFunction:: ExtensionFunction::ResponseAction WebstorePrivateCompleteInstallFunction::Run() { std::unique_ptr<CompleteInstall::Params> params( - CompleteInstall::Params::Create(*args_)); + CompleteInstall::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); Profile* const profile = Profile::FromBrowserContext(browser_context()); if (profile->IsGuestSession() || profile->IsOffTheRecord()) { @@ -1031,7 +1033,7 @@ WebstorePrivateSetStoreLoginFunction:: ExtensionFunction::ResponseAction WebstorePrivateSetStoreLoginFunction::Run() { std::unique_ptr<SetStoreLogin::Params> params( - SetStoreLogin::Params::Create(*args_)); + SetStoreLogin::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); SetWebstoreLogin(Profile::FromBrowserContext(browser_context()), params->login); @@ -1117,7 +1119,7 @@ WebstorePrivateIsPendingCustodianApprovalFunction:: ExtensionFunction::ResponseAction WebstorePrivateIsPendingCustodianApprovalFunction::Run() { std::unique_ptr<IsPendingCustodianApproval::Params> params( - IsPendingCustodianApproval::Params::Create(*args_)); + IsPendingCustodianApproval::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); if (!Profile::FromBrowserContext(browser_context())->IsSupervised()) @@ -1213,7 +1215,7 @@ WebstorePrivateGetExtensionStatusFunction:: ExtensionFunction::ResponseAction WebstorePrivateGetExtensionStatusFunction::Run() { std::unique_ptr<GetExtensionStatus::Params> params( - GetExtensionStatus::Params::Create(*args_)); + GetExtensionStatus::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const ExtensionId& extension_id = params->id; @@ -1283,7 +1285,7 @@ WebstorePrivateRequestExtensionFunction:: ExtensionFunction::ResponseAction WebstorePrivateRequestExtensionFunction::Run() { std::unique_ptr<RequestExtension::Params> params( - RequestExtension::Params::Create(*args_)); + RequestExtension::Params::Create(args())); EXTENSION_FUNCTION_VALIDATE(params); const ExtensionId& extension_id = params->id; diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h index f80ba9fbd65..90a31a6e821 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_api.h @@ -351,13 +351,16 @@ class WebstorePrivateGetReferrerChainFunction : public ExtensionFunction { WebstorePrivateGetReferrerChainFunction(); + WebstorePrivateGetReferrerChainFunction( + const WebstorePrivateGetReferrerChainFunction&) = delete; + WebstorePrivateGetReferrerChainFunction& operator=( + const WebstorePrivateGetReferrerChainFunction&) = delete; + private: ~WebstorePrivateGetReferrerChainFunction() override; // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(WebstorePrivateGetReferrerChainFunction); }; class WebstorePrivateGetExtensionStatusFunction : public ExtensionFunction { @@ -367,6 +370,11 @@ class WebstorePrivateGetExtensionStatusFunction : public ExtensionFunction { WebstorePrivateGetExtensionStatusFunction(); + WebstorePrivateGetExtensionStatusFunction( + const WebstorePrivateGetExtensionStatusFunction&) = delete; + WebstorePrivateGetExtensionStatusFunction& operator=( + const WebstorePrivateGetExtensionStatusFunction&) = delete; + private: ~WebstorePrivateGetExtensionStatusFunction() override; @@ -377,8 +385,6 @@ class WebstorePrivateGetExtensionStatusFunction : public ExtensionFunction { // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(WebstorePrivateGetExtensionStatusFunction); }; class WebstorePrivateRequestExtensionFunction : public ExtensionFunction { @@ -387,13 +393,16 @@ class WebstorePrivateRequestExtensionFunction : public ExtensionFunction { WEBSTOREPRIVATE_REQUESTEXTENSION) WebstorePrivateRequestExtensionFunction(); + WebstorePrivateRequestExtensionFunction( + const WebstorePrivateRequestExtensionFunction&) = delete; + WebstorePrivateRequestExtensionFunction& operator=( + const WebstorePrivateRequestExtensionFunction&) = delete; + private: ~WebstorePrivateRequestExtensionFunction() override; // Extensionfunction: ExtensionFunction::ResponseAction Run() override; - - DISALLOW_COPY_AND_ASSIGN(WebstorePrivateRequestExtensionFunction); }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc index 07e4431cf3b..9c25c6dda7d 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_apitest.cc @@ -137,6 +137,12 @@ class WebstoreInstallListener : public WebstoreInstaller::Delegate { class ExtensionWebstorePrivateApiTest : public MixinBasedExtensionApiTest { public: ExtensionWebstorePrivateApiTest() {} + + ExtensionWebstorePrivateApiTest(const ExtensionWebstorePrivateApiTest&) = + delete; + ExtensionWebstorePrivateApiTest& operator=( + const ExtensionWebstorePrivateApiTest&) = delete; + ~ExtensionWebstorePrivateApiTest() override {} void SetUpCommandLine(base::CommandLine* command_line) override { @@ -208,8 +214,6 @@ class ExtensionWebstorePrivateApiTest : public MixinBasedExtensionApiTest { base::FilePath webstore_install_dir_copy_; std::unique_ptr<ScopedTestDialogAutoConfirm> auto_confirm_install_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionWebstorePrivateApiTest); }; // Test cases for webstore origin frame blocking. @@ -218,7 +222,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, GURL url = embedded_test_server()->GetURL( "/extensions/api_test/webstore_private/noframe.html"); content::WebContents* web_contents = GetWebContents(); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Try to load the same URL, but with the current Chrome web store origin in // an iframe (i.e. http://www.example.com) @@ -241,7 +245,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, FrameErrorPageBlocked) { GURL url = embedded_test_server()->GetURL( "/extensions/api_test/webstore_private/noframe2.html"); content::WebContents* web_contents = GetWebContents(); - ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); // Try to load the same URL, but with the current Chrome web store origin in // an iframe (i.e. http://www.example.com) @@ -389,7 +393,7 @@ class ExtensionWebstorePrivateApiTestChild embedded_test_server_(std::make_unique<net::EmbeddedTestServer>()), logged_in_user_mixin_( &mixin_host_, - chromeos::LoggedInUserMixin::LogInType::kChild, + ash::LoggedInUserMixin::LogInType::kChild, embedded_test_server_.get(), this, true /* should_launch_browser */, @@ -433,7 +437,7 @@ class ExtensionWebstorePrivateApiTestChild true); } - chromeos::LoggedInUserMixin* GetLoggedInUserMixin() { + ash::LoggedInUserMixin* GetLoggedInUserMixin() { return &logged_in_user_mixin_; } @@ -473,7 +477,7 @@ class ExtensionWebstorePrivateApiTestChild private: // Create another embedded test server to avoid starting the same one twice. std::unique_ptr<net::EmbeddedTestServer> embedded_test_server_; - chromeos::LoggedInUserMixin logged_in_user_mixin_; + ash::LoggedInUserMixin logged_in_user_mixin_; absl::optional<NextDialogAction> next_dialog_action_; }; @@ -667,8 +671,9 @@ class ExtensionWebstorePrivateApiAllowlistEnforcementTest IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest, EnhancedSafeBrowsingNotAllowlisted) { - safe_browsing::SetSafeBrowsingState(browser()->profile()->GetPrefs(), - safe_browsing::ENHANCED_PROTECTION); + safe_browsing::SetSafeBrowsingState( + browser()->profile()->GetPrefs(), + safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION); ASSERT_TRUE( RunInstallTest("safebrowsing_not_allowlisted.html", "extension.crx")); @@ -683,8 +688,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest, IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest, EnhancedSafeBrowsingAllowlisted) { - safe_browsing::SetSafeBrowsingState(browser()->profile()->GetPrefs(), - safe_browsing::ENHANCED_PROTECTION); + safe_browsing::SetSafeBrowsingState( + browser()->profile()->GetPrefs(), + safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION); ASSERT_TRUE(RunInstallTest("safebrowsing_allowlisted.html", "extension.crx")); EXPECT_EQ(ALLOWLIST_UNDEFINED, @@ -694,8 +700,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest, IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiAllowlistEnforcementTest, StandardSafeBrowsingNotAllowlisted) { - safe_browsing::SetSafeBrowsingState(browser()->profile()->GetPrefs(), - safe_browsing::STANDARD_PROTECTION); + safe_browsing::SetSafeBrowsingState( + browser()->profile()->GetPrefs(), + safe_browsing::SafeBrowsingState::STANDARD_PROTECTION); ASSERT_TRUE( RunInstallTest("safebrowsing_not_allowlisted.html", "extension.crx")); diff --git a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc index c54d04759a2..5270d01d6d4 100644 --- a/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc +++ b/chromium/chrome/browser/extensions/api/webstore_private/webstore_private_unittest.cc @@ -154,6 +154,11 @@ class WebstorePrivateExtensionInstallRequestBase : public ExtensionApiUnittest { : ExtensionApiUnittest( base::test::TaskEnvironment::TimeSource::MOCK_TIME) {} + WebstorePrivateExtensionInstallRequestBase( + const WebstorePrivateExtensionInstallRequestBase&) = delete; + WebstorePrivateExtensionInstallRequestBase& operator=( + const WebstorePrivateExtensionInstallRequestBase&) = delete; + std::string GenerateArgs(const char* id) { return base::StringPrintf(R"(["%s"])", id); } @@ -171,9 +176,6 @@ class WebstorePrivateExtensionInstallRequestBase : public ExtensionApiUnittest { ASSERT_TRUE(actual_response->is_string()); EXPECT_EQ(ToString(expected_response), actual_response->GetString()); } - - private: - DISALLOW_COPY_AND_ASSIGN(WebstorePrivateExtensionInstallRequestBase); }; class WebstorePrivateGetExtensionStatusTest @@ -725,8 +727,9 @@ TEST_P(WebstorePrivateBeginInstallWithManifest3FrictionDialogTest, if (test_case.esb_user) { // Enable Enhanced Protection - safe_browsing::SetSafeBrowsingState(profile()->GetPrefs(), - safe_browsing::ENHANCED_PROTECTION); + safe_browsing::SetSafeBrowsingState( + profile()->GetPrefs(), + safe_browsing::SafeBrowsingState::ENHANCED_PROTECTION); } extension_service()->Init(); |