diff options
Diffstat (limited to 'chromium/chrome/browser/extensions')
251 files changed, 3510 insertions, 2099 deletions
diff --git a/chromium/chrome/browser/extensions/BUILD.gn b/chromium/chrome/browser/extensions/BUILD.gn index e26b2ba3fb5..000374bc06a 100644 --- a/chromium/chrome/browser/extensions/BUILD.gn +++ b/chromium/chrome/browser/extensions/BUILD.gn @@ -422,10 +422,6 @@ jumbo_static_library("extensions") { "blacklist_factory.h", "blacklist_state_fetcher.cc", "blacklist_state_fetcher.h", - "bookmark_app_extension_util.cc", - "bookmark_app_extension_util.h", - "bookmark_app_helper.cc", - "bookmark_app_helper.h", "browser_context_keyed_service_factories.cc", "browser_context_keyed_service_factories.h", "browser_extension_window_controller.cc", @@ -447,8 +443,6 @@ jumbo_static_library("extensions") { "chrome_content_browser_client_extensions_part.h", "chrome_content_verifier_delegate.cc", "chrome_content_verifier_delegate.h", - "chrome_extension_api_frame_id_map_helper.cc", - "chrome_extension_api_frame_id_map_helper.h", "chrome_extension_browser_constants.cc", "chrome_extension_browser_constants.h", "chrome_extension_chooser_dialog.h", @@ -764,6 +758,7 @@ jumbo_static_library("extensions") { "//chrome/common", "//chrome/common/extensions/api", "//components/safe_browsing:csd_proto", + "//components/safe_browsing:webprotect_proto", "//components/safe_browsing/db:util", "//components/signin/core/browser", "//content/public/browser", @@ -830,11 +825,14 @@ jumbo_static_library("extensions") { "//components/proxy_config", "//components/rappor", "//components/resources", + "//components/safe_browsing:buildflags", "//components/safe_browsing:csd_proto", "//components/safe_browsing:features", "//components/safe_browsing/common:safe_browsing_prefs", "//components/safe_browsing/db:database_manager", "//components/search_engines", + "//components/services/patch/content", + "//components/services/unzip/content", "//components/services/unzip/public/cpp", "//components/sessions", "//components/signin/public/identity_manager", @@ -997,7 +995,7 @@ jumbo_static_library("extensions") { "//components/drive", "//components/user_manager", "//media/capture:capture_lib", - "//media/capture/video/chromeos/mojo:cros_camera", + "//media/capture/video/chromeos/mojom:cros_camera", "//remoting/base", "//remoting/host", "//remoting/host/it2me:chrome_os_host", @@ -1100,7 +1098,6 @@ jumbo_static_library("extensions") { if (is_win) { deps += [ - "//chrome/services/wifi_util_win/public/mojom", "//third_party/iaccessible2", "//third_party/isimpledom", ] 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 d900d64d169..afee1976650 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 @@ -82,8 +82,7 @@ class ActivityLogPrivateGetExtensionActivitiesFunction }; // The implementation of activityLogPrivate.deleteActivities -class ActivityLogPrivateDeleteActivitiesFunction - : public UIThreadExtensionFunction { +class ActivityLogPrivateDeleteActivitiesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteActivities", ACTIVITYLOGPRIVATE_DELETEACTIVITIES) @@ -97,7 +96,7 @@ class ActivityLogPrivateDeleteActivitiesFunction // The implementation of activityLogPrivate.deleteActivitiesByExtension class ActivityLogPrivateDeleteActivitiesByExtensionFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteActivitiesByExtension", ACTIVITYLOGPRIVATE_DELETEACTIVITIESBYEXTENSION) @@ -110,8 +109,7 @@ class ActivityLogPrivateDeleteActivitiesByExtensionFunction }; // The implementation of activityLogPrivate.deleteDatabase -class ActivityLogPrivateDeleteDatabaseFunction - : public UIThreadExtensionFunction { +class ActivityLogPrivateDeleteDatabaseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteDatabase", ACTIVITYLOGPRIVATE_DELETEDATABASE) @@ -124,7 +122,7 @@ class ActivityLogPrivateDeleteDatabaseFunction }; // The implementation of activityLogPrivate.deleteUrls -class ActivityLogPrivateDeleteUrlsFunction : public UIThreadExtensionFunction { +class ActivityLogPrivateDeleteUrlsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("activityLogPrivate.deleteUrls", ACTIVITYLOGPRIVATE_DELETEURLS) 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 7636ce0380c..69f3e85c660 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 @@ -57,8 +57,8 @@ class ActivityLogApiTest : public ExtensionApiTest { base::CommandLine saved_cmdline_; }; -#if defined(OS_WIN) -// TODO(pmarch): fix flakiness on win debug - http://crbug.com/299393 +#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) +// TODO(crbug.com/299393): Flaky on Mac, Windows and Linux. #define MAYBE_TriggerEvent DISABLED_TriggerEvent #else #define MAYBE_TriggerEvent TriggerEvent diff --git a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h index 20a4924315b..5b42cd41d7a 100644 --- a/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h +++ b/chromium/chrome/browser/extensions/api/autofill_private/autofill_private_api.h @@ -13,7 +13,7 @@ namespace extensions { -class AutofillPrivateSaveAddressFunction : public UIThreadExtensionFunction { +class AutofillPrivateSaveAddressFunction : public ExtensionFunction { public: AutofillPrivateSaveAddressFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.saveAddress", @@ -31,7 +31,7 @@ class AutofillPrivateSaveAddressFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateSaveAddressFunction); }; -class AutofillPrivateGetCountryListFunction : public UIThreadExtensionFunction { +class AutofillPrivateGetCountryListFunction : public ExtensionFunction { public: AutofillPrivateGetCountryListFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.getCountryList", @@ -49,8 +49,7 @@ class AutofillPrivateGetCountryListFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetCountryListFunction); }; -class AutofillPrivateGetAddressComponentsFunction : - public UIThreadExtensionFunction { +class AutofillPrivateGetAddressComponentsFunction : public ExtensionFunction { public: AutofillPrivateGetAddressComponentsFunction() {} DECLARE_EXTENSION_FUNCTION("autofillPrivate.getAddressComponents", @@ -66,7 +65,7 @@ class AutofillPrivateGetAddressComponentsFunction : DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetAddressComponentsFunction); }; -class AutofillPrivateGetAddressListFunction : public UIThreadExtensionFunction { +class AutofillPrivateGetAddressListFunction : public ExtensionFunction { public: AutofillPrivateGetAddressListFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.getAddressList", @@ -84,7 +83,7 @@ class AutofillPrivateGetAddressListFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetAddressListFunction); }; -class AutofillPrivateSaveCreditCardFunction : public UIThreadExtensionFunction { +class AutofillPrivateSaveCreditCardFunction : public ExtensionFunction { public: AutofillPrivateSaveCreditCardFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.saveCreditCard", @@ -102,7 +101,7 @@ class AutofillPrivateSaveCreditCardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateSaveCreditCardFunction); }; -class AutofillPrivateRemoveEntryFunction : public UIThreadExtensionFunction { +class AutofillPrivateRemoveEntryFunction : public ExtensionFunction { public: AutofillPrivateRemoveEntryFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.removeEntry", @@ -120,8 +119,7 @@ class AutofillPrivateRemoveEntryFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateRemoveEntryFunction); }; -class AutofillPrivateValidatePhoneNumbersFunction : - public UIThreadExtensionFunction { +class AutofillPrivateValidatePhoneNumbersFunction : public ExtensionFunction { public: AutofillPrivateValidatePhoneNumbersFunction() {} DECLARE_EXTENSION_FUNCTION("autofillPrivate.validatePhoneNumbers", @@ -137,7 +135,7 @@ class AutofillPrivateValidatePhoneNumbersFunction : DISALLOW_COPY_AND_ASSIGN(AutofillPrivateValidatePhoneNumbersFunction); }; -class AutofillPrivateMaskCreditCardFunction : public UIThreadExtensionFunction { +class AutofillPrivateMaskCreditCardFunction : public ExtensionFunction { public: AutofillPrivateMaskCreditCardFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.maskCreditCard", @@ -155,8 +153,7 @@ class AutofillPrivateMaskCreditCardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(AutofillPrivateMaskCreditCardFunction); }; -class AutofillPrivateGetCreditCardListFunction - : public UIThreadExtensionFunction { +class AutofillPrivateGetCreditCardListFunction : public ExtensionFunction { public: AutofillPrivateGetCreditCardListFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.getCreditCardList", @@ -174,8 +171,7 @@ class AutofillPrivateGetCreditCardListFunction DISALLOW_COPY_AND_ASSIGN(AutofillPrivateGetCreditCardListFunction); }; -class AutofillPrivateMigrateCreditCardsFunction - : public UIThreadExtensionFunction { +class AutofillPrivateMigrateCreditCardsFunction : public ExtensionFunction { public: AutofillPrivateMigrateCreditCardsFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.migrateCreditCards", @@ -194,7 +190,7 @@ class AutofillPrivateMigrateCreditCardsFunction }; class AutofillPrivateLogServerCardLinkClickedFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: AutofillPrivateLogServerCardLinkClickedFunction(); DECLARE_EXTENSION_FUNCTION("autofillPrivate.logServerCardLinkClicked", diff --git a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc index b33da9fe462..f2333134976 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc +++ b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.cc @@ -56,11 +56,8 @@ bool ChromeAutomationInternalApiDelegate::GetTabById( content::WebContents** contents, std::string* error_msg) { *error_msg = tabs_constants::kTabNotFoundError; - return ExtensionTabUtil::GetTabById( - tab_id, browser_context, include_incognito, - nullptr, /* browser out param */ - nullptr, /* tab strip out param */ - contents, nullptr /* tab_index out param */); + return ExtensionTabUtil::GetTabById(tab_id, browser_context, + include_incognito, contents); } int ChromeAutomationInternalApiDelegate::GetTabId( @@ -69,7 +66,7 @@ int ChromeAutomationInternalApiDelegate::GetTabId( } content::WebContents* ChromeAutomationInternalApiDelegate::GetActiveWebContents( - UIThreadExtensionFunction* function) { + ExtensionFunction* function) { return ChromeExtensionFunctionDetails(function) .GetCurrentBrowser() ->tab_strip_model() diff --git a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h index 474b575dc6e..f2bdc737969 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h +++ b/chromium/chrome/browser/extensions/api/automation_internal/chrome_automation_internal_api_delegate.h @@ -26,7 +26,7 @@ class ChromeAutomationInternalApiDelegate std::string* error_msg) override; int GetTabId(content::WebContents* contents) override; content::WebContents* GetActiveWebContents( - UIThreadExtensionFunction* function) override; + ExtensionFunction* function) override; void EnableDesktop() override; ui::AXTreeID GetAXTreeID() override; void SetEventBundleSink(ui::AXEventBundleSink* sink) override; diff --git a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc index 95240d00bc2..2da1d159732 100644 --- a/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc +++ b/chromium/chrome/browser/extensions/api/bluetooth_low_energy/bluetooth_low_energy_apitest.cc @@ -321,6 +321,7 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ServiceEvents) { ExtensionTestMessageListener listener(true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth_low_energy/service_events"))); + EXPECT_TRUE(listener.WaitUntilSatisfied()); // These will create the identifier mappings. event_router()->GattServiceAdded( @@ -341,7 +342,6 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, ServiceEvents) { event_router()->GattServiceRemoved( mock_adapter_, device0_.get(), service0_.get()); - EXPECT_TRUE(listener.WaitUntilSatisfied()); ASSERT_EQ("ready", listener.message()) << listener.message(); listener.Reply("go"); @@ -366,12 +366,13 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetRemovedService) { .Times(1) .WillOnce(Return(service0_.get())); + ExtensionTestMessageListener get_service_success_listener(false); + event_router()->GattServiceAdded( mock_adapter_, device0_.get(), service0_.get()); event_router()->GattDiscoveryCompleteForService(mock_adapter_, service0_.get()); - ExtensionTestMessageListener get_service_success_listener(false); EXPECT_TRUE(get_service_success_listener.WaitUntilSatisfied()); ASSERT_EQ("getServiceSuccess", get_service_success_listener.message()) << get_service_success_listener.message(); @@ -382,10 +383,11 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, GetRemovedService) { EXPECT_CALL(*mock_adapter_, GetDevice(_)).Times(0); EXPECT_CALL(*device0_, GetGattService(kTestServiceId0)).Times(0); + ExtensionTestMessageListener get_service_fail_listener(true); + event_router()->GattServiceRemoved( mock_adapter_, device0_.get(), service0_.get()); - ExtensionTestMessageListener get_service_fail_listener(true); EXPECT_TRUE(get_service_fail_listener.WaitUntilSatisfied()); ASSERT_EQ("getServiceFail", get_service_fail_listener.message()) << get_service_fail_listener.message(); @@ -931,6 +933,7 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, DescriptorValueChanged) { ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII( "bluetooth_low_energy/descriptor_value_changed"))); + EXPECT_TRUE(listener.WaitUntilSatisfied()); // Cause events to be sent to the extension. std::vector<uint8_t> value; @@ -939,7 +942,6 @@ IN_PROC_BROWSER_TEST_F(BluetoothLowEnergyApiTest, DescriptorValueChanged) { event_router()->GattDescriptorValueChanged( mock_adapter_, desc1_.get(), value); - EXPECT_TRUE(listener.WaitUntilSatisfied()); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); diff --git a/chromium/chrome/browser/extensions/api/bookmark_manager_private/OWNERS b/chromium/chrome/browser/extensions/api/bookmark_manager_private/OWNERS new file mode 100644 index 00000000000..745d78d4c26 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/bookmark_manager_private/OWNERS @@ -0,0 +1,2 @@ +calamity@chromium.org +johntlee@chromium.org diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc index 81209a9ac4b..5f90d3df246 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_api_helpers_unittest.cc @@ -19,7 +19,7 @@ #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/managed/managed_bookmark_service.h" #include "components/bookmarks/test/bookmark_test_helpers.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" using bookmarks::BookmarkModel; @@ -65,7 +65,7 @@ class ExtensionBookmarksTest : public testing::Test { folder_, 0, base::ASCIIToUTF16("CNet"), GURL("http://cnet.com")); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; bookmarks::ManagedBookmarkService* managed_; BookmarkModel* model_; diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc index 3ee926982f7..12113c4f5d4 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc @@ -794,9 +794,9 @@ bool BookmarksExportFunction::RunOnReady() { // extensions use user gesture for export, so use USER_VISIBLE priority. // GetDefaultFilepathForBookmarkExport() might have to touch filesystem // (stat or access, for example), so this requires IO. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&GetDefaultFilepathForBookmarkExport), base::BindOnce(&BookmarksIOFunction::ShowSelectFileDialog, this, 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 d222c335e76..09b44ef1f9a 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 @@ -134,10 +134,9 @@ void BrailleControllerImpl::WriteDots(const std::vector<uint8_t>& cells, void BrailleControllerImpl::AddObserver(BrailleObserver* observer) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - if (!base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&BrailleControllerImpl::StartConnecting, - base::Unretained(this)))) { + if (!base::PostTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&BrailleControllerImpl::StartConnecting, + base::Unretained(this)))) { NOTREACHED(); } observers_.AddObserver(observer); @@ -174,8 +173,9 @@ void BrailleControllerImpl::StartConnecting() { } if (!sequenced_task_runner_) { - sequenced_task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + sequenced_task_runner_ = + base::CreateSequencedTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); } // Only try to connect after we've started to watch the @@ -213,7 +213,7 @@ void BrailleControllerImpl::OnSocketDirChangedOnTaskThread( LOG(ERROR) << "Error watching brlapi directory: " << path.value(); return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&BrailleControllerImpl::OnSocketDirChangedOnIOThread, base::Unretained(this))); @@ -272,11 +272,10 @@ void BrailleControllerImpl::ScheduleTryToConnect() { } VLOG(1) << "Scheduling connection retry to brlapi"; connect_scheduled_ = true; - base::PostDelayedTaskWithTraits( - FROM_HERE, {BrowserThread::IO}, - base::BindOnce(&BrailleControllerImpl::TryToConnect, - base::Unretained(this)), - kConnectionDelay); + base::PostDelayedTask(FROM_HERE, {BrowserThread::IO}, + base::BindOnce(&BrailleControllerImpl::TryToConnect, + base::Unretained(this)), + kConnectionDelay); } void BrailleControllerImpl::Disconnect() { @@ -318,7 +317,7 @@ void BrailleControllerImpl::DispatchKeys() { void BrailleControllerImpl::DispatchKeyEvent(std::unique_ptr<KeyEvent> event) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BrailleControllerImpl::DispatchKeyEvent, base::Unretained(this), base::Passed(&event))); @@ -332,7 +331,7 @@ void BrailleControllerImpl::DispatchKeyEvent(std::unique_ptr<KeyEvent> event) { void BrailleControllerImpl::DispatchOnDisplayStateChanged( std::unique_ptr<DisplayState> new_state) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - if (!base::PostTaskWithTraits( + if (!base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &BrailleControllerImpl::DispatchOnDisplayStateChanged, diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h index d6a88e094d4..2684e50134e 100644 --- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h +++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_api.h @@ -107,7 +107,7 @@ class BrailleDisplayPrivateWriteDotsFunction : public AsyncApiFunction { }; class BrailleDisplayPrivateUpdateBluetoothBrailleDisplayAddressFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { ~BrailleDisplayPrivateUpdateBluetoothBrailleDisplayAddressFunction() override {} ResponseAction Run() override; diff --git a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc index e9efd7d7ba0..037d634141f 100644 --- a/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/braille_display_private/braille_display_private_apitest.cc @@ -68,10 +68,9 @@ class MockBrlapiConnection : public BrlapiConnection { data_->connected = true; on_data_ready_ = on_data_ready; if (!data_->pending_keys.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&MockBrlapiConnection::NotifyDataReady, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&MockBrlapiConnection::NotifyDataReady, + base::Unretained(this))); } return CONNECT_SUCCESS; } @@ -80,7 +79,7 @@ class MockBrlapiConnection : public BrlapiConnection { data_->connected = false; if (data_->reappear_on_disconnect) { data_->display_columns *= 2; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &BrailleControllerImpl::PokeSocketDirForTesting, @@ -129,10 +128,9 @@ class MockBrlapiConnection : public BrlapiConnection { void NotifyDataReady() { on_data_ready_.Run(); if (!data_->pending_keys.empty()) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::IO}, - base::BindOnce(&MockBrlapiConnection::NotifyDataReady, - base::Unretained(this))); + base::PostTask(FROM_HERE, {content::BrowserThread::IO}, + base::BindOnce(&MockBrlapiConnection::NotifyDataReady, + base::Unretained(this))); } } 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 cd22764d64c..e73cd3f3032 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 @@ -351,13 +351,13 @@ bool BrowsingDataRemoverFunction::RunAsync() { ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA) { // If we're being asked to remove plugin data, check whether it's actually // supported. - PostTaskWithTraits( - FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, - base::TaskPriority::USER_VISIBLE}, - base::BindOnce( - &BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported, - this, PluginPrefs::GetForProfile(GetProfile()))); + PostTask(FROM_HERE, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, + base::TaskPriority::USER_VISIBLE}, + base::BindOnce( + &BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported, + this, PluginPrefs::GetForProfile(GetProfile()))); } else { StartRemoving(); } @@ -377,7 +377,7 @@ void BrowsingDataRemoverFunction::CheckRemovingPluginDataSupported( if (!PluginDataRemoverHelper::IsSupported(plugin_prefs.get())) removal_mask_ &= ~ChromeBrowsingDataRemoverDelegate::DATA_TYPE_PLUGIN_DATA; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&BrowsingDataRemoverFunction::StartRemoving, this)); } 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 d5a9a0c05a9..2a588cf744e 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 @@ -61,7 +61,7 @@ extern const char kInvalidOriginError[]; } // namespace extension_browsing_data_api_constants -class BrowsingDataSettingsFunction : public UIThreadExtensionFunction { +class BrowsingDataSettingsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("browsingData.settings", BROWSINGDATA_SETTINGS) diff --git a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc index e72b5ae5c9b..b2e4c22d486 100644 --- a/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc +++ b/chromium/chrome/browser/extensions/api/browsing_data/browsing_data_test.cc @@ -64,8 +64,7 @@ bool SetGaiaCookieForProfile(Profile* profile) { callback = base::BindLambdaForTesting( [&success, &loop_quit](net::CanonicalCookie::CookieInclusionStatus s) { - success = - (s == net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + success = s.IsInclude(); std::move(loop_quit).Run(); }); network::mojom::CookieManager* cookie_manager = @@ -76,8 +75,9 @@ bool SetGaiaCookieForProfile(Profile* profile) { cookie_manager->SetCanonicalCookie( cookie, google_url.scheme(), options, mojo::WrapCallbackWithDefaultInvokeIfNotRun( - std::move(callback), - net::CanonicalCookie::CookieInclusionStatus::EXCLUDE_UNKNOWN_ERROR)); + std::move(callback), net::CanonicalCookie::CookieInclusionStatus( + net::CanonicalCookie::CookieInclusionStatus:: + EXCLUDE_UNKNOWN_ERROR))); loop.Run(); return success; } 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 19e460c0dbc..c10602fe117 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 @@ -55,7 +55,7 @@ class BrowsingDataApiTest : public ExtensionServiceTestBase { browser_window_ = std::make_unique<TestBrowserWindow>(); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_ = std::make_unique<Browser>(params); diff --git a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc b/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc index a94ea2115e3..3aef65b5906 100644 --- a/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc +++ b/chromium/chrome/browser/extensions/api/cast_streaming/cast_streaming_apitest.cc @@ -434,18 +434,14 @@ IN_PROC_BROWSER_TEST_P(CastStreamingApiTestWithPixelOutput, // removed after launch. Note: CastStreamingApiTestWithPixelOutput.EndToEnd is // the only integration test exercising audio service loopback streams, so it's // a very important test to have. -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) -// Platforms launched on. +#if defined(OS_WIN) || defined(OS_MACOSX) || \ + (defined(OS_LINUX) && !defined(OS_CHROMEOS)) +// Platforms where the out of process audio service is supported. INSTANTIATE_TEST_SUITE_P(, CastStreamingApiTestWithPixelOutput, ::testing::Values(true)); -#elif defined(OS_MACOSX) || defined(OS_WIN) -// Supported platforms but not launched on. -INSTANTIATE_TEST_SUITE_P(, - CastStreamingApiTestWithPixelOutput, - ::testing::Bool()); #else -// Platforms where the out of process audio service isn't supported +// Platforms where the out of process audio service is not supported. INSTANTIATE_TEST_SUITE_P(, CastStreamingApiTestWithPixelOutput, ::testing::Values(false)); 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 42b5813d2a5..533bdee1e87 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 @@ -15,8 +15,10 @@ #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service.h" #include "chrome/browser/chromeos/certificate_provider/certificate_provider_service_factory.h" #include "chrome/browser/chromeos/certificate_provider/pin_dialog_manager.h" +#include "chrome/browser/chromeos/certificate_provider/security_token_pin_dialog_host.h" #include "chrome/common/extensions/api/certificate_provider.h" #include "chrome/common/extensions/api/certificate_provider_internal.h" +#include "chromeos/constants/security_token_pin_types.h" #include "net/cert/x509_certificate.h" #include "net/ssl/ssl_private_key.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" @@ -24,28 +26,28 @@ namespace api_cp = extensions::api::certificate_provider; namespace api_cpi = extensions::api::certificate_provider_internal; +using PinCodeType = chromeos::SecurityTokenPinCodeType; +using PinErrorLabel = chromeos::SecurityTokenPinErrorLabel; namespace { -chromeos::RequestPinView::RequestPinErrorType GetErrorTypeForView( - api_cp::PinRequestErrorType error_type) { +PinErrorLabel GetErrorLabelForDialog(api_cp::PinRequestErrorType error_type) { switch (error_type) { case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_INVALID_PIN: - return chromeos::RequestPinView::RequestPinErrorType::INVALID_PIN; + return PinErrorLabel::kInvalidPin; case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_INVALID_PUK: - return chromeos::RequestPinView::RequestPinErrorType::INVALID_PUK; + return PinErrorLabel::kInvalidPuk; case api_cp::PinRequestErrorType:: PIN_REQUEST_ERROR_TYPE_MAX_ATTEMPTS_EXCEEDED: - return chromeos::RequestPinView::RequestPinErrorType:: - MAX_ATTEMPTS_EXCEEDED; + return PinErrorLabel::kMaxAttemptsExceeded; case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_UNKNOWN_ERROR: - return chromeos::RequestPinView::RequestPinErrorType::UNKNOWN_ERROR; + return PinErrorLabel::kUnknown; case api_cp::PinRequestErrorType::PIN_REQUEST_ERROR_TYPE_NONE: - return chromeos::RequestPinView::RequestPinErrorType::NONE; + return PinErrorLabel::kNone; } NOTREACHED(); - return chromeos::RequestPinView::RequestPinErrorType::NONE; + return PinErrorLabel::kNone; } } // namespace @@ -216,11 +218,11 @@ CertificateProviderStopPinRequestFunction::Run() { // Extension provided an error, which means it intends to notify the user with // the error and not allow any more input. - chromeos::RequestPinView::RequestPinErrorType error_type = - GetErrorTypeForView(params->details.error_type); + const PinErrorLabel error_label = + GetErrorLabelForDialog(params->details.error_type); const chromeos::PinDialogManager::StopPinRequestResult stop_request_result = service->pin_dialog_manager()->StopPinRequestWithError( - extension()->id(), error_type, + extension()->id(), error_label, base::BindOnce( &CertificateProviderStopPinRequestFunction::OnPinRequestStopped, this)); @@ -238,13 +240,7 @@ CertificateProviderStopPinRequestFunction::Run() { } void CertificateProviderStopPinRequestFunction::OnPinRequestStopped() { - chromeos::CertificateProviderService* const service = - chromeos::CertificateProviderServiceFactory::GetForBrowserContext( - browser_context()); - DCHECK(service); - Respond(NoArguments()); - service->pin_dialog_manager()->OnPinDialogClosed(); } CertificateProviderRequestPinFunction:: @@ -274,19 +270,19 @@ ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() { api_cp::RequestPin::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - api_cp::PinRequestType pin_request_type = + const api_cp::PinRequestType pin_request_type = params->details.request_type == api_cp::PinRequestType::PIN_REQUEST_TYPE_NONE ? api_cp::PinRequestType::PIN_REQUEST_TYPE_PIN : params->details.request_type; - chromeos::RequestPinView::RequestPinErrorType error_type = - GetErrorTypeForView(params->details.error_type); + const PinErrorLabel error_label = + GetErrorLabelForDialog(params->details.error_type); - chromeos::RequestPinView::RequestPinCodeType code_type = + const PinCodeType code_type = (pin_request_type == api_cp::PinRequestType::PIN_REQUEST_TYPE_PIN) - ? chromeos::RequestPinView::RequestPinCodeType::PIN - : chromeos::RequestPinView::RequestPinCodeType::PUK; + ? PinCodeType::kPin + : PinCodeType::kPuk; chromeos::CertificateProviderService* const service = chromeos::CertificateProviderServiceFactory::GetForBrowserContext( @@ -303,7 +299,8 @@ ExtensionFunction::ResponseAction CertificateProviderRequestPinFunction::Run() { const chromeos::PinDialogManager::RequestPinResult result = service->pin_dialog_manager()->RequestPin( extension()->id(), extension()->name(), - params->details.sign_request_id, code_type, error_type, attempts_left, + params->details.sign_request_id, code_type, error_label, + attempts_left, base::BindOnce( &CertificateProviderRequestPinFunction::OnInputReceived, this)); switch (result) { diff --git a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h index 67b8ee0eabb..b61e947336d 100644 --- a/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h +++ b/chromium/chrome/browser/extensions/api/certificate_provider/certificate_provider_api.h @@ -28,9 +28,9 @@ struct CertificateInfo; } class CertificateProviderInternalReportCertificatesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderInternalReportCertificatesFunction() override; ResponseAction Run() override; @@ -43,9 +43,9 @@ class CertificateProviderInternalReportCertificatesFunction }; class CertificateProviderInternalReportSignatureFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderInternalReportSignatureFunction() override; ResponseAction Run() override; @@ -53,9 +53,9 @@ class CertificateProviderInternalReportSignatureFunction CERTIFICATEPROVIDERINTERNAL_REPORTSIGNATURE) }; -class CertificateProviderRequestPinFunction : public UIThreadExtensionFunction { +class CertificateProviderRequestPinFunction : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderRequestPinFunction() override; ResponseAction Run() override; bool ShouldSkipQuotaLimiting() const override; @@ -68,10 +68,9 @@ class CertificateProviderRequestPinFunction : public UIThreadExtensionFunction { CERTIFICATEPROVIDER_REQUESTPIN) }; -class CertificateProviderStopPinRequestFunction - : public UIThreadExtensionFunction { +class CertificateProviderStopPinRequestFunction : public ExtensionFunction { private: - // UIThreadExtensionFunction: + // ExtensionFunction: ~CertificateProviderStopPinRequestFunction() override; ResponseAction Run() override; 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 2a266152d46..1611eb4a730 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 @@ -173,7 +173,7 @@ class CertificateProviderRequestPinTest : public CertificateProviderApiTest { void AddFakeSignRequest() { cert_provider_service_->pin_dialog_manager()->AddSignRequestId( - extension_->id(), kFakeSignRequestId); + extension_->id(), kFakeSignRequestId, {}); } void NavigateTo(const std::string& test_page_file_name) { @@ -183,11 +183,13 @@ class CertificateProviderRequestPinTest : public CertificateProviderApiTest { chromeos::RequestPinView* GetActivePinDialogView() { return cert_provider_service_->pin_dialog_manager() + ->default_dialog_host_for_testing() ->active_view_for_testing(); } views::Widget* GetActivePinDialogWindow() { return cert_provider_service_->pin_dialog_manager() + ->default_dialog_host_for_testing() ->active_window_for_testing(); } 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 b8070abbf3d..4772d8e3c12 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.cc @@ -9,6 +9,7 @@ #include "base/bind.h" #include "base/files/file_path.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string_util.h" #include "base/task/post_task.h" #include "build/build_config.h" @@ -16,6 +17,7 @@ #include "chrome/browser/extensions/api/chrome_device_permissions_prompt.h" #include "chrome/browser/extensions/api/declarative_content/chrome_content_rules_registry.h" #include "chrome/browser/extensions/api/declarative_content/default_content_predicate_evaluators.h" +#include "chrome/browser/extensions/api/extension_action/extension_action_api.h" #include "chrome/browser/extensions/api/feedback_private/chrome_feedback_private_delegate.h" #include "chrome/browser/extensions/api/file_system/chrome_file_system_delegate.h" #include "chrome/browser/extensions/api/management/chrome_management_api_delegate.h" @@ -25,7 +27,10 @@ #include "chrome/browser/extensions/api/storage/managed_value_store_cache.h" #include "chrome/browser/extensions/api/storage/sync_value_store_cache.h" #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h" +#include "chrome/browser/extensions/extension_action.h" +#include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_action_runner.h" +#include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/system_display/display_info_provider.h" #include "chrome/browser/favicon/favicon_utils.h" #include "chrome/browser/guest_view/app_view/chrome_app_view_guest_delegate.h" @@ -103,7 +108,7 @@ void ChromeExtensionsAPIClient::AttachWebContentsHelpers( extensions::ChromeExtensionWebContentsObserver::CreateForWebContents( web_contents); - if (performance_manager::PerformanceManager::GetInstance()) { + if (performance_manager::PerformanceManager::IsAvailable()) { performance_manager::PerformanceManagerTabHelper::CreateForWebContents( web_contents); } @@ -213,6 +218,57 @@ void ChromeExtensionsAPIClient::NotifyWebRequestWithheld( runner->OnWebRequestBlocked(extension); } +void ChromeExtensionsAPIClient::UpdateActionCount( + content::BrowserContext* context, + const ExtensionId& extension_id, + int tab_id, + int action_count, + bool clear_badge_text) { + const Extension* extension = + ExtensionRegistry::Get(context)->enabled_extensions().GetByID( + extension_id); + DCHECK(extension); + + ExtensionAction* action = + ExtensionActionManager::Get(context)->GetExtensionAction(*extension); + DCHECK(action); + + action->SetDNRActionCount(tab_id, action_count); + + // The badge text should be cleared if |action| contains explicitly set badge + // text for the |tab_id| when the preference is then toggled on. In this case, + // the matched action count should take precedence over the badge text. + if (clear_badge_text) + action->ClearBadgeText(tab_id); + + content::WebContents* tab_contents = nullptr; + if (ExtensionTabUtil::GetTabById( + tab_id, context, true /* include_incognito */, &tab_contents) && + tab_contents) { + ExtensionActionAPI::Get(context)->NotifyChange(action, tab_contents, + context); + } +} + +void ChromeExtensionsAPIClient::ClearActionCount( + content::BrowserContext* context, + const Extension& extension) { + ExtensionAction* action = + ExtensionActionManager::Get(context)->GetExtensionAction(extension); + DCHECK(action); + + action->ClearDNRActionCountForAllTabs(); + + std::vector<content::WebContents*> contents_to_notify = + ExtensionTabUtil::GetAllActiveWebContentsForContext( + context, true /* include_incognito */); + + for (auto* active_contents : contents_to_notify) { + ExtensionActionAPI::Get(context)->NotifyChange(action, active_contents, + context); + } +} + AppViewGuestDelegate* ChromeExtensionsAPIClient::CreateAppViewGuestDelegate() const { return new ChromeAppViewGuestDelegate(); @@ -241,9 +297,9 @@ WebViewGuestDelegate* ChromeExtensionsAPIClient::CreateWebViewGuestDelegate( return new ChromeWebViewGuestDelegate(web_view_guest); } -WebViewPermissionHelperDelegate* ChromeExtensionsAPIClient:: - CreateWebViewPermissionHelperDelegate( - WebViewPermissionHelper* web_view_permission_helper) const { +WebViewPermissionHelperDelegate* +ChromeExtensionsAPIClient::CreateWebViewPermissionHelperDelegate( + WebViewPermissionHelper* web_view_permission_helper) const { return new ChromeWebViewPermissionHelperDelegate(web_view_permission_helper); } @@ -251,12 +307,10 @@ scoped_refptr<ContentRulesRegistry> ChromeExtensionsAPIClient::CreateContentRulesRegistry( content::BrowserContext* browser_context, RulesCacheDelegate* cache_delegate) const { - return scoped_refptr<ContentRulesRegistry>( - new ChromeContentRulesRegistry( - browser_context, - cache_delegate, - base::Bind(&CreateDefaultContentPredicateEvaluators, - base::Unretained(browser_context)))); + return base::MakeRefCounted<ChromeContentRulesRegistry>( + browser_context, cache_delegate, + base::Bind(&CreateDefaultContentPredicateEvaluators, + base::Unretained(browser_context))); } std::unique_ptr<DevicePermissionsPrompt> 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 a4837bf2e18..f5ff000a8c4 100644 --- a/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h +++ b/chromium/chrome/browser/extensions/api/chrome_extensions_api_client.h @@ -39,6 +39,13 @@ class ChromeExtensionsAPIClient : public ExtensionsAPIClient { void NotifyWebRequestWithheld(int render_process_id, int render_frame_id, const ExtensionId& extension_id) override; + void UpdateActionCount(content::BrowserContext* context, + const ExtensionId& extension_id, + int tab_id, + int action_count, + bool clear_badge_text) override; + void ClearActionCount(content::BrowserContext* context, + const Extension& extension) override; AppViewGuestDelegate* CreateAppViewGuestDelegate() const override; ExtensionOptionsGuestDelegate* CreateExtensionOptionsGuestDelegate( ExtensionOptionsGuest* guest) const override; 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 73d0c21d940..7948a83f6dc 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 @@ -6,7 +6,7 @@ #include "base/macros.h" #include "chrome/common/webui_url_constants.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/web_request/web_request_info.h" #include "google_apis/gaia/gaia_urls.h" #include "testing/gtest/include/gtest/gtest.h" @@ -19,7 +19,7 @@ class ChromeExtensionsAPIClientTest : public testing::Test { ChromeExtensionsAPIClientTest() = default; private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; DISALLOW_COPY_AND_ASSIGN(ChromeExtensionsAPIClientTest); }; diff --git a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h index eb7494ec660..35900ac4fd7 100644 --- a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h +++ b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.h @@ -48,8 +48,7 @@ class CloudPrintTestsDelegate { virtual std::vector<std::string> GetPrinters() = 0; }; -class CloudPrintPrivateSetupConnectorFunction - : public UIThreadExtensionFunction { +class CloudPrintPrivateSetupConnectorFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.setupConnector", CLOUDPRINTPRIVATE_SETUPCONNECTOR) @@ -63,7 +62,7 @@ class CloudPrintPrivateSetupConnectorFunction ResponseAction Run() override; }; -class CloudPrintPrivateGetHostNameFunction : public UIThreadExtensionFunction { +class CloudPrintPrivateGetHostNameFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.getHostName", CLOUDPRINTPRIVATE_GETHOSTNAME) @@ -77,7 +76,7 @@ class CloudPrintPrivateGetHostNameFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class CloudPrintPrivateGetPrintersFunction : public UIThreadExtensionFunction { +class CloudPrintPrivateGetPrintersFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.getPrinters", CLOUDPRINTPRIVATE_GETPRINTERS) @@ -94,7 +93,7 @@ class CloudPrintPrivateGetPrintersFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class CloudPrintPrivateGetClientIdFunction : public UIThreadExtensionFunction { +class CloudPrintPrivateGetClientIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cloudPrintPrivate.getClientId", CLOUDPRINTPRIVATE_GETCLIENTID) diff --git a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h index 4ab0dd1457e..56841a47bb3 100644 --- a/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h +++ b/chromium/chrome/browser/extensions/api/command_line_private/command_line_private_api.h @@ -9,7 +9,7 @@ namespace extensions { -class CommandLinePrivateHasSwitchFunction : public UIThreadExtensionFunction { +class CommandLinePrivateHasSwitchFunction : public ExtensionFunction { DECLARE_EXTENSION_FUNCTION("commandLinePrivate.hasSwitch", COMMANDLINEPRIVATE_HASSWITCH) protected: diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.cc b/chromium/chrome/browser/extensions/api/commands/command_service.cc index 8e055684c41..6f1e04fcaf5 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.cc +++ b/chromium/chrome/browser/extensions/api/commands/command_service.cc @@ -143,12 +143,12 @@ bool CommandService::RemovesBookmarkShortcut(const Extension* extension) { } // static -bool CommandService::RemovesBookmarkOpenPagesShortcut( +bool CommandService::RemovesBookmarkAllTabsShortcut( const Extension* extension) { - return UIOverrides::RemovesBookmarkOpenPagesShortcut(extension) && - (extension->permissions_data()->HasAPIPermission( - APIPermission::kBookmarkManagerPrivate) || - FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()); + return UIOverrides::RemovesBookmarkAllTabsShortcut(extension) && + (extension->permissions_data()->HasAPIPermission( + APIPermission::kBookmarkManagerPrivate) || + FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()); } bool CommandService::GetBrowserActionCommand(const std::string& extension_id, @@ -426,7 +426,7 @@ bool CommandService::RequestsBookmarkShortcutOverride( return RemovesBookmarkShortcut(extension) && GetSuggestedExtensionCommand( extension->id(), - chrome::GetPrimaryChromeAcceleratorForBookmarkPage(), nullptr); + chrome::GetPrimaryChromeAcceleratorForBookmarkTab(), nullptr); } void CommandService::AddObserver(Observer* observer) { @@ -579,7 +579,7 @@ bool CommandService::CanAutoAssign(const Command &command, // Not a global command, check if Chrome shortcut and whether // we can override it. if (command.accelerator() == - chrome::GetPrimaryChromeAcceleratorForBookmarkPage() && + chrome::GetPrimaryChromeAcceleratorForBookmarkTab() && CommandService::RemovesBookmarkShortcut(extension)) { // If this check fails it either means we have an API to override a // key that isn't a ChromeAccelerator (and the API can therefore be diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.h b/chromium/chrome/browser/extensions/api/commands/command_service.h index 22d82e817a1..6f3e1e89a9c 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.h +++ b/chromium/chrome/browser/extensions/api/commands/command_service.h @@ -99,8 +99,8 @@ class CommandService : public BrowserContextKeyedAPI, static bool RemovesBookmarkShortcut(const Extension* extension); // Returns true if |extension| is permitted to and does remove the bookmark - // open pages shortcut key. - static bool RemovesBookmarkOpenPagesShortcut(const Extension* extension); + // all tabs shortcut key. + static bool RemovesBookmarkAllTabsShortcut(const Extension* extension); // Gets the command (if any) for the browser action of an extension given // its |extension_id|. The function consults the master list to see if diff --git a/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc b/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc index c9ecdae11e3..a6a2e01b0ac 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/commands/command_service_browsertest.cc @@ -10,11 +10,11 @@ #include "build/build_config.h" #include "chrome/browser/extensions/api/commands/command_service.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/common/pref_names.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/test/browser_test.h" #include "content/public/test/test_utils.h" +#include "extensions/browser/extension_registry.h" #include "extensions/common/manifest_constants.h" namespace { @@ -64,15 +64,14 @@ IN_PROC_BROWSER_TEST_F(CommandServiceTest, RemoveShortcutSurvivesUpdate) { scoped_temp_dir.GetPath().AppendASCII("v2.crx"), pem_path, base::FilePath()); - ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> - extension_service(); + ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); CommandService* command_service = CommandService::Get(browser()->profile()); const char kId[] = "pgoakhfeplldmjheffidklpoklkppipp"; // Install v1 of the extension. ASSERT_TRUE(InstallExtension(path_v1, 1)); - EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL); + EXPECT_TRUE(registry->GetExtensionById(kId, ExtensionRegistry::ENABLED)); // Verify it has a command of Alt+Shift+F. ui::Accelerator accelerator = command_service->FindCommandByName( @@ -93,7 +92,7 @@ IN_PROC_BROWSER_TEST_F(CommandServiceTest, RemoveShortcutSurvivesUpdate) { // Update to version 2. EXPECT_TRUE(UpdateExtension(kId, path_v2, 0)); - EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL); + EXPECT_TRUE(registry->GetExtensionById(kId, ExtensionRegistry::ENABLED)); // Verify it is still set to nothing. accelerator = command_service->FindCommandByName( diff --git a/chromium/chrome/browser/extensions/api/commands/commands.h b/chromium/chrome/browser/extensions/api/commands/commands.h index 16b940fb965..433bdd19756 100644 --- a/chromium/chrome/browser/extensions/api/commands/commands.h +++ b/chromium/chrome/browser/extensions/api/commands/commands.h @@ -7,7 +7,7 @@ #include "extensions/browser/extension_function.h" -class GetAllCommandsFunction : public UIThreadExtensionFunction { +class GetAllCommandsFunction : public ExtensionFunction { ~GetAllCommandsFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("commands.getAll", COMMANDS_GETALL) 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 f2458751626..0f87e20fe15 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 @@ -347,7 +347,7 @@ void ContentSettingsContentSettingGetResourceIdentifiersFunction::OnGotPlugins( list->Append(std::move(dict)); } SetResult(std::move(list)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &ContentSettingsContentSettingGetResourceIdentifiersFunction:: diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h index fa0fb0c3e11..be5d3208e9c 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_api.h @@ -14,8 +14,7 @@ struct WebPluginInfo; namespace extensions { -class ContentSettingsContentSettingClearFunction - : public UIThreadExtensionFunction { +class ContentSettingsContentSettingClearFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.clear", CONTENTSETTINGS_CLEAR) @@ -26,8 +25,7 @@ class ContentSettingsContentSettingClearFunction ResponseAction Run() override; }; -class ContentSettingsContentSettingGetFunction - : public UIThreadExtensionFunction { +class ContentSettingsContentSettingGetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.get", CONTENTSETTINGS_GET) @@ -38,8 +36,7 @@ class ContentSettingsContentSettingGetFunction ResponseAction Run() override; }; -class ContentSettingsContentSettingSetFunction - : public UIThreadExtensionFunction { +class ContentSettingsContentSettingSetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contentSettings.set", CONTENTSETTINGS_SET) diff --git a/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc b/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc index 66c59d56e6e..47757999355 100644 --- a/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc +++ b/chromium/chrome/browser/extensions/api/content_settings/content_settings_service.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/content_settings/content_settings_service.h" #include "base/lazy_instance.h" +#include "base/memory/scoped_refptr.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_prefs_scope.h" #include "extensions/browser/pref_names.h" @@ -12,7 +13,7 @@ namespace extensions { ContentSettingsService::ContentSettingsService(content::BrowserContext* context) - : content_settings_store_(new ContentSettingsStore()), + : content_settings_store_(base::MakeRefCounted<ContentSettingsStore>()), scoped_observer_(this) {} ContentSettingsService::~ContentSettingsService() {} diff --git a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h index 78e00b7415c..4dc9f20151a 100644 --- a/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h +++ b/chromium/chrome/browser/extensions/api/context_menus/context_menus_api.h @@ -9,7 +9,7 @@ namespace extensions { -class ContextMenusCreateFunction : public UIThreadExtensionFunction { +class ContextMenusCreateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.create", CONTEXTMENUS_CREATE) @@ -20,7 +20,7 @@ class ContextMenusCreateFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ContextMenusUpdateFunction : public UIThreadExtensionFunction { +class ContextMenusUpdateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.update", CONTEXTMENUS_UPDATE) @@ -31,7 +31,7 @@ class ContextMenusUpdateFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ContextMenusRemoveFunction : public UIThreadExtensionFunction { +class ContextMenusRemoveFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.remove", CONTEXTMENUS_REMOVE) @@ -42,7 +42,7 @@ class ContextMenusRemoveFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ContextMenusRemoveAllFunction : public UIThreadExtensionFunction { +class ContextMenusRemoveAllFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("contextMenus.removeAll", CONTEXTMENUS_REMOVEALL) diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc index 9a1e1967385..aca854a958e 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc @@ -182,14 +182,14 @@ void CookiesEventRouter::MaybeStartListening() { ? original_profile->GetOffTheRecordProfile() : nullptr; - if (!binding_) - BindToCookieManager(&binding_, original_profile); - if (!otr_binding_.is_bound() && otr_profile) - BindToCookieManager(&otr_binding_, otr_profile); + if (!receiver_.is_bound()) + BindToCookieManager(&receiver_, original_profile); + if (!otr_receiver_.is_bound() && otr_profile) + BindToCookieManager(&otr_receiver_, otr_profile); } void CookiesEventRouter::BindToCookieManager( - mojo::Binding<network::mojom::CookieChangeListener>* binding, + mojo::Receiver<network::mojom::CookieChangeListener>* receiver, Profile* profile) { network::mojom::CookieManager* cookie_manager = content::BrowserContext::GetDefaultStoragePartition(profile) @@ -197,19 +197,17 @@ void CookiesEventRouter::BindToCookieManager( if (!cookie_manager) return; - network::mojom::CookieChangeListenerPtr listener_ptr; - binding->Bind(mojo::MakeRequest(&listener_ptr)); - binding->set_connection_error_handler(base::BindOnce( - &CookiesEventRouter::OnConnectionError, base::Unretained(this), binding)); - - cookie_manager->AddGlobalChangeListener(std::move(listener_ptr)); + cookie_manager->AddGlobalChangeListener(receiver->BindNewPipeAndPassRemote()); + receiver->set_disconnect_handler( + base::BindOnce(&CookiesEventRouter::OnConnectionError, + base::Unretained(this), receiver)); } void CookiesEventRouter::OnConnectionError( - mojo::Binding<network::mojom::CookieChangeListener>* binding) { + mojo::Receiver<network::mojom::CookieChangeListener>* receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - binding->Close(); + receiver->reset(); MaybeStartListening(); } @@ -251,25 +249,26 @@ ExtensionFunction::ResponseAction CookiesGetFunction::Run() { if (!parsed_args_->details.store_id.get()) parsed_args_->details.store_id.reset(new std::string(store_id)); + DCHECK(!url_.is_empty() && url_.is_valid()); cookies_helpers::GetCookieListFromManager( cookie_manager, url_, - base::BindOnce(&CookiesGetFunction::GetCookieCallback, this)); + base::BindOnce(&CookiesGetFunction::GetCookieListCallback, this)); // Will finish asynchronously. return RespondLater(); } -void CookiesGetFunction::GetCookieCallback( - const net::CookieList& cookie_list, +void CookiesGetFunction::GetCookieListCallback( + const net::CookieStatusList& cookie_status_list, const net::CookieStatusList& excluded_cookies) { DCHECK_CURRENTLY_ON(BrowserThread::UI); - for (const net::CanonicalCookie& cookie : cookie_list) { + for (const net::CookieWithStatus& cookie_with_status : cookie_status_list) { // Return the first matching cookie. Relies on the fact that the // CookieManager interface returns them in canonical order (longest path, // then earliest creation time). - if (cookie.Name() == parsed_args_->details.name) { + if (cookie_with_status.cookie.Name() == parsed_args_->details.name) { api::cookies::Cookie api_cookie = cookies_helpers::CreateCookie( - cookie, *parsed_args_->details.store_id); + cookie_with_status.cookie, *parsed_args_->details.store_id); Respond(ArgumentList(api::cookies::Get::Results::Create(api_cookie))); return; } @@ -308,22 +307,46 @@ ExtensionFunction::ResponseAction CookiesGetAllFunction::Run() { parsed_args_->details.store_id.reset(new std::string(store_id)); DCHECK(url_.is_empty() || url_.is_valid()); - cookies_helpers::GetCookieListFromManager( - cookie_manager, url_, - base::BindOnce(&CookiesGetAllFunction::GetAllCookiesCallback, this)); + if (url_.is_empty()) { + cookies_helpers::GetAllCookiesFromManager( + cookie_manager, + base::BindOnce(&CookiesGetAllFunction::GetAllCookiesCallback, this)); + } else { + cookies_helpers::GetCookieListFromManager( + cookie_manager, url_, + base::BindOnce(&CookiesGetAllFunction::GetCookieListCallback, this)); + } return RespondLater(); } void CookiesGetAllFunction::GetAllCookiesCallback( - const net::CookieList& cookie_list, + const net::CookieList& cookie_list) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + ResponseValue response; + if (extension()) { + std::vector<api::cookies::Cookie> match_vector; + cookies_helpers::AppendMatchingCookiesFromCookieListToVector( + cookie_list, &parsed_args_->details, extension(), &match_vector); + + response = + ArgumentList(api::cookies::GetAll::Results::Create(match_vector)); + } else { + // TODO(devlin): When can |extension()| be null for this function? + response = NoArguments(); + } + Respond(std::move(response)); +} + +void CookiesGetAllFunction::GetCookieListCallback( + const net::CookieStatusList& cookie_status_list, const net::CookieStatusList& excluded_cookies) { DCHECK_CURRENTLY_ON(BrowserThread::UI); ResponseValue response; if (extension()) { std::vector<api::cookies::Cookie> match_vector; - cookies_helpers::AppendMatchingCookiesToVector( - cookie_list, url_, &parsed_args_->details, extension(), &match_vector); + cookies_helpers::AppendMatchingCookiesFromCookieStatusListToVector( + cookie_status_list, &parsed_args_->details, extension(), &match_vector); response = ArgumentList(api::cookies::GetAll::Results::Create(match_vector)); @@ -417,7 +440,7 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() { // is generated. success_ = false; state_ = SET_COMPLETED; - GetCookieListCallback(net::CookieList(), net::CookieStatusList()); + GetCookieListCallback(net::CookieStatusList(), net::CookieStatusList()); return AlreadyResponded(); } @@ -428,6 +451,7 @@ ExtensionFunction::ResponseAction CookiesSetFunction::Run() { options.set_include_httponly(); options.set_same_site_cookie_context( net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); + DCHECK(!url_.is_empty() && url_.is_valid()); cookie_manager->SetCanonicalCookie( *cc, url_.scheme(), options, base::BindOnce(&CookiesSetFunction::SetCanonicalCookieCallback, this)); @@ -444,12 +468,11 @@ void CookiesSetFunction::SetCanonicalCookieCallback( DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(NO_RESPONSE, state_); state_ = SET_COMPLETED; - success_ = (set_cookie_result == - net::CanonicalCookie::CookieInclusionStatus::INCLUDE); + success_ = set_cookie_result.IsInclude(); } void CookiesSetFunction::GetCookieListCallback( - const net::CookieList& cookie_list, + const net::CookieStatusList& cookie_list, const net::CookieStatusList& excluded_cookies) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK_EQ(SET_COMPLETED, state_); @@ -465,16 +488,16 @@ void CookiesSetFunction::GetCookieListCallback( } ResponseValue value; - for (const net::CanonicalCookie& cookie : cookie_list) { + for (const net::CookieWithStatus& cookie_with_status : cookie_list) { // 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(); - if (cookie.Name() == name) { + if (cookie_with_status.cookie.Name() == name) { api::cookies::Cookie api_cookie = cookies_helpers::CreateCookie( - cookie, *parsed_args_->details.store_id); + cookie_with_status.cookie, *parsed_args_->details.store_id); value = ArgumentList(api::cookies::Set::Results::Create(api_cookie)); break; } diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h index fbd37d66f00..ac95fc35736 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h @@ -19,7 +19,8 @@ #include "chrome/common/extensions/api/cookies.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" -#include "mojo/public/cpp/bindings/binding.h" +#include "mojo/public/cpp/bindings/receiver.h" +#include "mojo/public/cpp/bindings/remote.h" #include "net/cookies/canonical_cookie.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "url/gurl.h" @@ -60,10 +61,10 @@ class CookiesEventRouter : public BrowserListObserver { void MaybeStartListening(); void BindToCookieManager( - mojo::Binding<network::mojom::CookieChangeListener>* binding, + mojo::Receiver<network::mojom::CookieChangeListener>* receiver, Profile* profile); void OnConnectionError( - mojo::Binding<network::mojom::CookieChangeListener>* binding); + mojo::Receiver<network::mojom::CookieChangeListener>* receiver); void OnCookieChange(bool otr, const net::CanonicalCookie& canonical_cookie, network::mojom::CookieChangeCause cause); @@ -81,17 +82,17 @@ class CookiesEventRouter : public BrowserListObserver { // profiles, we need a pair of bindings, as well as a pair of // CookieChangeListener instances. CookieChangeListener listener_{this, false}; - mojo::Binding<network::mojom::CookieChangeListener> binding_{&listener_}; + mojo::Receiver<network::mojom::CookieChangeListener> receiver_{&listener_}; CookieChangeListener otr_listener_{this, true}; - mojo::Binding<network::mojom::CookieChangeListener> otr_binding_{ + mojo::Receiver<network::mojom::CookieChangeListener> otr_receiver_{ &otr_listener_}; DISALLOW_COPY_AND_ASSIGN(CookiesEventRouter); }; // Implements the cookies.get() extension function. -class CookiesGetFunction : public UIThreadExtensionFunction { +class CookiesGetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.get", COOKIES_GET) @@ -104,16 +105,16 @@ class CookiesGetFunction : public UIThreadExtensionFunction { ResponseAction Run() override; private: - void GetCookieCallback(const net::CookieList& cookie_list, - const net::CookieStatusList& excluded_cookies); + void GetCookieListCallback(const net::CookieStatusList& cookie_status_list, + const net::CookieStatusList& excluded_cookies); GURL url_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::Get::Params> parsed_args_; }; // Implements the cookies.getAll() extension function. -class CookiesGetAllFunction : public UIThreadExtensionFunction { +class CookiesGetAllFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.getAll", COOKIES_GETALL) @@ -126,16 +127,19 @@ class CookiesGetAllFunction : public UIThreadExtensionFunction { ResponseAction Run() override; private: - void GetAllCookiesCallback(const net::CookieList& cookie_list, + // For the two different callback signatures for getting cookies for a URL vs + // getting all cookies. They do the same thing. + void GetAllCookiesCallback(const net::CookieList& cookie_list); + void GetCookieListCallback(const net::CookieStatusList& cookie_status_list, const net::CookieStatusList& excluded_cookies); GURL url_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::GetAll::Params> parsed_args_; }; // Implements the cookies.set() extension function. -class CookiesSetFunction : public UIThreadExtensionFunction { +class CookiesSetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.set", COOKIES_SET) @@ -148,18 +152,18 @@ class CookiesSetFunction : public UIThreadExtensionFunction { private: void SetCanonicalCookieCallback( net::CanonicalCookie::CookieInclusionStatus set_cookie_result); - void GetCookieListCallback(const net::CookieList& cookie_list, + void GetCookieListCallback(const net::CookieStatusList& cookie_list, const net::CookieStatusList& excluded_cookies); enum { NO_RESPONSE, SET_COMPLETED, GET_COMPLETED } state_; GURL url_; bool success_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::Set::Params> parsed_args_; }; // Implements the cookies.remove() extension function. -class CookiesRemoveFunction : public UIThreadExtensionFunction { +class CookiesRemoveFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.remove", COOKIES_REMOVE) @@ -175,12 +179,12 @@ class CookiesRemoveFunction : public UIThreadExtensionFunction { void RemoveCookieCallback(uint32_t /* num_deleted */); GURL url_; - network::mojom::CookieManagerPtr store_browser_cookie_manager_; + mojo::Remote<network::mojom::CookieManager> store_browser_cookie_manager_; std::unique_ptr<api::cookies::Remove::Params> parsed_args_; }; // Implements the cookies.getAllCookieStores() extension function. -class CookiesGetAllCookieStoresFunction : public UIThreadExtensionFunction { +class CookiesGetAllCookieStoresFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("cookies.getAllCookieStores", COOKIES_GETALLCOOKIESTORES) diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc index 2c663be2948..f4dfc24b93c 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.cc @@ -38,6 +38,28 @@ namespace GetAll = extensions::api::cookies::GetAll; namespace extensions { +namespace { + +void AppendCookieToVectorIfMatchAndHasHostPermission( + const net::CanonicalCookie cookie, + const GetAll::Params::Details* details, + const Extension* extension, + std::vector<Cookie>* match_vector) { + // Ignore any cookie whose domain doesn't match the extension's + // host permissions. + GURL cookie_domain_url = cookies_helpers::GetURLFromCanonicalCookie(cookie); + if (!extension->permissions_data()->HasHostPermission(cookie_domain_url)) + return; + // Filter the cookie using the match filter. + cookies_helpers::MatchFilter filter(details); + if (filter.MatchesCookie(cookie)) { + match_vector->push_back( + cookies_helpers::CreateCookie(cookie, *details->store_id)); + } +} + +} // namespace + namespace cookies_helpers { static const char kOriginalProfileStoreId[] = "0"; @@ -81,6 +103,7 @@ Cookie CreateCookie(const net::CanonicalCookie& canonical_cookie, cookie.secure = canonical_cookie.IsSecure(); cookie.http_only = canonical_cookie.IsHttpOnly(); + DCHECK(net::IsValidSameSiteValue(canonical_cookie.SameSite())); switch (canonical_cookie.SameSite()) { case net::CookieSameSite::NO_RESTRICTION: cookie.same_site = api::cookies::SAME_SITE_STATUS_NO_RESTRICTION; @@ -95,6 +118,8 @@ Cookie CreateCookie(const net::CanonicalCookie& canonical_cookie, case net::CookieSameSite::UNSPECIFIED: cookie.same_site = api::cookies::SAME_SITE_STATUS_UNSPECIFIED; break; + default: + NOTREACHED(); } cookie.session = !canonical_cookie.IsPersistent(); @@ -129,22 +154,14 @@ void GetCookieListFromManager( network::mojom::CookieManager* manager, const GURL& url, network::mojom::CookieManager::GetCookieListCallback callback) { - if (url.is_empty()) { - // GetAllCookies has a different callback signature than GetCookieList, but - // can be treated as the same, just returning no excluded cookies. - // |AddCookieStatusList| takes a |GetCookieListCallback| and returns a - // callback that calls the input callback with an empty excluded list. - manager->GetAllCookies( - net::cookie_util::AddCookieStatusList(std::move(callback))); - } else { - net::CookieOptions options; - options.set_include_httponly(); - options.set_same_site_cookie_context( - net::CookieOptions::SameSiteCookieContext::SAME_SITE_STRICT); - options.set_do_not_update_access_time(); - - manager->GetCookieList(url, options, std::move(callback)); - } + manager->GetCookieList(url, net::CookieOptions::MakeAllInclusive(), + std::move(callback)); +} + +void GetAllCookiesFromManager( + network::mojom::CookieManager* manager, + network::mojom::CookieManager::GetAllCookiesCallback callback) { + manager->GetAllCookies(std::move(callback)); } GURL GetURLFromCanonicalCookie(const net::CanonicalCookie& cookie) { @@ -158,21 +175,27 @@ GURL GetURLFromCanonicalCookie(const net::CanonicalCookie& cookie) { return GURL(scheme + url::kStandardSchemeSeparator + host + "/"); } -void AppendMatchingCookiesToVector(const net::CookieList& all_cookies, - const GURL& url, - const GetAll::Params::Details* details, - const Extension* extension, - std::vector<Cookie>* match_vector) { +void AppendMatchingCookiesFromCookieListToVector( + const net::CookieList& all_cookies, + const GetAll::Params::Details* details, + const Extension* extension, + std::vector<Cookie>* match_vector) { for (const net::CanonicalCookie& cookie : all_cookies) { - // Ignore any cookie whose domain doesn't match the extension's - // host permissions. - GURL cookie_domain_url = GetURLFromCanonicalCookie(cookie); - if (!extension->permissions_data()->HasHostPermission(cookie_domain_url)) - continue; - // Filter the cookie using the match filter. - cookies_helpers::MatchFilter filter(details); - if (filter.MatchesCookie(cookie)) - match_vector->push_back(CreateCookie(cookie, *details->store_id)); + AppendCookieToVectorIfMatchAndHasHostPermission(cookie, details, extension, + match_vector); + } +} + +void AppendMatchingCookiesFromCookieStatusListToVector( + const net::CookieStatusList& all_cookies_with_statuses, + const GetAll::Params::Details* details, + const Extension* extension, + std::vector<Cookie>* match_vector) { + for (const net::CookieWithStatus& cookie_with_status : + all_cookies_with_statuses) { + const net::CanonicalCookie& cookie = cookie_with_status.cookie; + AppendCookieToVectorIfMatchAndHasHostPermission(cookie, details, extension, + match_vector); } } diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h index 0b21eb056db..298b16e49a7 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h @@ -58,12 +58,17 @@ api::cookies::CookieStore CreateCookieStore( std::unique_ptr<base::ListValue> tab_ids); // Dispatch a request to the CookieManager for cookies associated with -// |url|, or all cookies if |url.is_empty()|. +// |url|. void GetCookieListFromManager( network::mojom::CookieManager* manager, const GURL& url, network::mojom::CookieManager::GetCookieListCallback callback); +// Dispatch a request to the CookieManager for all cookies. +void GetAllCookiesFromManager( + network::mojom::CookieManager* manager, + network::mojom::CookieManager::GetAllCookiesCallback callback); + // Constructs a URL from a cookie's information for use in checking // a cookie against the extension's host permissions. The Secure // property of the cookie defines the URL scheme, and the cookie's @@ -74,9 +79,15 @@ GURL GetURLFromCanonicalCookie( // Looks through all cookies in the given cookie store, and appends to the // match vector all the cookies that both match the given URL and cookie details // and are allowed by extension host permissions. -void AppendMatchingCookiesToVector( +void AppendMatchingCookiesFromCookieListToVector( const net::CookieList& all_cookies, - const GURL& url, + const api::cookies::GetAll::Params::Details* details, + const Extension* extension, + std::vector<api::cookies::Cookie>* match_vector); + +// Same as above except takes a CookieStatusList (and ignores the statuses). +void AppendMatchingCookiesFromCookieStatusListToVector( + const net::CookieStatusList& all_cookies_with_statuses, const api::cookies::GetAll::Params::Details* details, const Extension* extension, std::vector<api::cookies::Cookie>* match_vector); diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc index fbfc9935aa7..56e587afe38 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_unittest.cc @@ -10,13 +10,14 @@ #include <memory> #include <utility> +#include "base/optional.h" #include "base/stl_util.h" #include "base/values.h" #include "chrome/browser/extensions/api/cookies/cookies_api_constants.h" #include "chrome/browser/extensions/api/cookies/cookies_helpers.h" #include "chrome/common/extensions/api/cookies.h" #include "chrome/test/base/testing_profile.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_constants.h" #include "testing/gtest/include/gtest/gtest.h" @@ -43,7 +44,7 @@ struct DomainMatchCase { class ExtensionCookiesTest : public testing::Test { private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(ExtensionCookiesTest, StoreIdProfileConversion) { @@ -186,9 +187,9 @@ TEST_F(ExtensionCookiesTest, DomainMatching) { TEST_F(ExtensionCookiesTest, DecodeUTF8WithErrorHandling) { std::unique_ptr<net::CanonicalCookie> canonical_cookie( - net::CanonicalCookie::Create(GURL("http://test.com"), - "=011Q255bNX_1!yd\203e+;path=/path\203", - base::Time::Now(), net::CookieOptions())); + net::CanonicalCookie::Create( + GURL("http://test.com"), "=011Q255bNX_1!yd\203e+;path=/path\203", + base::Time::Now(), base::nullopt /* server_time */)); ASSERT_NE(nullptr, canonical_cookie.get()); Cookie cookie = cookies_helpers::CreateCookie(*canonical_cookie, "some cookie store"); 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 40acfb6057a..da020fe3416 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 @@ -216,9 +216,7 @@ CryptotokenPrivateCanAppIdGetAttestationFunction::Run() { content::WebContents* web_contents = nullptr; if (!ExtensionTabUtil::GetTabById(params->options.tab_id, browser_context(), true /* include incognito windows */, - nullptr /* out_browser */, - nullptr /* out_tab_strip */, &web_contents, - nullptr /* out_tab_index */)) { + &web_contents)) { return RespondNow(Error("cannot find specified tab")); } 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 7c92493260b..9ac938c8b12 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 @@ -27,18 +27,18 @@ void CryptotokenRegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry); class CryptotokenPrivateCanOriginAssertAppIdFunction - : public UIThreadExtensionFunction { - public: - CryptotokenPrivateCanOriginAssertAppIdFunction(); - DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canOriginAssertAppId", - CRYPTOTOKENPRIVATE_CANORIGINASSERTAPPID) - protected: - ~CryptotokenPrivateCanOriginAssertAppIdFunction() override {} - ResponseAction Run() override; + : public ExtensionFunction { + public: + CryptotokenPrivateCanOriginAssertAppIdFunction(); + DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canOriginAssertAppId", + CRYPTOTOKENPRIVATE_CANORIGINASSERTAPPID) + protected: + ~CryptotokenPrivateCanOriginAssertAppIdFunction() override {} + ResponseAction Run() override; }; class CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction(); DECLARE_EXTENSION_FUNCTION( @@ -51,7 +51,7 @@ class CryptotokenPrivateIsAppIdHashInEnterpriseContextFunction }; class CryptotokenPrivateCanAppIdGetAttestationFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: CryptotokenPrivateCanAppIdGetAttestationFunction(); DECLARE_EXTENSION_FUNCTION("cryptotokenPrivate.canAppIdGetAttestation", 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 0500f7e9888..4ed224a3259 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 @@ -31,7 +31,7 @@ namespace { using namespace api::cryptotoken_private; -bool GetSingleBooleanResult(UIThreadExtensionFunction* function, bool* result) { +bool GetSingleBooleanResult(ExtensionFunction* function, bool* result) { const base::ListValue* result_list = function->GetResultList(); if (!result_list) { ADD_FAILURE() << "Function has no result list."; 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 b7903610641..b8d2c3b4444 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 @@ -7,6 +7,7 @@ #include <utility> #include "base/bind.h" +#include "base/memory/scoped_refptr.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/bitmap_fetcher/bitmap_fetcher.h" #include "chrome/browser/profiles/profile.h" @@ -82,7 +83,7 @@ DashboardPrivateShowPermissionPromptForDelegatedInstallFunction::Run() { .get(); } - scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper( + auto helper = base::MakeRefCounted<WebstoreInstallHelper>( this, params_->details.id, params_->details.manifest, icon_url); // The helper will call us back via OnWebstoreParseSuccess or 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 66697ef6964..93a75ad77b5 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 @@ -23,7 +23,7 @@ namespace extensions { class Extension; class DashboardPrivateShowPermissionPromptForDelegatedInstallFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public WebstoreInstallHelper::Delegate { public: DECLARE_EXTENSION_FUNCTION( diff --git a/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h b/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h index 8af53d7e2bd..07306919e59 100644 --- a/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h +++ b/chromium/chrome/browser/extensions/api/data_reduction_proxy/data_reduction_proxy_api.h @@ -15,8 +15,7 @@ class DataUsageBucket; namespace extensions { -class DataReductionProxyClearDataSavingsFunction - : public UIThreadExtensionFunction { +class DataReductionProxyClearDataSavingsFunction : public ExtensionFunction { private: ~DataReductionProxyClearDataSavingsFunction() override {} @@ -26,8 +25,7 @@ class DataReductionProxyClearDataSavingsFunction ResponseAction Run() override; }; -class DataReductionProxyGetDataUsageFunction - : public UIThreadExtensionFunction { +class DataReductionProxyGetDataUsageFunction : public ExtensionFunction { private: ~DataReductionProxyGetDataUsageFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc index e5cd5ab180e..6c79f07702a 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_api.cc @@ -421,10 +421,10 @@ void DebuggerFunction::FormatErrorMessage(const std::string& format) { bool DebuggerFunction::InitAgentHost() { if (debuggee_.tab_id) { - WebContents* web_contents = NULL; + WebContents* web_contents = nullptr; bool result = ExtensionTabUtil::GetTabById(*debuggee_.tab_id, GetProfile(), include_incognito_information(), - NULL, NULL, &web_contents, NULL); + &web_contents); if (result && web_contents) { // TODO(rdevlin.cronin) This should definitely be GetLastCommittedURL(). GURL url = web_contents->GetVisibleURL(); @@ -668,7 +668,7 @@ DebuggerGetTargetsFunction::~DebuggerGetTargetsFunction() { bool DebuggerGetTargetsFunction::RunAsync() { content::DevToolsAgentHost::List list = DevToolsAgentHost::GetOrCreateAll(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DebuggerGetTargetsFunction::SendTargetList, this, list)); return true; diff --git a/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc b/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc index 29f627d834f..ae31311197c 100644 --- a/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative/rules_registry_service_unittest.cc @@ -15,8 +15,8 @@ #include "components/version_info/channel.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_task_traits.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "extensions/browser/api/declarative/test_rules_registry.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" #include "extensions/common/api/declarative/declarative_constants.h" @@ -63,7 +63,7 @@ class RulesRegistryServiceTest : public testing::Test { } protected: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) { @@ -85,22 +85,22 @@ TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) { EXPECT_TRUE(registry_service.GetRulesRegistry(key, "io").get()); EXPECT_FALSE(registry_service.GetRulesRegistry(key, "foo").get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "ui"), "ui_task")); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&InsertRule, registry_service.GetRulesRegistry(key, "io"), "io_task")); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "ui"), 1)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "io"), 1)); @@ -121,12 +121,12 @@ TEST_F(RulesRegistryServiceTest, TestConstructionAndMultiThreading) { .Build(); registry_service.SimulateExtensionUninstalled(extension.get()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "ui"), 0)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&VerifyNumberOfRules, registry_service.GetRulesRegistry(key, "io"), 0)); 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 fd55b3da387..6d91223e12d 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 @@ -17,7 +17,7 @@ #include "chrome/common/extensions/extension_test_util.h" #include "chrome/test/base/testing_profile.h" #include "components/version_info/version_info.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "extensions/browser/api/declarative/rules_cache_delegate.h" #include "extensions/browser/api/declarative/rules_registry_service.h" 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 3cad3939ab9..058b888d5a0 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 @@ -11,8 +11,8 @@ #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/render_view_host.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/browser_test_utils.h" -#include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_renderer_host.h" #include "testing/gtest/include/gtest/gtest.h" @@ -45,7 +45,7 @@ class DeclarativeContentConditionTrackerTest : public testing::Test { const void* GeneratePredicateGroupID(); private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; // Enables MockRenderProcessHosts. content::RenderViewHostTestEnabler render_view_host_test_enabler_; 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 d9b1b058ecd..e704227958c 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 @@ -29,17 +29,22 @@ #include "base/threading/thread_restrictions.h" #include "base/values.h" #include "build/build_config.h" +#include "chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.h" +#include "chrome/browser/extensions/extension_action.h" +#include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_action_runner.h" #include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/load_error_reporter.h" #include "chrome/browser/extensions/scripting_permissions_modifier.h" #include "chrome/browser/net/profile_network_context_service.h" #include "chrome/browser/net/profile_network_context_service_factory.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_paths.h" +#include "chrome/common/extensions/api/extension_action/action_info.h" #include "chrome/common/webui_url_constants.h" #include "chrome/test/base/ui_test_utils.h" #include "components/prefs/pref_service.h" @@ -490,6 +495,18 @@ class DeclarativeNetRequestBrowserTest ASSERT_EQ("success", ExecuteScriptInBackgroundPage(extension_id, script)); } + void SetActionsAsBadgeText(const ExtensionId& extension_id, bool pref) { + const char* pref_string = pref ? "true" : "false"; + static constexpr char kSetActionCountAsBadgeTextScript[] = R"( + chrome.declarativeNetRequest.setActionCountAsBadgeText(%s); + window.domAutomationController.send("done"); + )"; + + ExecuteScriptInBackgroundPage( + extension_id, + base::StringPrintf(kSetActionCountAsBadgeTextScript, pref_string)); + } + std::set<GURL> GetAndResetRequestsToServer() { base::AutoLock lock(requests_to_server_lock_); std::set<GURL> results = requests_to_server_; @@ -942,7 +959,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, AllowRedirect) { rule.condition->url_filter = rule_data.url_filter; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rule.action->type = rule_data.action_type; - rule.action->redirect_url = rule_data.redirect_url; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; rules.push_back(rule); } @@ -1155,7 +1173,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // Add |kNumExtensions| each redirecting example.com to a different redirect // url. for (size_t i = 1; i <= kNumExtensions; ++i) { - rule.action->redirect_url = redirect_url_for_extension_number(i); + rule.action->redirect.emplace(); + rule.action->redirect->url = redirect_url_for_extension_number(i); ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( {rule}, std::to_string(i), {URLPattern::kAllUrlsPattern})); @@ -1198,7 +1217,6 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) { {"def.com", 4, "block", base::nullopt}, {"def.com", 5, "redirect", get_url_for_host("xyz.com")}, {"ghi*", 6, "redirect", get_url_for_host("ghijk.com")}, - {"ijk*", 7, "redirect", "/manifest.json"}, }; // Load the extension. @@ -1210,7 +1228,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) { rule.priority = kMinValidPriority; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rule.action->type = rule_data.action_type; - rule.action->redirect_url = rule_data.redirect_url; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; rules.push_back(rule); } ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( @@ -1236,13 +1255,7 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, BlockAndRedirect) { // Though ghijk.com still matches the redirect rule for |ghi*|, it will // not redirect to itself. {"ghi.com", true, GURL(get_url_for_host("ghijk.com")), 2}, - // ijklm.com -> chrome-extension://<extension_id>/manifest.json. - // Since this redirects to a manifest.json, don't expect the frame with - // script to load. - {"ijklm.com", false, - GURL("chrome-extension://" + last_loaded_extension_id() + - "/manifest.json"), - 2}}; + }; for (const auto& test_case : test_cases) { std::string url = get_url_for_host(test_case.hostname); @@ -1299,7 +1312,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RedirectPriority) { rule.id = id++; rule.priority = j; rule.action->type = std::string("redirect"); - rule.action->redirect_url = redirect_url_for_priority(j); + rule.action->redirect.emplace(); + rule.action->redirect->url = redirect_url_for_priority(j); rule.condition->url_filter = pattern; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rules.push_back(rule); @@ -1372,7 +1386,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, UpgradeRules) { rule.priority = rule_data.priority; rule.condition->resource_types = std::vector<std::string>({"main_frame"}); rule.action->type = rule_data.action_type; - rule.action->redirect_url = rule_data.redirect_url; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; rules.push_back(rule); } @@ -1688,8 +1703,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, set_has_background_script(true); LoadExtensionWithRules({}); - const Extension* dnr_extension = extension_service()->GetExtensionById( - last_loaded_extension_id(), false /*include_disabled*/); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED); ASSERT_TRUE(dnr_extension); EXPECT_EQ("Test extension", dnr_extension->name()); @@ -2046,8 +2061,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest_Packed, const GURL unblocked_url = embedded_test_server()->GetURL( "yahoo.com", "/pages_with_script/index.html"); - const Extension* extension = extension_service()->GetExtensionById( - extension_id, false /*include_disabled*/); + const Extension* extension = extension_registry()->GetExtensionById( + extension_id, ExtensionRegistry::ENABLED); RulesetSource static_source = RulesetSource::CreateStatic(*extension); RulesetSource dynamic_source = RulesetSource::CreateDynamic(profile(), *extension); @@ -2281,15 +2296,16 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, rule.condition->resource_types = std::vector<std::string>({"script"}); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = + rule.action->redirect.emplace(); + rule.action->redirect->url = embedded_test_server()->GetURL("b.com", "/subresources/script.js").spec(); std::vector<std::string> host_permissions = {"*://a.com/", "*://b.com/*"}; ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( {rule}, "extension" /* directory */, host_permissions)); - const Extension* extension = extension_service()->GetExtensionById( - last_loaded_extension_id(), false /*include_disabled*/); + const Extension* extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); auto verify_script_redirected = [this, extension]( @@ -2414,8 +2430,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( {rule}, "test_extension", {URLPattern::kAllUrlsPattern})); - const Extension* extension = extension_service()->GetExtensionById( - last_loaded_extension_id(), false /*include_disabled*/); + const Extension* extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_TRUE(extension->permissions_data()->HasEffectiveAccessToAllHosts()); @@ -2477,7 +2493,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, DynamicRules) { std::vector<std::string>({"main_frame"}); redirect_rule.priority = kMinValidPriority; redirect_rule.action->type = std::string("redirect"); - redirect_rule.action->redirect_url = dynamic_redirect_url.spec(); + redirect_rule.action->redirect.emplace(); + redirect_rule.action->redirect->url = dynamic_redirect_url.spec(); redirect_rule.id = kMinValidID + 1; ASSERT_NO_FATAL_FAILURE(AddDynamicRules(last_loaded_extension_id(), @@ -2571,6 +2588,464 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, test_referrer_blocked(false); } +// Tests rules using the Redirect dictionary. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, Redirect) { + TestRule rule1 = CreateGenericRule(); + rule1.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule1.id = kMinValidID; + rule1.condition->url_filter = std::string("ex"); + rule1.action->type = std::string("redirect"); + rule1.priority = kMinValidPriority; + rule1.action->redirect.emplace(); + rule1.action->redirect->url = + embedded_test_server() + ->GetURL("google.com", "/pages_with_script/index.html") + .spec(); + + TestRule rule2 = CreateGenericRule(); + rule2.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule2.id = kMinValidID + 1; + rule2.condition->url_filter = std::string("example.com"); + rule2.action->type = std::string("redirect"); + rule2.priority = kMinValidPriority + 1; + rule2.action->redirect.emplace(); + rule2.action->redirect->extension_path = "/manifest.json?query#fragment"; + + TestRule rule3 = CreateGenericRule(); + rule3.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule3.id = kMinValidID + 2; + rule3.condition->url_filter = std::string("||example.com"); + rule3.action->type = std::string("redirect"); + rule3.priority = kMinValidPriority + 2; + rule3.action->redirect.emplace(); + rule3.action->redirect->transform.emplace(); + auto& transform = rule3.action->redirect->transform; + transform->host = "new.host.com"; + transform->path = "/pages_with_script/page.html"; + transform->query = "?new_query"; + transform->fragment = "#new_fragment"; + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {rule1, rule2, rule3}, "test_extension", {URLPattern::kAllUrlsPattern})); + + struct { + GURL url; + GURL expected_url; + } cases[] = {{embedded_test_server()->GetURL("example.com", + "/pages_with_script/index.html"), + // Because of higher priority, the transform rule is chosen. + embedded_test_server()->GetURL( + "new.host.com", + "/pages_with_script/page.html?new_query#new_fragment")}, + // Because of higher priority, the extensionPath rule is chosen. + {embedded_test_server()->GetURL( + "xyz.com", "/pages_with_script/index.html?example.com"), + GURL("chrome-extension://" + last_loaded_extension_id() + + "/manifest.json?query#fragment")}, + {embedded_test_server()->GetURL("ex.com", + "/pages_with_script/index.html"), + embedded_test_server()->GetURL( + "google.com", "/pages_with_script/index.html")}}; + + for (const auto& test_case : cases) { + SCOPED_TRACE("Testing " + test_case.url.spec()); + ui_test_utils::NavigateToURL(browser(), test_case.url); + EXPECT_EQ(test_case.expected_url, web_contents()->GetLastCommittedURL()); + } +} + +// Test that the badge text for an extension will update to reflect the number +// of actions taken on requests matching the extension's ruleset. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionsMatchedCountAsBadgeText) { + auto get_url_for_host = [this](std::string hostname) { + return embedded_test_server()->GetURL(hostname, + "/pages_with_script/index.html"); + }; + + // This page simulates a user clicking on a link, so that the next page it + // navigates to has a Referrer header. + auto get_url_with_referrer = [this](std::string hostname) { + return embedded_test_server()->GetURL(hostname, "/simulate_click.html"); + }; + + // Navigates frame with name |frame_name| to |url|. + auto navigate_frame = [this](const std::string& frame_name, const GURL& url) { + content::TestNavigationObserver navigation_observer( + web_contents(), 1 /*number_of_navigations*/); + + // Before navigation, We set the referrer policy of the iframe to + // 'no-referrer' to prevent a referer header from being added for the iframe + // navigation. + ASSERT_TRUE(content::ExecuteScript( + GetMainFrame(), + base::StringPrintf(R"( + document.getElementsByName('%s')[0].referrerPolicy = 'no-referrer'; + document.getElementsByName('%s')[0].src = '%s';)", + frame_name.c_str(), frame_name.c_str(), + url.spec().c_str()))); + navigation_observer.Wait(); + }; + + const std::string kFrameName1 = "frame1"; + const GURL page_url = embedded_test_server()->GetURL( + "norulesmatched.com", "/page_with_two_frames.html"); + + struct { + std::string url_filter; + int id; + int priority; + std::string action_type; + base::Optional<std::string> redirect_url; + base::Optional<std::vector<std::string>> remove_headers_list; + } rules_data[] = { + {"abc.com", 1, 1, "block", base::nullopt, base::nullopt}, + {"def.com", 2, 1, "redirect", "http://zzz.com", base::nullopt}, + {"jkl.com", 3, 1, "removeHeaders", base::nullopt, + std::vector<std::string>({"referer"})}, + {"abcd.com", 4, 1, "block", base::nullopt, base::nullopt}, + {"abcd", 5, 1, "allow", base::nullopt, base::nullopt}, + }; + + // Load the extension. + std::vector<TestRule> rules; + for (const auto& rule_data : rules_data) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = rule_data.url_filter; + rule.id = rule_data.id; + rule.priority = rule_data.priority; + rule.condition->resource_types = + std::vector<std::string>({"main_frame", "sub_frame"}); + rule.action->type = rule_data.action_type; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; + rule.action->remove_headers_list = rule_data.remove_headers_list; + rules.push_back(rule); + } + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId& extension_id = last_loaded_extension_id(); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + + ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText(extension_id, + true); + + ExtensionAction* action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + struct { + std::string frame_hostname; + std::string expected_badge_text; + bool has_referrer_header; + } test_cases[] = { + // zzz.com does not match any rules, but we should still display 0 as the + // badge text as the preference is on. + {"zzz.com", "0", false}, + // abc.com is blocked by a matching rule and should increment the badge + // text. + {"abc.com", "1", false}, + // def.com is redirected by a matching rule and should increment the badge + // text. + {"def.com", "2", false}, + // jkl.com matches with a removeHeaders rule, but has no headers. + // Therefore no action is taken and the badge text stays the same. + {"jkl.com", "2", false}, + // jkl.com matches with a removeHeaders rule and has a referrer header. + // Therefore the badge text should be incremented. + {"jkl.com", "3", true}, + // abcd.com matches both a block rule and an allow rule. Since the allow + // rule overrides the block rule, no action is taken and the badge text + // stays the same, + {"abcd.com", "3", false}, + }; + + ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); + + // Verify that the badge text is 0 when navigation finishes. + int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ("0", action->GetDisplayBadgeText(first_tab_id)); + + for (const auto& test_case : test_cases) { + GURL url = test_case.has_referrer_header + ? get_url_with_referrer(test_case.frame_hostname) + : get_url_for_host(test_case.frame_hostname); + SCOPED_TRACE(base::StringPrintf("Testing %s", url.spec().c_str())); + + navigate_frame(kFrameName1, url); + EXPECT_EQ(test_case.expected_badge_text, + action->GetDisplayBadgeText(first_tab_id)); + } + + std::string first_tab_badge_text = action->GetDisplayBadgeText(first_tab_id); + + const GURL second_tab_url = get_url_for_host("nomatch.com"); + ui_test_utils::NavigateToURLWithDisposition( + browser(), second_tab_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, + ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); + + ASSERT_EQ(2, browser()->tab_strip_model()->count()); + ASSERT_TRUE(browser()->tab_strip_model()->IsTabSelected(1)); + + int second_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ("0", action->GetDisplayBadgeText(second_tab_id)); + + // Verify that the badge text for the first tab is unaffected. + EXPECT_EQ(first_tab_badge_text, action->GetDisplayBadgeText(first_tab_id)); +} + +// Test that the extension cannot retrieve the number of actions matched +// from the badge text by calling chrome.browserAction.getBadgeText. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + GetBadgeTextForActionsMatched) { + auto query_badge_text_from_ext = [this](const ExtensionId& extension_id, + int tab_id) { + static constexpr char kBadgeTextQueryScript[] = R"( + chrome.browserAction.getBadgeText({tabId: %d}, badgeText => { + window.domAutomationController.send(badgeText); + }); + )"; + + return ExecuteScriptInBackgroundPage( + extension_id, base::StringPrintf(kBadgeTextQueryScript, tab_id)); + }; + + // Load the extension with a background script so scripts can be run from its + // generated background page. + set_has_background_script(true); + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {}, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId& extension_id = last_loaded_extension_id(); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + + ExtensionAction* action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + const std::string default_badge_text = "asdf"; + action->SetBadgeText(ExtensionAction::kDefaultTabId, default_badge_text); + + const GURL page_url = embedded_test_server()->GetURL( + "norulesmatched.com", "/pages_with_script/index.html"); + ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); + + // The preference is initially turned off. Both the visible badge text and the + // badge text queried by the extension using getBadgeText() should return the + // default badge text. + int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ(default_badge_text, action->GetDisplayBadgeText(first_tab_id)); + + std::string queried_badge_text = + query_badge_text_from_ext(extension_id, first_tab_id); + EXPECT_EQ(default_badge_text, queried_badge_text); + + SetActionsAsBadgeText(extension_id, true); + // Since the preference is on for the current tab, attempting to query the + // badge text from the extension should return the placeholder text instead of + // the matched action count. + queried_badge_text = query_badge_text_from_ext(extension_id, first_tab_id); + EXPECT_EQ(declarative_net_request::kActionCountPlaceholderBadgeText, + queried_badge_text); + + // The displayed badge text should show "0" as no actions have been matched. + EXPECT_EQ("0", action->GetDisplayBadgeText(first_tab_id)); + + SetActionsAsBadgeText(extension_id, false); + // Switching the preference off should cause the extension queried badge text + // to be the explicitly set badge text for this tab if it exists. In this + // case, the queried badge text should be the default badge text. + queried_badge_text = query_badge_text_from_ext(extension_id, first_tab_id); + EXPECT_EQ(default_badge_text, queried_badge_text); + + // The displayed badge text should be the default badge text now that the + // preference is off. + EXPECT_EQ(default_badge_text, action->GetDisplayBadgeText(first_tab_id)); + + // Verify that turning off the preference deletes the DNR action count within + // the extension action. + EXPECT_FALSE(action->HasDNRActionCount(first_tab_id)); +} + +// Test that enabling the setActionCountAsBadgeText preference will update +// all browsers sharing the same browser context. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionCountPreferenceMultipleWindows) { + // Load the extension with a background script so scripts can be run from its + // generated background page. + set_has_background_script(true); + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {}, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId& extension_id = last_loaded_extension_id(); + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + + ExtensionAction* extension_action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + const GURL page_url = embedded_test_server()->GetURL( + "norulesmatched.com", "/pages_with_script/index.html"); + ui_test_utils::NavigateToURL(browser(), page_url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); + + int first_browser_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + EXPECT_EQ("", extension_action->GetDisplayBadgeText(first_browser_tab_id)); + + // 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(WasFrameWithScriptLoaded(GetMainFrame(second_browser))); + content::WebContents* second_browser_contents = + second_browser->tab_strip_model()->GetActiveWebContents(); + + int second_browser_tab_id = + ExtensionTabUtil::GetTabId(second_browser_contents); + EXPECT_EQ("", extension_action->GetDisplayBadgeText(second_browser_tab_id)); + + // Set up an observer to listen for ExtensionAction updates for the active web + // contents of both browser windows. + TestExtensionActionAPIObserver test_api_observer( + profile(), extension_id, {web_contents(), second_browser_contents}); + + SetActionsAsBadgeText(extension_id, true); + + // Wait until ExtensionActionAPI::NotifyChange is called, then perform a + // sanity check on the browser action's badge text. + test_api_observer.Wait(); + + EXPECT_EQ("0", extension_action->GetDisplayBadgeText(first_browser_tab_id)); + + // The badge text for the second browser window should also update to the + // matched action count because the second browser shares the same browser + // context as the first. + EXPECT_EQ("0", extension_action->GetDisplayBadgeText(second_browser_tab_id)); +} + +// Test that the action matched badge text for an extension is visible in an +// incognito context if the extension is incognito enabled. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionsMatchedCountAsBadgeTextIncognito) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = "abc.com"; + rule.id = kMinValidID; + rule.condition->resource_types = std::vector<std::string>({"main_frame"}); + rule.action->type = "block"; + + std::vector<TestRule> rules({rule}); + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {rules}, "test_extension", {URLPattern::kAllUrlsPattern})); + + const ExtensionId extension_id = last_loaded_extension_id(); + util::SetIsIncognitoEnabled(extension_id, profile(), true /*enabled*/); + + ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText(extension_id, + true); + + Browser* incognito_browser = CreateIncognitoBrowser(); + ui_test_utils::NavigateToURL(incognito_browser, GURL("http://abc.com")); + + content::WebContents* incognito_contents = + incognito_browser->tab_strip_model()->GetActiveWebContents(); + + const Extension* dnr_extension = extension_registry()->GetExtensionById( + extension_id, extensions::ExtensionRegistry::ENABLED); + ExtensionAction* incognito_action = + ExtensionActionManager::Get(incognito_contents->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + // TODO(crbug.com/992251): This should be a "1" after the main-frame + // navigation case is fixed. + EXPECT_EQ("0", incognito_action->GetDisplayBadgeText( + ExtensionTabUtil::GetTabId(incognito_contents))); +} + +// Test that the actions matched badge text for an extension will be reset +// when a main-frame navigation finishes. +// TODO(crbug.com/992251): Edit this test to add more main-frame cases. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + ActionsMatchedCountAsBadgeTextMainFrame) { + auto get_url_for_host = [this](std::string hostname) { + return embedded_test_server()->GetURL(hostname, + "/pages_with_script/index.html"); + }; + + struct { + std::string url_filter; + int id; + int priority; + std::string action_type; + std::vector<std::string> resource_types; + base::Optional<std::string> redirect_url; + } rules_data[] = { + {"abc.com", 1, 1, "block", std::vector<std::string>({"script"}), + base::nullopt}, + {"def.com", 2, 1, "redirect", std::vector<std::string>({"main_frame"}), + get_url_for_host("abc.com").spec()}, + }; + + // Load the extension. + std::vector<TestRule> rules; + for (const auto& rule_data : rules_data) { + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = rule_data.url_filter; + rule.id = rule_data.id; + rule.priority = rule_data.priority; + rule.condition->resource_types = rule_data.resource_types; + rule.action->type = rule_data.action_type; + rule.action->redirect.emplace(); + rule.action->redirect->url = rule_data.redirect_url; + rules.push_back(rule); + } + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules, "test_extension", {URLPattern::kAllUrlsPattern})); + + const Extension* dnr_extension = extension_registry()->GetExtensionById( + last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED); + + ExtensionPrefs::Get(profile())->SetDNRUseActionCountAsBadgeText( + last_loaded_extension_id(), true); + + ExtensionAction* action = + ExtensionActionManager::Get(web_contents()->GetBrowserContext()) + ->GetExtensionAction(*dnr_extension); + + struct { + std::string frame_hostname; + std::string expected_badge_text; + } test_cases[] = { + // The script on get_url_for_host("abc.com") matches with a rule and + // should increment the badge text. + {"abc.com", "1"}, + // No rules match, so the badge text should be 0 once navigation finishes. + {"nomatch.com", "0"}, + // The request to def.com will redirect to get_url_for_host("abc.com") and + // the script on abc.com should match with a rule. + {"def.com", "1"}, + }; + + int first_tab_id = ExtensionTabUtil::GetTabId(web_contents()); + for (const auto& test_case : test_cases) { + 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); + EXPECT_EQ(test_case.expected_badge_text, + action->GetDisplayBadgeText(first_tab_id)); + } +} + // Test fixture to verify that host permissions for the request url and the // request initiator are properly checked when redirecting requests. Loads an // example.com url with four sub-frames named frame_[1..4] from hosts @@ -2595,7 +3070,8 @@ class DeclarativeNetRequestHostPermissionsBrowserTest rule.condition->url_filter = std::string("not_a_valid_child_frame.html"); rule.condition->resource_types = std::vector<std::string>({"sub_frame"}); rule.action->type = std::string("redirect"); - rule.action->redirect_url = + rule.action->redirect.emplace(); + rule.action->redirect->url = embedded_test_server()->GetURL("foo.com", "/child_frame.html").spec(); ASSERT_NO_FATAL_FAILURE( diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc index eb626a6c874..7d3391696c1 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/rule_indexing_unittest.cc @@ -191,7 +191,8 @@ TEST_P(RuleIndexingTest, DuplicateResourceTypes) { TEST_P(RuleIndexingTest, EmptyRedirectRulePriority) { TestRule rule = CreateGenericRule(); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("https://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("https://google.com"); AddRule(rule); LoadAndExpectError( ParseInfo(ParseResult::ERROR_EMPTY_REDIRECT_RULE_PRIORITY, *rule.id) @@ -208,7 +209,7 @@ TEST_P(RuleIndexingTest, EmptyRedirectRuleUrl) { rule.priority = kMinValidPriority; AddRule(rule); - LoadAndExpectError(ParseInfo(ParseResult::ERROR_EMPTY_REDIRECT_URL, *rule.id) + LoadAndExpectError(ParseInfo(ParseResult::ERROR_INVALID_REDIRECT, *rule.id) .GetErrorDescription()); } @@ -223,7 +224,8 @@ TEST_P(RuleIndexingTest, InvalidRuleID) { TEST_P(RuleIndexingTest, InvalidRedirectRulePriority) { TestRule rule = CreateGenericRule(); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("https://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("https://google.com"); rule.priority = kMinValidPriority - 1; AddRule(rule); LoadAndExpectError( @@ -271,7 +273,8 @@ TEST_P(RuleIndexingTest, EmptyURLFilter) { TEST_P(RuleIndexingTest, InvalidRedirectURL) { TestRule rule = CreateGenericRule(); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("google"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("google"); rule.priority = kMinValidPriority; AddRule(rule); LoadAndExpectError( 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 d2648003e57..808d1b52973 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 @@ -307,7 +307,8 @@ TEST_P(RulesetManagerTest, Redirect) { rule.condition->url_filter = std::string("example.com"); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("http://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("http://google.com"); std::unique_ptr<CompositeMatcher> matcher; ASSERT_NO_FATAL_FAILURE( CreateMatcherForRules({rule}, "test_extension", &matcher, @@ -373,7 +374,8 @@ TEST_P(RulesetManagerTest, ExtensionScheme) { rule.condition->url_filter = std::string("*"); rule.priority = kMinValidPriority; rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("http://google.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("http://google.com"); ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules( {rule}, "test extension_2", &matcher, std::vector<std::string>({URLPattern::kAllUrlsPattern}), @@ -460,7 +462,7 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { int frame_id; int parent_frame_id; std::string last_committed_main_frame_url; - base::Optional<std::string> pending_main_frame_url; + base::Optional<GURL> pending_main_frame_url; }; struct TestCase { std::string url; @@ -511,7 +513,7 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { "http://example.com", kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - kAllowedPageURL, "http://example.com/xyz"}), + kAllowedPageURL, GURL("http://example.com/xyz")}), true}, // Here we'll determine |kAllowedPageURL| to be the main @@ -520,7 +522,7 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { "http://google.com", kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - kAllowedPageURL, "http://yahoo.com/xyz"}), + kAllowedPageURL, GURL("http://yahoo.com/xyz")}), false}, // In these cases both |pending_main_frame_url| and @@ -530,19 +532,20 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { "http://google.com", kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - "http://google.com/abc", kAllowedPageURL}), + "http://google.com/abc", GURL(kAllowedPageURL)}), false}, {"http://example.com/script.js", content::ResourceType::kScript, base::nullopt, kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - kAllowedPageURL, "http://google.com/abc"}), + kAllowedPageURL, GURL("http://google.com/abc")}), false}, {"http://example.com/script.js", content::ResourceType::kScript, base::nullopt, kDummyFrameRoutingId, FrameDataParams({ExtensionApiFrameIdMap::kTopFrameId, ExtensionApiFrameIdMap::kInvalidFrameId, - "http://yahoo.com/abc", "http://yahoo.com/allow123"}), + "http://yahoo.com/abc", + GURL("http://yahoo.com/allow123")}), true}, }; @@ -564,10 +567,8 @@ TEST_P(RulesetManagerTest, PageAllowingAPI) { const FrameDataParams& frame_params = *test_case.frame_data_params; params.frame_data = ExtensionApiFrameIdMap::FrameData( frame_params.frame_id, frame_params.parent_frame_id, kDummyTabId, - kDummyWindowId, GURL(frame_params.last_committed_main_frame_url)); - if (frame_params.pending_main_frame_url) - params.frame_data->pending_main_frame_url = - GURL(*frame_params.pending_main_frame_url); + kDummyWindowId, GURL(frame_params.last_committed_main_frame_url), + frame_params.pending_main_frame_url); } Action expected_action = test_case.expect_blocked_with_allowed_pages @@ -590,7 +591,8 @@ TEST_P(RulesetManagerTest, HostPermissionForInitiator) { rule.priority = kMinValidPriority; rule.condition->url_filter = std::string("example.com"); rule.action->type = std::string("redirect"); - rule.action->redirect_url = std::string("https://foo.com"); + rule.action->redirect.emplace(); + rule.action->redirect->url = std::string("https://foo.com"); std::vector<std::string> host_permissions = {"*://yahoo.com/*", "*://example.com/*"}; ASSERT_NO_FATAL_FAILURE(CreateMatcherForRules( diff --git a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc index fe07b62a6cf..9cf163ca4d9 100644 --- a/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_webrequest/webrequest_action_unittest.cc @@ -19,7 +19,7 @@ #include "chrome/common/chrome_paths.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_test_util.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/declarative_webrequest/request_stage.h" #include "extensions/browser/api/declarative_webrequest/webrequest_condition.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" 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 5ac5e3a80c3..897c6601bb7 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 @@ -19,7 +19,7 @@ #include "chrome/common/extensions/extension_test_util.h" #include "chrome/test/base/testing_profile.h" #include "components/url_matcher/url_matcher_constants.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/declarative/rules_registry_service.h" #include "extensions/browser/api/declarative_webrequest/webrequest_constants.h" #include "extensions/browser/api/web_request/permission_helper.h" @@ -223,7 +223,7 @@ class WebRequestRulesRegistryTest : public testing::Test { } protected: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; // Two extensions with host permissions for all URLs and the DWR permission. // Installation times will be so that |extension_| is older than 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 13b8da3d41e..9b97e1bbd96 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 @@ -83,7 +83,7 @@ bool DesktopCaptureChooseDesktopMediaFunction::RunAsync() { } if (!ExtensionTabUtil::GetTabById(*(params->target_tab->id), GetProfile(), - true, NULL, NULL, &web_contents, NULL)) { + true, &web_contents)) { error_ = kDesktopCaptureApiInvalidTabIdError; return false; } 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 595a331a6a2..798348f9e7a 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 @@ -67,7 +67,7 @@ class DesktopCaptureChooseDesktopMediaFunctionBase }; class DesktopCaptureCancelChooseDesktopMediaFunctionBase - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DesktopCaptureCancelChooseDesktopMediaFunctionBase(); 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 a923c4d2d71..6cd0dd1f2f8 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 @@ -14,6 +14,7 @@ #include "base/files/file_util.h" #include "base/guid.h" #include "base/lazy_instance.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" @@ -176,8 +177,9 @@ void GetManifestError(const std::string& error, // This will read the manifest and call AddFailure with the read manifest // contents. - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_BLOCKING}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_BLOCKING}, base::BindOnce(&ReadFileToString, extension_path.Append(kManifestFilename)), base::BindOnce(std::move(callback), extension_path, error, line)); @@ -1472,9 +1474,10 @@ bool DeveloperPrivateLoadDirectoryFunction::LoadByFileSystemAPI( project_base_path_ = project_path; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce( &DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent, this, project_base_path_)); @@ -1498,7 +1501,7 @@ void DeveloperPrivateLoadDirectoryFunction::ClearExistingDirectoryContent( pending_copy_operations_count_ = 1; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce( &DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPI, @@ -1563,7 +1566,7 @@ void DeveloperPrivateLoadDirectoryFunction::ReadDirectoryByFileSystemAPICb( pending_copy_operations_count_--; if (!pending_copy_operations_count_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::SendResponse, this, success_)); @@ -1583,9 +1586,10 @@ void DeveloperPrivateLoadDirectoryFunction::SnapshotFileCallback( return; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, - {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + {base::ThreadPool(), base::MayBlock(), + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::CopyFile, this, src_path, target_path)); } @@ -1605,7 +1609,7 @@ void DeveloperPrivateLoadDirectoryFunction::CopyFile( pending_copy_operations_count_--; if (!pending_copy_operations_count_) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&DeveloperPrivateLoadDirectoryFunction::Load, this)); } @@ -1710,8 +1714,9 @@ DeveloperPrivateRequestFileSourceFunction::Run() { if (properties.path_suffix == kManifestFile && !properties.manifest_key) return RespondNow(Error(kManifestKeyIsRequiredError)); - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&ReadFileToString, extension->path().Append(path_suffix)), base::Bind(&DeveloperPrivateRequestFileSourceFunction::Finish, this)); @@ -1817,7 +1822,7 @@ DeveloperPrivateOpenDevToolsFunction::Run() { // ... but some pages (popups and apps) don't have tabs, and some (background // pages) don't have an associated browser. For these, the inspector opens in // a new window, and our work is done. - if (!browser || !browser->is_type_tabbed()) + if (!browser || !browser->is_type_normal()) return RespondNow(NoArguments()); TabStripModel* tab_strip = browser->tab_strip_model(); @@ -1886,11 +1891,10 @@ DeveloperPrivateRepairExtensionFunction::Run() { if (!web_contents) return RespondNow(Error(kCouldNotFindWebContentsError)); - scoped_refptr<WebstoreReinstaller> reinstaller(new WebstoreReinstaller( + auto reinstaller = base::MakeRefCounted<WebstoreReinstaller>( web_contents, params->extension_id, base::BindOnce( - &DeveloperPrivateRepairExtensionFunction::OnReinstallComplete, - this))); + &DeveloperPrivateRepairExtensionFunction::OnReinstallComplete, this)); reinstaller->BeginReinstall(); return RespondLater(); 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 4113d204780..639cf9e4777 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 @@ -294,7 +294,7 @@ void BrowserContextKeyedAPIFactory< namespace api { -class DeveloperPrivateAPIFunction : public UIThreadExtensionFunction { +class DeveloperPrivateAPIFunction : public ExtensionFunction { protected: ~DeveloperPrivateAPIFunction() override; @@ -488,7 +488,7 @@ class DeveloperPrivateShowPermissionsDialogFunction DISALLOW_COPY_AND_ASSIGN(DeveloperPrivateShowPermissionsDialogFunction); }; -class DeveloperPrivateChooseEntryFunction : public UIThreadExtensionFunction, +class DeveloperPrivateChooseEntryFunction : public ExtensionFunction, public EntryPickerClient { protected: ~DeveloperPrivateChooseEntryFunction() override; @@ -498,7 +498,6 @@ class DeveloperPrivateChooseEntryFunction : public UIThreadExtensionFunction, int file_type_index); }; - class DeveloperPrivateLoadUnpackedFunction : public DeveloperPrivateChooseEntryFunction { public: @@ -611,8 +610,7 @@ class DeveloperPrivatePackDirectoryFunction std::string key_path_str_; }; -class DeveloperPrivateIsProfileManagedFunction - : public UIThreadExtensionFunction { +class DeveloperPrivateIsProfileManagedFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("developerPrivate.isProfileManaged", DEVELOPERPRIVATE_ISPROFILEMANAGED) 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 b3d60b9ec88..7dc5b23f894 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 @@ -31,7 +31,6 @@ #include "chrome/test/base/testing_profile.h" #include "components/crx_file/id_util.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" -#include "components/services/unzip/unzip_service.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/browser/notification_service.h" #include "content/public/test/web_contents_tester.h" @@ -127,7 +126,7 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestWithInstall { // A wrapper around extension_function_test_utils::RunFunction that runs with // the associated browser, no flags, and can take stack-allocated arguments. - bool RunFunction(const scoped_refptr<UIThreadExtensionFunction>& function, + bool RunFunction(const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args); // Loads an unpacked extension that is backed by a real directory, allowing @@ -185,7 +184,7 @@ class DeveloperPrivateApiUnitTest : public ExtensionServiceTestWithInstall { }; bool DeveloperPrivateApiUnitTest::RunFunction( - const scoped_refptr<UIThreadExtensionFunction>& function, + const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args) { return extension_function_test_utils::RunFunction( function.get(), args.CreateDeepCopy(), browser(), api_test_utils::NONE); @@ -235,7 +234,7 @@ void DeveloperPrivateApiUnitTest::TestExtensionPrefSetting( const base::Callback<bool()>& has_pref, const std::string& key, const std::string& extension_id) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateUpdateExtensionConfigurationFunction()); EXPECT_FALSE(has_pref.Run()) << key; @@ -280,7 +279,7 @@ testing::AssertionResult DeveloperPrivateApiUnitTest::TestPackExtensionFunction( const base::ListValue& args, api::developer_private::PackStatus expected_status, int expected_flags) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivatePackDirectoryFunction()); if (!RunFunction(function, args)) return testing::AssertionFailure() << "Could not run function."; @@ -309,7 +308,7 @@ testing::AssertionResult DeveloperPrivateApiUnitTest::TestPackExtensionFunction( void DeveloperPrivateApiUnitTest::UpdateProfileConfigurationDevMode( bool dev_mode) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateUpdateProfileConfigurationFunction()); std::unique_ptr<base::ListValue> args = ListBuilder() @@ -320,7 +319,7 @@ void DeveloperPrivateApiUnitTest::UpdateProfileConfigurationDevMode( void DeveloperPrivateApiUnitTest::GetProfileConfiguration( std::unique_ptr<api::developer_private::ProfileInfo>* profile_info) { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetProfileConfigurationFunction()); base::ListValue args; EXPECT_TRUE(RunFunction(function, args)) << function->GetError(); @@ -338,7 +337,7 @@ void DeveloperPrivateApiUnitTest::RunUpdateHostAccess( base::StringPiece new_access) { SCOPED_TRACE(new_access); ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; - scoped_refptr<UIThreadExtensionFunction> function = base::MakeRefCounted< + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted< api::DeveloperPrivateUpdateExtensionConfigurationFunction>(); std::string args = base::StringPrintf(R"([{"extensionId": "%s", "hostAccess": "%s"}])", @@ -360,7 +359,7 @@ void DeveloperPrivateApiUnitTest::SetUp() { browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); @@ -406,14 +405,14 @@ TEST_F(DeveloperPrivateApiUnitTest, TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateReload) { const Extension* extension = LoadUnpackedExtension(); std::string extension_id = extension->id(); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateReloadFunction()); base::ListValue reload_args; reload_args.AppendString(extension_id); TestExtensionRegistryObserver registry_observer(registry()); EXPECT_TRUE(RunFunction(function, reload_args)); - const Extension* unloaded_extension = + scoped_refptr<const Extension> unloaded_extension = registry_observer.WaitForExtensionUnloaded(); EXPECT_EQ(extension, unloaded_extension); const Extension* reloaded_extension = @@ -487,7 +486,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateChoosePath) { base::ListValue choose_args; choose_args.AppendString("FOLDER"); choose_args.AppendString("LOAD"); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateChoosePathFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); EXPECT_TRUE(RunFunction(function, choose_args)) << function->GetError(); @@ -528,7 +527,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpacked) { // Try loading a good extension (it should succeed, and the extension should // be added). - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); ExtensionIdSet current_ids = registry()->enabled_extensions().GetIDs(); @@ -578,7 +577,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpackedLoadError) { base::FilePath path = dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -605,7 +604,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpackedLoadError) { base::FilePath path = dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -637,7 +636,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateLoadUnpackedLoadError) { base::FilePath path = dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -670,7 +669,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { { // Trying to load the extension should result in a load error with the // retry id populated. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -690,7 +689,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { // same retry id. This is somewhat an implementation detail, but is // important to ensure we don't allocate crazy numbers of ids if the user // just retries continuously. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -719,7 +718,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { base::FilePath second_path = second_dir.UnpackedPath(); api::EntryPicker::SkipPickerAndAlwaysSelectPathForTest(&second_path); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::unique_ptr<base::Value> result = @@ -750,7 +749,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { { // Try reloading the extension by supplying the retry id. It should succeed. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); TestExtensionRegistryObserver observer(registry()); @@ -767,7 +766,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedRetryId) { { // Try supplying an invalid retry id. It should fail with an error. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateLoadUnpackedFunction()); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = api_test_utils::RunFunctionAndReturnError( @@ -996,7 +995,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateRequestFileSource) { properties.message = kErrorMessage; properties.manifest_key.reset(new std::string("name")); - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateRequestFileSourceFunction()); base::ListValue file_source_args; file_source_args.Append(properties.ToValue()); @@ -1022,7 +1021,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateGetExtensionsInfo) { // ExtensionInfoGenerator's unittest), but rather just to make sure we can // serialize/deserialize the result - which implicity tests that everything // has a sane value. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetExtensionsInfoFunction()); EXPECT_TRUE(RunFunction(function, base::ListValue())) << function->GetError(); const base::ListValue* results = function->GetResultList(); @@ -1081,7 +1080,7 @@ TEST_F(DeveloperPrivateApiUnitTest, DeveloperPrivateDeleteExtensionErrors) { .Set("type", type_string) .Build()) .Build(); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new api::DeveloperPrivateDeleteExtensionErrorsFunction(); EXPECT_TRUE(RunFunction(function, *args)) << function->GetError(); // Two errors should remain. @@ -1124,7 +1123,7 @@ TEST_F(DeveloperPrivateApiUnitTest, RepairNotBrokenExtension) { // Attempt to repair the good extension, expect failure. std::unique_ptr<base::ListValue> args = ListBuilder().Append(extension->id()).Build(); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new api::DeveloperPrivateRepairExtensionFunction(); EXPECT_FALSE(RunFunction(function, *args)); EXPECT_EQ("Cannot repair a healthy extension.", function->GetError()); @@ -1155,7 +1154,7 @@ TEST_F(DeveloperPrivateApiUnitTest, RepairPolicyExtension) { // Attempt to repair the good extension, expect failure. std::unique_ptr<base::ListValue> args = ListBuilder().Append(extension_id).Build(); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new api::DeveloperPrivateRepairExtensionFunction(); EXPECT_FALSE(RunFunction(function, *args)); EXPECT_EQ("Cannot repair a healthy extension.", function->GetError()); @@ -1220,7 +1219,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedFailsWithoutDevMode) { PrefService* prefs = profile()->GetPrefs(); prefs->SetBoolean(prefs::kExtensionsUIDeveloperMode, false); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = extension_function_test_utils::RunFunctionAndReturnError( @@ -1253,7 +1252,7 @@ TEST_F(DeveloperPrivateApiUnitTest, LoadUnpackedFailsWithBlacklistingPolicy) { EXPECT_FALSE(info->can_load_unpacked); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = extension_function_test_utils::RunFunctionAndReturnError( @@ -1296,7 +1295,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileNoDraggedPath) { std::unique_ptr<content::WebContents> web_contents( content::WebContentsTester::CreateTestWebContents(profile(), nullptr)); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1322,7 +1321,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileCrx) { DeveloperPrivateAPI::Get(profile())->SetDraggedPath(web_contents.get(), crx_path); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1345,7 +1344,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileUserScript) { DeveloperPrivateAPI::Get(profile())->SetDraggedPath(web_contents.get(), script_path); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1369,7 +1368,7 @@ TEST_F(DeveloperPrivateApiUnitTest, GrantHostPermission) { bool should_succeed, const char* expected_error) { SCOPED_TRACE(host); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateAddHostPermissionFunction>(); std::string args = base::StringPrintf(R"(["%s", "%s"])", @@ -1426,7 +1425,7 @@ TEST_F(DeveloperPrivateApiUnitTest, RemoveHostPermission) { bool should_succeed, const char* expected_error) { SCOPED_TRACE(host); - scoped_refptr<UIThreadExtensionFunction> function = base::MakeRefCounted< + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted< api::DeveloperPrivateRemoveHostPermissionFunction>(); std::string args = base::StringPrintf(R"(["%s", "%s"])", extension->id().c_str(), host.data()); @@ -1580,7 +1579,7 @@ TEST_F(DeveloperPrivateApiUnitTest, *extension_prefs->GetRuntimeGrantedPermissions(extension->id())); { - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateAddHostPermissionFunction>(); std::string args = base::StringPrintf( R"(["%s", "%s"])", extension->id().c_str(), "*://chromium.org/*"); @@ -1611,7 +1610,7 @@ TEST_F(DeveloperPrivateApiUnitTest, *extension_prefs->GetRuntimeGrantedPermissions(extension->id())); { - scoped_refptr<UIThreadExtensionFunction> function = base::MakeRefCounted< + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted< api::DeveloperPrivateRemoveHostPermissionFunction>(); std::string args = base::StringPrintf( R"(["%s", "%s"])", extension->id().c_str(), "*://chromium.org/*"); @@ -1731,7 +1730,7 @@ TEST_F(DeveloperPrivateApiUnitTest, InstallDroppedFileZip) { DeveloperPrivateAPI::Get(profile())->SetDraggedPath(web_contents.get(), zip_path); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateInstallDroppedFileFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); @@ -1766,7 +1765,7 @@ TEST_F(DeveloperPrivateApiSupervisedUserUnitTest, ASSERT_TRUE(profile()->IsSupervised()); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = base::MakeRefCounted<api::DeveloperPrivateLoadUnpackedFunction>(); function->SetRenderFrameHost(web_contents->GetMainFrame()); std::string error = extension_function_test_utils::RunFunctionAndReturnError( diff --git a/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc b/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc index 570844d39d4..f4cb2836829 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/developer_private_apitest.cc @@ -43,7 +43,7 @@ IN_PROC_BROWSER_TEST_F(DeveloperPrivateApiTest, InspectAppWindowView) { const Extension* app = LoadAndLaunchApp(dir); // Get the info about the app, including the inspectable views. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetExtensionInfoFunction()); std::unique_ptr<base::Value> result( extension_function_test_utils::RunFunctionAndReturnSingleResult( @@ -97,7 +97,7 @@ IN_PROC_BROWSER_TEST_F(DeveloperPrivateApiTest, InspectEmbeddedOptionsPage) { WaitForExtensionNotIdle(extension->id()); // Get the info about the extension, including the inspectable views. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new api::DeveloperPrivateGetExtensionInfoFunction()); std::unique_ptr<base::Value> result( extension_function_test_utils::RunFunctionAndReturnSingleResult( diff --git a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc index f886ffd58e4..afb404e5637 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/entry_picker.cc @@ -37,13 +37,13 @@ EntryPicker::EntryPicker(EntryPickerClient* client, : client_(client) { if (g_skip_picker_for_test) { if (g_path_to_be_picked_for_test) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EntryPicker::FileSelected, base::Unretained(this), *g_path_to_be_picked_for_test, 1, static_cast<void*>(nullptr))); } else { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&EntryPicker::FileSelectionCanceled, base::Unretained(this), static_cast<void*>(nullptr))); diff --git a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc index d51463b16ef..095b9e97d3f 100644 --- a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc @@ -17,6 +17,7 @@ #include "extensions/browser/api/usb/usb_device_manager.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/extension.h" +#include "mojo/public/cpp/bindings/pending_remote.h" #include "services/device/public/cpp/hid/fake_hid_manager.h" #include "services/device/public/cpp/test/fake_usb_device_manager.h" #include "services/device/public/mojom/hid.mojom.h" @@ -53,10 +54,10 @@ class DevicePermissionsManagerTest : public testing::Test { "}")); // Set fake device manager for extensions::UsbDeviceManager. - device::mojom::UsbDeviceManagerPtr usb_manager_ptr; - fake_usb_manager_.AddBinding(mojo::MakeRequest(&usb_manager_ptr)); + mojo::PendingRemote<device::mojom::UsbDeviceManager> usb_manager; + fake_usb_manager_.AddReceiver(usb_manager.InitWithNewPipeAndPassReceiver()); UsbDeviceManager::Get(env_->profile()) - ->SetDeviceManagerForTesting(std::move(usb_manager_ptr)); + ->SetDeviceManagerForTesting(std::move(usb_manager)); base::RunLoop().RunUntilIdle(); device0_ = fake_usb_manager_.CreateAndAddDevice(0, 0, "Test Manufacturer", diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc index 689928221a8..7ba05fc5f7a 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc @@ -929,13 +929,14 @@ const char ExtensionDownloadsEventRouterData::kKey[] = bool OnDeterminingFilenameWillDispatchCallback( bool* any_determiners, ExtensionDownloadsEventRouterData* data, - content::BrowserContext* context, + content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { *any_determiners = true; base::Time installed = - ExtensionPrefs::Get(context)->GetInstallTime(extension->id()); + ExtensionPrefs::Get(browser_context)->GetInstallTime(extension->id()); data->AddPendingDeterminer(extension->id(), installed); return true; } diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h index 105cbe800e6..1f39ba01ffd 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h @@ -107,7 +107,7 @@ class DownloadsDownloadFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsDownloadFunction); }; -class DownloadsSearchFunction : public UIThreadExtensionFunction { +class DownloadsSearchFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.search", DOWNLOADS_SEARCH) DownloadsSearchFunction(); @@ -120,7 +120,7 @@ class DownloadsSearchFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsSearchFunction); }; -class DownloadsPauseFunction : public UIThreadExtensionFunction { +class DownloadsPauseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.pause", DOWNLOADS_PAUSE) DownloadsPauseFunction(); @@ -133,7 +133,7 @@ class DownloadsPauseFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsPauseFunction); }; -class DownloadsResumeFunction : public UIThreadExtensionFunction { +class DownloadsResumeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.resume", DOWNLOADS_RESUME) DownloadsResumeFunction(); @@ -146,7 +146,7 @@ class DownloadsResumeFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsResumeFunction); }; -class DownloadsCancelFunction : public UIThreadExtensionFunction { +class DownloadsCancelFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.cancel", DOWNLOADS_CANCEL) DownloadsCancelFunction(); @@ -159,7 +159,7 @@ class DownloadsCancelFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsCancelFunction); }; -class DownloadsEraseFunction : public UIThreadExtensionFunction { +class DownloadsEraseFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.erase", DOWNLOADS_ERASE) DownloadsEraseFunction(); @@ -211,7 +211,7 @@ class DownloadsAcceptDangerFunction : public ChromeAsyncExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsAcceptDangerFunction); }; -class DownloadsShowFunction : public UIThreadExtensionFunction { +class DownloadsShowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.show", DOWNLOADS_SHOW) DownloadsShowFunction(); @@ -224,7 +224,7 @@ class DownloadsShowFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsShowFunction); }; -class DownloadsShowDefaultFolderFunction : public UIThreadExtensionFunction { +class DownloadsShowDefaultFolderFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION( "downloads.showDefaultFolder", DOWNLOADS_SHOWDEFAULTFOLDER) @@ -238,7 +238,7 @@ class DownloadsShowDefaultFolderFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsShowDefaultFolderFunction); }; -class DownloadsOpenFunction : public UIThreadExtensionFunction { +class DownloadsOpenFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.open", DOWNLOADS_OPEN) DownloadsOpenFunction(); @@ -261,7 +261,7 @@ class DownloadsOpenFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(DownloadsOpenFunction); }; -class DownloadsSetShelfEnabledFunction : public UIThreadExtensionFunction { +class DownloadsSetShelfEnabledFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloads.setShelfEnabled", DOWNLOADS_SETSHELFENABLED) 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 039b3d9d3d8..0e2a4d31138 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc @@ -111,7 +111,7 @@ void OnOpenPromptCreated(download::DownloadItem* item, DownloadOpenPrompt* prompt) { EXPECT_FALSE(item->GetOpened()); // Posts a task to accept the DownloadOpenPrompt. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&DownloadOpenPrompt::AcceptConfirmationDialogForTesting, base::Unretained(prompt))); @@ -599,9 +599,8 @@ class DownloadExtensionTest : public ExtensionApiTest { GetCurrentManager(), download_count); } - bool RunFunction(UIThreadExtensionFunction* function, - const std::string& args) { - scoped_refptr<UIThreadExtensionFunction> delete_function(function); + bool RunFunction(ExtensionFunction* function, const std::string& args) { + scoped_refptr<ExtensionFunction> delete_function(function); SetUpExtensionFunction(function); bool result = extension_function_test_utils::RunFunction( function, args, current_browser(), GetFlags()); @@ -622,7 +621,7 @@ class DownloadExtensionTest : public ExtensionApiTest { // on-record profile to match real-life behavior. base::Value* RunFunctionAndReturnResult( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, const std::string& args) { SetUpExtensionFunction(function.get()); return extension_function_test_utils::RunFunctionAndReturnSingleResult( @@ -630,17 +629,16 @@ class DownloadExtensionTest : public ExtensionApiTest { } std::string RunFunctionAndReturnError( - scoped_refptr<UIThreadExtensionFunction> function, + scoped_refptr<ExtensionFunction> function, const std::string& args) { SetUpExtensionFunction(function.get()); return extension_function_test_utils::RunFunctionAndReturnError( function.get(), args, current_browser(), GetFlags()); } - bool RunFunctionAndReturnString( - scoped_refptr<UIThreadExtensionFunction> function, - const std::string& args, - std::string* result_string) { + bool RunFunctionAndReturnString(scoped_refptr<ExtensionFunction> function, + const std::string& args, + std::string* result_string) { SetUpExtensionFunction(function.get()); std::unique_ptr<base::Value> result( RunFunctionAndReturnResult(function, args)); @@ -661,7 +659,7 @@ class DownloadExtensionTest : public ExtensionApiTest { const Extension* extension() { return extension_; } private: - void SetUpExtensionFunction(UIThreadExtensionFunction* function) { + void SetUpExtensionFunction(ExtensionFunction* function) { if (extension_) { const GURL url = current_browser_ == incognito_browser_ && !IncognitoInfo::IsSplitMode(extension_) @@ -708,10 +706,9 @@ class MockIconExtractorImpl : public DownloadFileIconExtractor { if (expected_path_ == path && expected_icon_size_ == icon_size) { callback_ = callback; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&MockIconExtractorImpl::RunCallback, - base::Unretained(this))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&MockIconExtractorImpl::RunCallback, + base::Unretained(this))); return true; } else { return false; @@ -793,7 +790,7 @@ class HTML5FileWriter { // Invoke the fileapi to copy it into the sandboxed filesystem. bool result = false; base::RunLoop run_loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&CreateFileForTestingOnIOThread, base::Unretained(context), path, temp_file, @@ -810,7 +807,7 @@ class HTML5FileWriter { base::File::Error error) { DCHECK_CURRENTLY_ON(BrowserThread::IO); *result = error == base::File::FILE_OK; - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, quit_closure); + base::PostTask(FROM_HERE, {BrowserThread::UI}, quit_closure); } static void CreateFileForTestingOnIOThread( @@ -1044,7 +1041,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, EXPECT_EQ(id, element); } -scoped_refptr<UIThreadExtensionFunction> MockedGetFileIconFunction( +scoped_refptr<ExtensionFunction> MockedGetFileIconFunction( const base::FilePath& expected_path, IconLoader::IconSize icon_size, const std::string& response) { @@ -2324,14 +2321,14 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, " \"paused\": false," " \"url\": \"%s\"}]", download_url.c_str()))); - ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, - base::StringPrintf( - "[{\"id\": %d," - " \"filename\": {" - " \"previous\": \"\"," - " \"current\": \"%s\"}}]", - result_id, - GetFilename("file.txt").c_str()))); + // File will be renamed to file.html due to its mime type. + ASSERT_TRUE( + WaitFor(downloads::OnChanged::kEventName, + base::StringPrintf("[{\"id\": %d," + " \"filename\": {" + " \"previous\": \"\"," + " \"current\": \"%s\"}}]", + result_id, GetFilename("file.html").c_str()))); ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, base::StringPrintf( "[{\"id\": %d," @@ -3003,6 +3000,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, EXPECT_FALSE(determine_result.get()); // No return value. } +// 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) { @@ -3042,7 +3041,7 @@ IN_PROC_BROWSER_TEST_F( ASSERT_TRUE(item->GetTargetFilePath().empty()); ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); - // Respond to the onDeterminingFilename. + // Respond to the onDeterminingFilename with a dangerous extension. std::string error; ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename( current_browser()->profile(), false, GetExtensionId(), result_id, @@ -3051,12 +3050,68 @@ IN_PROC_BROWSER_TEST_F( EXPECT_EQ("", error); ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, - base::StringPrintf( - "[{\"id\": %d," - " \"danger\": {" - " \"previous\":\"safe\"," - " \"current\":\"file\"}}]", - result_id))); + base::StringPrintf("[{\"id\": %d," + " \"state\": {" + " \"previous\": \"in_progress\"," + " \"current\": \"complete\"}}]", + result_id))); + EXPECT_EQ(downloads_directory().AppendASCII("overridden.txt"), + item->GetTargetFilePath()); +} + +// Tests that overriding a dangerous file extension to a safe extension will +// trigger the dangerous prompt and will not change the extension. +IN_PROC_BROWSER_TEST_F( + DownloadExtensionTest, + DownloadExtensionTest_OnDeterminingFilename_SafeOverride) { + GoOnTheRecord(); + LoadExtension("downloads_split"); + AddFilenameDeterminer(); + + std::string download_url = "data:application/x-shockwave-flash,"; + // Start downloading a file. + std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( + new DownloadsDownloadFunction(), + base::StringPrintf("[{\"url\": \"%s\"}]", download_url.c_str()))); + ASSERT_TRUE(result.get()); + int result_id = -1; + ASSERT_TRUE(result->GetAsInteger(&result_id)); + DownloadItem* item = GetCurrentManager()->GetDownload(result_id); + ASSERT_TRUE(item); + ScopedCancellingItem canceller(item); + ASSERT_EQ(download_url, item->GetOriginalUrl().spec()); + + ASSERT_TRUE(WaitFor( + downloads::OnCreated::kEventName, + base::StringPrintf("[{\"danger\": \"safe\"," + " \"incognito\": false," + " \"id\": %d," + " \"mime\": \"application/x-shockwave-flash\"," + " \"paused\": false," + " \"url\": \"%s\"}]", + result_id, download_url.c_str()))); + ASSERT_TRUE(WaitFor(downloads::OnDeterminingFilename::kEventName, + base::StringPrintf("[{\"id\": %d," + " \"filename\":\"download.swf\"}]", + result_id))); + ASSERT_TRUE(item->GetTargetFilePath().empty()); + ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); + + // Respond to the onDeterminingFilename with a safe extension. + std::string error; + ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename( + current_browser()->profile(), false, GetExtensionId(), result_id, + base::FilePath(FILE_PATH_LITERAL("overridden.txt")), + downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY, &error)); + EXPECT_EQ("", error); + + // Dangerous download prompt will be shown. + ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, + base::StringPrintf("[{\"id\": %d, " + " \"danger\": {" + " \"previous\": \"safe\"," + " \"current\": \"file\"}}]", + result_id))); item->ValidateDangerousDownload(); ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, @@ -3066,6 +3121,7 @@ IN_PROC_BROWSER_TEST_F( " \"previous\":\"file\"," " \"current\":\"accepted\"}}]", result_id))); + ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, base::StringPrintf( "[{\"id\": %d," @@ -4159,7 +4215,7 @@ IN_PROC_BROWSER_TEST_F( // This test is very flaky on Win XP and Aura. http://crbug.com/248438 // Also flaky on Linux. http://crbug.com/700382 -// Also flaky on Mac ASAN with PlzNavigate. +// Also flaky on Mac ASAN. // Test download interruption while extensions determining filename. Should not // re-dispatch onDeterminingFilename. IN_PROC_BROWSER_TEST_F( @@ -4337,7 +4393,8 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, LoadExtension("downloads_split"); std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( new DownloadsDownloadFunction(), - "[{\"url\": \"data:,\", \"filename\": \"dangerous.swf\"}]")); + "[{\"url\": \"data:application/x-shockwave-flash,\", \"filename\": " + "\"dangerous.swf\"}]")); ASSERT_TRUE(result.get()); int result_id = -1; ASSERT_TRUE(result->GetAsInteger(&result_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 639906d4bbe..490c94eed33 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 @@ -10,8 +10,7 @@ namespace extensions { -class DownloadsInternalDetermineFilenameFunction - : public UIThreadExtensionFunction { +class DownloadsInternalDetermineFilenameFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloadsInternal.determineFilename", DOWNLOADSINTERNAL_DETERMINEFILENAME) diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc index 35679e37510..87b1c700975 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.cc @@ -19,8 +19,13 @@ namespace extensions { namespace { -// Checks for the current browser context if the user is affiliated. +// Checks for the current browser context if the user is affiliated or belongs +// to the sign-in profile. bool IsPermittedToGetDeviceAttributes(content::BrowserContext* context) { + if (chromeos::ProfileHelper::IsSigninProfile( + Profile::FromBrowserContext(context))) { + return true; + } const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile( Profile::FromBrowserContext(context)); diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h index 0f879217328..5c6a57cf641 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_api.h @@ -10,7 +10,7 @@ namespace extensions { class EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction(); @@ -25,7 +25,7 @@ class EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction }; class EnterpriseDeviceAttributesGetDeviceSerialNumberFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDeviceSerialNumberFunction(); @@ -41,7 +41,7 @@ class EnterpriseDeviceAttributesGetDeviceSerialNumberFunction }; class EnterpriseDeviceAttributesGetDeviceAssetIdFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDeviceAssetIdFunction(); @@ -56,7 +56,7 @@ class EnterpriseDeviceAttributesGetDeviceAssetIdFunction }; class EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction(); 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 1600ac52056..0d691184809 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 @@ -12,7 +12,7 @@ namespace extensions { class EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterpriseHardwarePlatformGetHardwarePlatformInfoFunction(); 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 1d0643aaf8b..2932c7037d5 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 @@ -281,12 +281,12 @@ EnterprisePlatformKeysChallengeMachineKeyFunction::Run() { this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeMachineKey::Run, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, StringFromVector(params->challenge), - params->register_key ? *params->register_key : false); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = + base::Bind(&EPKPChallengeMachineKey::Run, base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), callback, + StringFromVector(params->challenge), + params->register_key ? *params->register_key : false); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } @@ -322,11 +322,11 @@ EnterprisePlatformKeysChallengeUserKeyFunction::Run() { &EnterprisePlatformKeysChallengeUserKeyFunction::OnChallengedKey, this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeUserKey::Run, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, StringFromVector(params->challenge), params->register_key); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = + base::Bind(&EPKPChallengeUserKey::Run, base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), callback, + StringFromVector(params->challenge), params->register_key); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h index 6900eb2f582..9ec384a2ef3 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys/enterprise_platform_keys_api.h @@ -21,7 +21,7 @@ typedef std::vector<scoped_refptr<X509Certificate> > CertificateList; namespace extensions { class EnterprisePlatformKeysInternalGenerateKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysInternalGenerateKeyFunction() override; ResponseAction Run() override; @@ -35,8 +35,7 @@ class EnterprisePlatformKeysInternalGenerateKeyFunction ENTERPRISE_PLATFORMKEYSINTERNAL_GENERATEKEY) }; -class EnterprisePlatformKeysGetCertificatesFunction - : public UIThreadExtensionFunction { +class EnterprisePlatformKeysGetCertificatesFunction : public ExtensionFunction { private: ~EnterprisePlatformKeysGetCertificatesFunction() override; ResponseAction Run() override; @@ -51,7 +50,7 @@ class EnterprisePlatformKeysGetCertificatesFunction }; class EnterprisePlatformKeysImportCertificateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysImportCertificateFunction() override; ResponseAction Run() override; @@ -65,7 +64,7 @@ class EnterprisePlatformKeysImportCertificateFunction }; class EnterprisePlatformKeysRemoveCertificateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysRemoveCertificateFunction() override; ResponseAction Run() override; @@ -79,7 +78,7 @@ class EnterprisePlatformKeysRemoveCertificateFunction }; class EnterprisePlatformKeysInternalGetTokensFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~EnterprisePlatformKeysInternalGetTokensFunction() override; ResponseAction Run() override; @@ -94,7 +93,7 @@ class EnterprisePlatformKeysInternalGetTokensFunction }; class EnterprisePlatformKeysChallengeMachineKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysChallengeMachineKeyFunction(); explicit EnterprisePlatformKeysChallengeMachineKeyFunction( @@ -117,7 +116,7 @@ class EnterprisePlatformKeysChallengeMachineKeyFunction }; class EnterprisePlatformKeysChallengeUserKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysChallengeUserKeyFunction(); explicit EnterprisePlatformKeysChallengeUserKeyFunction( 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 5fa0fffc205..bffca7db092 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 @@ -85,6 +85,7 @@ void SignChallengeCallbackTrue( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, true, "response")); @@ -98,6 +99,7 @@ void SignChallengeCallbackFalse( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, false, "")); @@ -108,6 +110,7 @@ void GetCertificateCallbackTrue( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -121,6 +124,7 @@ void GetCertificateCallbackFalse( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -141,9 +145,9 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { ON_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .WillByDefault(Invoke(RegisterKeyCallbackTrue)); ON_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillByDefault(Invoke(SignChallengeCallbackTrue)); - ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillByDefault(Invoke(GetCertificateCallbackTrue)); stub_install_attributes_.SetCloudManaged("google.com", "device_id"); @@ -181,7 +185,7 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { // Like extension_function_test_utils::RunFunctionAndReturnError but with an // explicit ListValue. - std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, + std::string RunFunctionAndReturnError(ExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { utils::RunFunction(function, std::move(args), browser, @@ -193,7 +197,7 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { // Like extension_function_test_utils::RunFunctionAndReturnSingleResult but // with an explicit ListValue. base::Value* RunFunctionAndReturnSingleResult( - UIThreadExtensionFunction* function, + ExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { scoped_refptr<ExtensionFunction> function_owner(function); @@ -297,7 +301,7 @@ TEST_F(EPKChallengeMachineKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKChallengeMachineKeyTest, GetCertificateFailed) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackFalse)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -306,7 +310,7 @@ TEST_F(EPKChallengeMachineKeyTest, GetCertificateFailed) { TEST_F(EPKChallengeMachineKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -327,7 +331,8 @@ TEST_F(EPKChallengeMachineKeyTest, KeyExists) { std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) + .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), extensions::api_test_utils::NONE)); @@ -354,14 +359,14 @@ TEST_F(EPKChallengeMachineKeyTest, Success) { EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. - EXPECT_CALL( - mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), - "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) + EXPECT_CALL(mock_async_method_caller_, + TpmAttestationSignEnterpriseChallenge( + chromeos::attestation::KEY_DEVICE, + cryptohome::Identification(), "attest-ent-machine", + "google.com", "device_id", _, "challenge", _, _)) .Times(1); std::unique_ptr<base::Value> value( @@ -373,24 +378,26 @@ TEST_F(EPKChallengeMachineKeyTest, Success) { } TEST_F(EPKChallengeMachineKeyTest, KeyRegisteredSuccess) { + std::string key_name_for_spkac = "attest-ent-machine-" + extension_->id(); // GetCertificate must be called exactly once. EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); // TpmAttestationRegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(chromeos::attestation::KEY_DEVICE, _ /* Unused by the API. */, - "attest-ent-machine", _)) + key_name_for_spkac, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. EXPECT_CALL( mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), - "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) + "attest-ent-machine", "google.com", "device_id", _, "challenge", + key_name_for_spkac, _)) .Times(1); std::unique_ptr<base::Value> value(RunFunctionAndReturnSingleResult( @@ -488,7 +495,7 @@ TEST_F(EPKChallengeUserKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKChallengeUserKeyTest, GetCertificateFailed) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackFalse)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -497,7 +504,7 @@ TEST_F(EPKChallengeUserKeyTest, GetCertificateFailed) { TEST_F(EPKChallengeUserKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -518,7 +525,8 @@ TEST_F(EPKChallengeUserKeyTest, KeyExists) { AccountId::FromUserEmail(kUserEmail)), "attest-ent-user", std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) + .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), extensions::api_test_utils::NONE)); @@ -545,7 +553,7 @@ TEST_F(EPKChallengeUserKeyTest, Success) { EXPECT_CALL( mock_attestation_flow_, GetCertificate(chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); const cryptohome::Identification cryptohome_id( AccountId::FromUserEmail(kUserEmail)); @@ -554,7 +562,7 @@ TEST_F(EPKChallengeUserKeyTest, Success) { mock_async_method_caller_, TpmAttestationSignEnterpriseChallenge( chromeos::attestation::KEY_USER, cryptohome_id, "attest-ent-user", - kUserEmail, "device_id", _, "challenge", _)) + kUserEmail, "device_id", _, "challenge", _, _)) .Times(1); // RegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, 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 92e1bc05574..c68aaa5367b 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 @@ -43,6 +43,12 @@ #include "google_apis/gaia/gaia_auth_util.h" #include "third_party/cros_system_api/dbus/service_constants.h" +namespace { +// Prefix for naming machine keys used for SignedPublicKeyAndChallenge when +// challenging the EMK with register=true. +const char kEnterpriseMachineKeyForSpkacPrefix[] = "attest-ent-machine-"; +} // namespace + namespace extensions { namespace api_epkp = api::enterprise_platform_keys_private; @@ -68,12 +74,14 @@ EPKPChallengeKeyBase::PrepareKeyContext::PrepareKeyContext( const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback) : key_type(key_type), account_id(account_id), key_name(key_name), certificate_profile(certificate_profile), require_user_consent(require_user_consent), + key_name_for_spkac(key_name_for_spkac), callback(callback) {} EPKPChallengeKeyBase::PrepareKeyContext::PrepareKeyContext( @@ -199,13 +207,11 @@ void EPKPChallengeKeyBase::PrepareKey( const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback) { - const PrepareKeyContext context = PrepareKeyContext(key_type, - account_id, - key_name, - certificate_profile, - require_user_consent, - callback); + const PrepareKeyContext context = + PrepareKeyContext(key_type, account_id, key_name, certificate_profile, + require_user_consent, key_name_for_spkac, callback); cryptohome_client_->TpmAttestationIsPrepared( base::BindOnce(&EPKPChallengeKeyBase::IsAttestationPreparedCallback, base::Unretained(this), context)); @@ -224,6 +230,18 @@ void EPKPChallengeKeyBase::IsAttestationPreparedCallback( base::Unretained(this), context)); return; } + + if (!context.key_name_for_spkac.empty()) { + // Generate a new key and have it signed by PCA. + attestation_flow_->GetCertificate( + context.certificate_profile, context.account_id, + std::string(), // Not used. + true, // Force a new key to be generated. + context.key_name_for_spkac, + base::Bind(&EPKPChallengeKeyBase::GetCertificateCallback, + base::Unretained(this), context.callback)); + return; + } // Attestation is available, see if the key we need already exists. cryptohome_client_->TpmAttestationDoesKeyExist( context.key_type, @@ -295,6 +313,7 @@ void EPKPChallengeKeyBase::AskForUserConsentCallback( context.certificate_profile, context.account_id, std::string(), // Not used. true, // Force a new key to be generated. + std::string(), // Leave key name empty to generate a default name. base::Bind(&EPKPChallengeKeyBase::GetCertificateCallback, base::Unretained(this), context.callback)); } @@ -337,11 +356,10 @@ EPKPChallengeMachineKey::EPKPChallengeMachineKey( EPKPChallengeMachineKey::~EPKPChallengeMachineKey() { } -void EPKPChallengeMachineKey::Run( - scoped_refptr<UIThreadExtensionFunction> caller, - const ChallengeKeyCallback& callback, - const std::string& challenge, - bool register_key) { +void EPKPChallengeMachineKey::Run(scoped_refptr<ExtensionFunction> caller, + const ChallengeKeyCallback& callback, + const std::string& challenge, + bool register_key) { callback_ = callback; profile_ = ChromeExtensionFunctionDetails(caller.get()).GetProfile(); extension_ = scoped_refptr<const Extension>(caller->extension()); @@ -372,7 +390,7 @@ void EPKPChallengeMachineKey::Run( } void EPKPChallengeMachineKey::DecodeAndRun( - scoped_refptr<UIThreadExtensionFunction> caller, + scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key) { @@ -393,18 +411,31 @@ void EPKPChallengeMachineKey::GetDeviceAttestationEnabledCallback( return; } + // The EMK cannot be registered as that would relinquish it and the DMServer + // relies on it to remain stable. If register_key = true, generate a new + // machine key to side-load into the system-wide token. This key will be + // used for SignedPublicKeyAndChallenge but the challenge response will still + // be singed using the stable EMK. + std::string key_name_for_spkac; + if (register_key) { + key_name_for_spkac = kEnterpriseMachineKeyForSpkacPrefix + extension_->id(); + } PrepareKey(chromeos::attestation::KEY_DEVICE, EmptyAccountId(), // Not used. chromeos::attestation::kEnterpriseMachineKey, chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, false, // user consent is not required. + key_name_for_spkac, base::Bind(&EPKPChallengeMachineKey::PrepareKeyCallback, - base::Unretained(this), challenge, register_key)); + base::Unretained(this), challenge, register_key, + key_name_for_spkac)); } -void EPKPChallengeMachineKey::PrepareKeyCallback(const std::string& challenge, - bool register_key, - PrepareKeyResult result) { +void EPKPChallengeMachineKey::PrepareKeyCallback( + const std::string& challenge, + bool register_key, + const std::string& key_name_for_spkac, + PrepareKeyResult result) { if (result != PREPARE_KEY_OK) { callback_.Run(false, base::StringPrintf(kGetCertificateFailedError, result)); @@ -419,7 +450,7 @@ void EPKPChallengeMachineKey::PrepareKeyCallback(const std::string& challenge, GetDeviceId(), register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY : chromeos::attestation::CHALLENGE_OPTION_NONE, - challenge, + challenge, key_name_for_spkac, base::Bind(&EPKPChallengeMachineKey::SignChallengeCallback, base::Unretained(this), register_key)); } @@ -433,10 +464,12 @@ void EPKPChallengeMachineKey::SignChallengeCallback( return; } if (register_key) { + std::string key_name_for_spkac = + kEnterpriseMachineKeyForSpkacPrefix + extension_->id(); async_caller_->TpmAttestationRegisterKey( chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), // Not used. - chromeos::attestation::kEnterpriseMachineKey, + key_name_for_spkac, base::Bind(&EPKPChallengeMachineKey::RegisterKeyCallback, base::Unretained(this), response)); } else { @@ -489,7 +522,7 @@ void EPKPChallengeUserKey::RegisterProfilePrefs( registry->RegisterListPref(prefs::kAttestationExtensionWhitelist); } -void EPKPChallengeUserKey::Run(scoped_refptr<UIThreadExtensionFunction> caller, +void EPKPChallengeUserKey::Run(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& challenge, bool register_key) { @@ -535,11 +568,10 @@ void EPKPChallengeUserKey::Run(scoped_refptr<UIThreadExtensionFunction> caller, } } -void EPKPChallengeUserKey::DecodeAndRun( - scoped_refptr<UIThreadExtensionFunction> caller, - const ChallengeKeyCallback& callback, - const std::string& encoded_challenge, - bool register_key) { +void EPKPChallengeUserKey::DecodeAndRun(scoped_refptr<ExtensionFunction> caller, + const ChallengeKeyCallback& callback, + const std::string& encoded_challenge, + bool register_key) { std::string challenge; if (!base::Base64Decode(encoded_challenge, &challenge)) { callback.Run(false, kChallengeBadBase64Error); @@ -561,7 +593,7 @@ void EPKPChallengeUserKey::GetDeviceAttestationEnabledCallback( PrepareKey(chromeos::attestation::KEY_USER, GetAccountId(), chromeos::attestation::kEnterpriseUserKey, chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, - require_user_consent, + require_user_consent, std::string() /* key_name_for_spkac */, base::Bind(&EPKPChallengeUserKey::PrepareKeyCallback, base::Unretained(this), challenge, register_key)); } @@ -582,7 +614,7 @@ void EPKPChallengeUserKey::PrepareKeyCallback(const std::string& challenge, chromeos::attestation::kEnterpriseUserKey, GetUserEmail(), GetDeviceId(), register_key ? chromeos::attestation::CHALLENGE_INCLUDE_SIGNED_PUBLIC_KEY : chromeos::attestation::CHALLENGE_OPTION_NONE, - challenge, + challenge, std::string() /* key_name_for_spkac */, base::Bind(&EPKPChallengeUserKey::SignChallengeCallback, base::Unretained(this), register_key)); } @@ -645,11 +677,11 @@ EnterprisePlatformKeysPrivateChallengeMachineKeyFunction::Run() { this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeMachineKey::DecodeAndRun, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, params->challenge, false); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = base::Bind(&EPKPChallengeMachineKey::DecodeAndRun, + base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), + callback, params->challenge, false); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } @@ -688,11 +720,11 @@ EnterprisePlatformKeysPrivateChallengeUserKeyFunction::Run() { this); // base::Unretained is safe on impl_ since its life-cycle matches |this| and // |callback| holds a reference to |this|. - base::Closure task = base::Bind( - &EPKPChallengeUserKey::DecodeAndRun, base::Unretained(impl_), - scoped_refptr<UIThreadExtensionFunction>(AsUIThreadExtensionFunction()), - callback, params->challenge, params->register_key); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, task); + base::Closure task = + base::Bind(&EPKPChallengeUserKey::DecodeAndRun, base::Unretained(impl_), + scoped_refptr<ExtensionFunction>(this), callback, + params->challenge, params->register_key); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, task); return RespondLater(); } diff --git a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h index 66cb475b59f..e8e9fa09d43 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h +++ b/chromium/chrome/browser/extensions/api/enterprise_platform_keys_private/enterprise_platform_keys_private_api.h @@ -100,16 +100,18 @@ class EPKPChallengeKeyBase { // Returns the enterprise virtual device ID. std::string GetDeviceId() const; - // Prepares the key for signing. It will first check if the key exists. If - // the key does not exist, it will call AttestationFlow::GetCertificate() to - // get a new one. If require_user_consent is true, it will explicitly ask for - // user consent before calling GetCertificate(). + // Prepares the key for signing. It will first check if a new key should be + // generated, i.e. |key_name_for_spkac| is not empty or the key doesn't + // exist and, if necessary, call AttestationFlow::GetCertificate() to get a + // new one. If require_user_consent is true, it will explicitly ask for user + // consent before calling GetCertificate(). void PrepareKey( chromeos::attestation::AttestationKeyType key_type, const AccountId& account_id, const std::string& key_name, chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback); chromeos::CryptohomeClient* cryptohome_client_; @@ -130,6 +132,7 @@ class EPKPChallengeKeyBase { chromeos::attestation::AttestationCertificateProfile certificate_profile, bool require_user_consent, + const std::string& key_name_for_spkac, const base::Callback<void(PrepareKeyResult)>& callback); PrepareKeyContext(const PrepareKeyContext& other); ~PrepareKeyContext(); @@ -139,6 +142,7 @@ class EPKPChallengeKeyBase { const std::string key_name; chromeos::attestation::AttestationCertificateProfile certificate_profile; bool require_user_consent; + std::string key_name_for_spkac; const base::Callback<void(PrepareKeyResult)> callback; }; @@ -176,13 +180,13 @@ class EPKPChallengeMachineKey : public EPKPChallengeKeyBase { // Asynchronously run the flow to challenge a machine key in the |caller| // context. - void Run(scoped_refptr<UIThreadExtensionFunction> caller, + void Run(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key); // Like |Run| but expects a Base64 |encoded_challenge|. - void DecodeAndRun(scoped_refptr<UIThreadExtensionFunction> caller, + void DecodeAndRun(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key); @@ -195,6 +199,7 @@ class EPKPChallengeMachineKey : public EPKPChallengeKeyBase { bool enabled); void PrepareKeyCallback(const std::string& challenge, bool register_key, + const std::string& key_name_for_spkac, PrepareKeyResult result); void SignChallengeCallback(bool register_key, bool success, @@ -223,13 +228,13 @@ class EPKPChallengeUserKey : public EPKPChallengeKeyBase { // Asynchronously run the flow to challenge a user key in the |caller| // context. - void Run(scoped_refptr<UIThreadExtensionFunction> caller, + void Run(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& challenge, bool register_key); // Like |Run| but expects a Base64 |encoded_challenge|. - void DecodeAndRun(scoped_refptr<UIThreadExtensionFunction> caller, + void DecodeAndRun(scoped_refptr<ExtensionFunction> caller, const ChallengeKeyCallback& callback, const std::string& encoded_challenge, bool register_key); @@ -255,7 +260,7 @@ class EPKPChallengeUserKey : public EPKPChallengeKeyBase { }; class EnterprisePlatformKeysPrivateChallengeMachineKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysPrivateChallengeMachineKeyFunction(); explicit EnterprisePlatformKeysPrivateChallengeMachineKeyFunction( @@ -279,7 +284,7 @@ class EnterprisePlatformKeysPrivateChallengeMachineKeyFunction }; class EnterprisePlatformKeysPrivateChallengeUserKeyFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: EnterprisePlatformKeysPrivateChallengeUserKeyFunction(); explicit EnterprisePlatformKeysPrivateChallengeUserKeyFunction( 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 3dc0c29bc66..6230610cb4a 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 @@ -88,6 +88,7 @@ void SignChallengeCallbackTrue( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, true, "response")); @@ -101,6 +102,7 @@ void SignChallengeCallbackFalse( const std::string& device_id, chromeos::attestation::AttestationChallengeOptions options, const std::string& challenge, + const std::string& key_name_for_spkac, const cryptohome::AsyncMethodCaller::DataCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, false, "")); @@ -111,6 +113,7 @@ void GetCertificateCallbackTrue( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -124,6 +127,7 @@ void GetCertificateCallbackUnspecifiedFailure( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -138,6 +142,7 @@ void GetCertificateCallbackBadRequestFailure( const AccountId& account_id, const std::string& request_origin, bool force_new_key, + const std::string& key_name, const chromeos::attestation::AttestationFlow::CertificateCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( @@ -164,9 +169,9 @@ class EPKPChallengeKeyTestBase : public BrowserWithTestWindowTest { ON_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .WillByDefault(Invoke(RegisterKeyCallbackTrue)); ON_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillByDefault(Invoke(SignChallengeCallbackTrue)); - ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + ON_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillByDefault(Invoke(GetCertificateCallbackTrue)); stub_install_attributes_.SetCloudManaged("google.com", "device_id"); @@ -301,7 +306,7 @@ TEST_F(EPKPChallengeMachineKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKPChallengeMachineKeyTest, GetCertificateFailed) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackUnspecifiedFailure)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -310,7 +315,7 @@ TEST_F(EPKPChallengeMachineKeyTest, GetCertificateFailed) { TEST_F(EPKPChallengeMachineKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -321,7 +326,7 @@ TEST_F(EPKPChallengeMachineKeyTest, KeyExists) { cryptohome_client_.SetTpmAttestationDeviceCertificate("attest-ent-machine", std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), @@ -366,14 +371,14 @@ TEST_P(EPKPChallengeMachineKeyAllProfilesTest, Success) { EXPECT_CALL(mock_attestation_flow_, GetCertificate( chromeos::attestation::PROFILE_ENTERPRISE_MACHINE_CERTIFICATE, - _, _, _, _)) + _, _, _, _, _)) .Times(1); // SignEnterpriseChallenge must be called exactly once. - EXPECT_CALL( - mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge( - chromeos::attestation::KEY_DEVICE, cryptohome::Identification(), - "attest-ent-machine", "google.com", "device_id", _, "challenge", _)) + EXPECT_CALL(mock_async_method_caller_, + TpmAttestationSignEnterpriseChallenge( + chromeos::attestation::KEY_DEVICE, + cryptohome::Identification(), "attest-ent-machine", + "google.com", "device_id", _, "challenge", _, _)) .Times(1); std::unique_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( @@ -464,7 +469,7 @@ TEST_F(EPKPChallengeUserKeyTest, DoesKeyExistDbusFailed) { } TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithUnspecifiedFailure) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackUnspecifiedFailure)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -472,7 +477,7 @@ TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithUnspecifiedFailure) { } TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithBadRequestFailure) { - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .WillRepeatedly(Invoke(GetCertificateCallbackBadRequestFailure)); EXPECT_EQ(GetCertificateError(kGetCertificateFailed), @@ -481,7 +486,7 @@ TEST_F(EPKPChallengeUserKeyTest, GetCertificateFailedWithBadRequestFailure) { TEST_F(EPKPChallengeUserKeyTest, SignChallengeFailed) { EXPECT_CALL(mock_async_method_caller_, - TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _)) + TpmAttestationSignEnterpriseChallenge(_, _, _, _, _, _, _, _, _)) .WillRepeatedly(Invoke(SignChallengeCallbackFalse)); EXPECT_EQ(EPKPChallengeKeyBase::kSignChallengeFailedError, @@ -502,7 +507,7 @@ TEST_F(EPKPChallengeUserKeyTest, KeyExists) { AccountId::FromUserEmail(kUserEmail)), "attest-ent-user", std::string()); // GetCertificate must not be called if the key exists. - EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) + EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _, _)) .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), @@ -527,10 +532,10 @@ TEST_F(EPKPChallengeUserKeyTest, PersonalDevice) { TEST_F(EPKPChallengeUserKeyTest, Success) { // GetCertificate must be called exactly once. - EXPECT_CALL(mock_attestation_flow_, - GetCertificate( - chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, - _, _, _, _)) + EXPECT_CALL( + mock_attestation_flow_, + GetCertificate(chromeos::attestation::PROFILE_ENTERPRISE_USER_CERTIFICATE, + _, _, _, _, _)) .Times(1); const AccountId account_id = AccountId::FromUserEmail(kUserEmail); // SignEnterpriseChallenge must be called exactly once. @@ -539,7 +544,7 @@ TEST_F(EPKPChallengeUserKeyTest, Success) { chromeos::attestation::KEY_USER, cryptohome::Identification(account_id), "attest-ent-user", cryptohome::Identification(account_id).id(), "device_id", _, - "challenge", _)) + "challenge", _, _)) .Times(1); // RegisterKey must be called exactly once. EXPECT_CALL(mock_async_method_caller_, diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc index 85b835c492a..5284f7e8586 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper.cc @@ -113,8 +113,10 @@ void AppendAdditionalBrowserInformation(em::ChromeDesktopReportRequest* request, // the future. request->mutable_browser_report() ->mutable_chrome_user_profile_reports(0) - ->set_policy_data( - policy::GetAllPolicyValuesAsJSON(profile, true, false, false)); + ->set_policy_data(policy::DictionaryPolicyConversions() + .WithBrowserContext(profile) + .EnablePrettyPrint(false) + .ToJSON()); int64_t timestamp = GetMachineLevelUserCloudPolicyFetchTimestamp(); if (timestamp > 0) { diff --git a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc index 9be986f7cfa..cfa80831e07 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_reporting_private/chrome_desktop_report_request_helper_unittest.cc @@ -15,7 +15,7 @@ #include "components/policy/core/common/cloud/cloud_policy_util.h" #include "components/policy/proto/device_management_backend.pb.h" #include "components/prefs/pref_service.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace em = enterprise_management; @@ -24,7 +24,7 @@ namespace extensions { class ChromeDesktopReportRequestGeneratorTest : public ::testing::Test { protected: - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; 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 c6ebd8fa877..ec772107862 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 @@ -27,7 +27,7 @@ extern const char kDeviceIdNotFound[]; } // namespace enterprise_reporting class EnterpriseReportingPrivateUploadChromeDesktopReportFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION( "enterprise.reportingPrivate.uploadChromeDesktopReport", @@ -65,8 +65,7 @@ class EnterpriseReportingPrivateUploadChromeDesktopReportFunction EnterpriseReportingPrivateUploadChromeDesktopReportFunction); }; -class EnterpriseReportingPrivateGetDeviceIdFunction - : public UIThreadExtensionFunction { +class EnterpriseReportingPrivateGetDeviceIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("enterprise.reportingPrivate.getDeviceId", ENTERPRISEREPORTINGPRIVATE_GETDEVICEID) 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 bca47a1b158..344b3238590 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 @@ -34,7 +34,7 @@ class EnterpriseReportingPrivateUploadChromeDesktopReportTest public: EnterpriseReportingPrivateUploadChromeDesktopReportTest() {} - UIThreadExtensionFunction* CreateChromeDesktopReportingFunction( + ExtensionFunction* CreateChromeDesktopReportingFunction( const std::string& dm_token) { EnterpriseReportingPrivateUploadChromeDesktopReportFunction* function = EnterpriseReportingPrivateUploadChromeDesktopReportFunction:: @@ -85,7 +85,7 @@ TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, } TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, UploadFailed) { - UIThreadExtensionFunction* function = + ExtensionFunction* function = CreateChromeDesktopReportingFunction(kFakeDMToken); EXPECT_CALL(*client_, SetupRegistration(kFakeDMToken, kFakeClientId, _)) .Times(1); @@ -99,7 +99,7 @@ TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, UploadFailed) { TEST_F(EnterpriseReportingPrivateUploadChromeDesktopReportTest, UploadSucceeded) { - UIThreadExtensionFunction* function = + ExtensionFunction* function = CreateChromeDesktopReportingFunction(kFakeDMToken); EXPECT_CALL(*client_, SetupRegistration(kFakeDMToken, kFakeClientId, _)) .Times(1); 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 5af703b6ed9..e8a2d2d10f7 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 @@ -15,6 +15,8 @@ #include "build/build_config.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/api/extension_action/extension_action_api.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_action.h" #include "chrome/browser/extensions/extension_action_icon_factory.h" #include "chrome/browser/extensions/extension_action_manager.h" @@ -209,7 +211,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, Basic) { // Test that we received the changes. ExtensionAction* action = GetBrowserAction(*extension); ASSERT_EQ("Modified", action->GetTitle(ExtensionAction::kDefaultTabId)); - ASSERT_EQ("badge", action->GetBadgeText(ExtensionAction::kDefaultTabId)); + ASSERT_EQ("badge", + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); ASSERT_EQ(SkColorSetARGB(255, 255, 255, 255), action->GetBadgeBackgroundColor(ExtensionAction::kDefaultTabId)); @@ -701,7 +704,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, DISABLED_CloseBackgroundPage) { extensions::ProcessManager::Get(browser()->profile()); ASSERT_TRUE(manager->GetBackgroundHostForExtension(extension->id())); ExtensionAction* action = GetBrowserAction(*extension); - ASSERT_EQ("", action->GetBadgeText(ExtensionAction::kDefaultTabId)); + ASSERT_EQ("", + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); content::WindowedNotificationObserver host_destroyed_observer( extensions::NOTIFICATION_EXTENSION_HOST_DESTROYED, @@ -715,7 +719,8 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, DISABLED_CloseBackgroundPage) { // and the badge text has been set. host_destroyed_observer.Wait(); ASSERT_FALSE(manager->GetBackgroundHostForExtension(extension->id())); - ASSERT_EQ("X", action->GetBadgeText(ExtensionAction::kDefaultTabId)); + ASSERT_EQ("X", + action->GetExplicitlySetBadgeText(ExtensionAction::kDefaultTabId)); } IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BadgeBackgroundColor) { @@ -878,14 +883,28 @@ IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionPopupWithIframe) { IN_PROC_BROWSER_TEST_F(BrowserActionApiTest, BrowserActionWithRectangularIcon) { ExtensionTestMessageListener ready_listener("ready", true); - ASSERT_TRUE(LoadExtension( - test_data_dir_.AppendASCII("browser_action").AppendASCII("rect_icon"))); + + const Extension* extension = LoadExtension( + test_data_dir_.AppendASCII("browser_action").AppendASCII("rect_icon")); + ASSERT_TRUE(extension); EXPECT_TRUE(ready_listener.WaitUntilSatisfied()); + + // Wait for the default icon to load before accessing the underlying + // gfx::Image. + TestIconImageObserver::WaitForExtensionActionIcon(extension, profile()); + gfx::Image first_icon = GetBrowserActionsBar()->GetIcon(0); + ASSERT_FALSE(first_icon.IsEmpty()); + + TestExtensionActionAPIObserver observer(profile(), extension->id()); ResultCatcher catcher; ready_listener.Reply(std::string()); EXPECT_TRUE(catcher.GetNextResult()); + // Wait for extension action to be updated. + observer.Wait(); + gfx::Image next_icon = GetBrowserActionsBar()->GetIcon(0); + ASSERT_FALSE(next_icon.IsEmpty()); EXPECT_FALSE(gfx::test::AreImagesEqual(first_icon, next_icon)); } diff --git a/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc b/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc index 2c4893d0dc1..5027f9ac3e0 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/browser_action_browsertest.cc @@ -94,7 +94,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, BrowserActionDefaultPersistence) { // If the extension hasn't already set the badge text, then we should wait for // it to do so. - if (extension_action->GetBadgeText(0) != "Hello") { + if (extension_action->GetExplicitlySetBadgeText(0) != "Hello") { ExtensionTestMessageListener listener("Badge Text Set", false /* won't send custom reply */); ASSERT_TRUE(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 7ad5b39767f..8fd11ee84dd 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 @@ -10,7 +10,6 @@ #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" @@ -29,7 +28,6 @@ #include "content/public/browser/notification_types.h" #include "content/public/common/page_zoom.h" #include "extensions/browser/extension_registry.h" -#include "extensions/browser/extension_system.h" #include "extensions/browser/notification_types.h" #include "extensions/common/extension.h" #include "extensions/common/extension_set.h" @@ -341,9 +339,10 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, return; OpenPopupViaAPI(false); - ExtensionService* service = extensions::ExtensionSystem::Get( - browser()->profile())->extension_service(); - ASSERT_FALSE(service->GetExtensionById(last_loaded_extension_id(), false) + ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ASSERT_FALSE(registry + ->GetExtensionById(last_loaded_extension_id(), + ExtensionRegistry::ENABLED) ->permissions_data() ->HasAPIPermissionForTab( SessionTabHelper::IdForTab( 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 ef0c3b6b928..28bdacc39e9 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 @@ -31,6 +31,7 @@ #include "chrome/browser/ui/toolbar/toolbar_actions_bar.h" #include "chrome/common/extensions/api/extension_action/action_info.h" #include "content/public/browser/notification_service.h" +#include "extensions/browser/api/declarative_net_request/constants.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" @@ -48,9 +49,6 @@ namespace extensions { namespace { -// Whether the browser action is visible in the toolbar. -const char kBrowserActionVisible[] = "browser_action_visible"; - // Errors. const char kNoExtensionActionError[] = "This extension has no action specified."; @@ -113,29 +111,6 @@ void ExtensionActionAPI::RemoveObserver(Observer* observer) { observers_.RemoveObserver(observer); } -bool ExtensionActionAPI::GetBrowserActionVisibility( - const std::string& extension_id) { - bool visible = false; - ExtensionPrefs* prefs = GetExtensionPrefs(); - if (!prefs || !prefs->ReadPrefAsBoolean(extension_id, - kBrowserActionVisible, - &visible)) { - return true; - } - return visible; -} - -void ExtensionActionAPI::SetBrowserActionVisibility( - const std::string& extension_id, - bool visible) { - if (GetBrowserActionVisibility(extension_id) == visible) - return; - - GetExtensionPrefs()->UpdateExtensionPref( - extension_id, kBrowserActionVisible, - std::make_unique<base::Value>(visible)); -} - bool ExtensionActionAPI::ShowExtensionActionPopup( const Extension* extension, Browser* browser, @@ -191,8 +166,16 @@ void ExtensionActionAPI::DispatchExtensionActionClicked( if (event_name) { std::unique_ptr<base::ListValue> args(new base::ListValue()); + // The action APIs (browserAction, pageAction, action) are only available + // to blessed extension contexts. As such, we deterministically know that + // the right context type here is blessed. + constexpr Feature::Context context_type = + Feature::BLESSED_EXTENSION_CONTEXT; + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, context_type, + web_contents); args->Append(ExtensionTabUtil::CreateTabObject( - web_contents, ExtensionTabUtil::kScrubTab, extension) + web_contents, scrub_tab_behavior, extension) ->ToValue()); DispatchEventToExtension(web_contents->GetBrowserContext(), @@ -283,8 +266,7 @@ ExtensionFunction::ResponseAction ExtensionActionFunction::Run() { // Find the WebContents that contains this tab id if one is required. if (tab_id_ != ExtensionAction::kDefaultTabId) { ExtensionTabUtil::GetTabById(tab_id_, browser_context(), - include_incognito_information(), nullptr, - nullptr, &contents_, nullptr); + include_incognito_information(), &contents_); if (!contents_) return RespondNow(Error(kNoTabError, base::NumberToString(tab_id_))); } else { @@ -494,8 +476,19 @@ ExtensionActionGetPopupFunction::RunExtensionAction() { ExtensionFunction::ResponseAction ExtensionActionGetBadgeTextFunction::RunExtensionAction() { - return RespondNow(OneArgument( - std::make_unique<base::Value>(extension_action_->GetBadgeText(tab_id_)))); + // Return a placeholder value if the extension has called + // setActionCountAsBadgeText(true) and the badge count shown for this tab is + // the number of actions matched. + std::string badge_text = + extension_action_->UseDNRActionCountAsBadgeText(tab_id_) + ? declarative_net_request::kActionCountPlaceholderBadgeText + : extension_action_->GetExplicitlySetBadgeText(tab_id_); + + // TODO(crbug.com/990224): Document this behavior once + // chrome.declarativeNetRequest.setActionCountAsBadgeText is promoted to beta + // from trunk. + return RespondNow( + OneArgument(std::make_unique<base::Value>(std::move(badge_text)))); } ExtensionFunction::ResponseAction 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 f4d9ea2b9dd..6ae7ffbe33a 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 @@ -67,10 +67,6 @@ class ExtensionActionAPI : public BrowserContextKeyedAPI { void AddObserver(Observer* observer); void RemoveObserver(Observer* observer); - bool GetBrowserActionVisibility(const std::string& extension_id); - void SetBrowserActionVisibility(const std::string& extension_id, - bool visible); - // Opens the popup for the given |extension| in the given |browser|'s window. // If |grant_active_tab_permissions| is true, this grants the extension // activeTab (so this should only be done if this is through a direct user @@ -130,7 +126,7 @@ class ExtensionActionAPI : public BrowserContextKeyedAPI { // tabIds while browserAction's are optional, they have different internal // browser notification requirements, and not all functions are defined for all // APIs). -class ExtensionActionFunction : public UIThreadExtensionFunction { +class ExtensionActionFunction : public ExtensionFunction { public: static bool ParseCSSColorString(const std::string& color_string, SkColor* result); @@ -446,7 +442,7 @@ class BrowserActionDisableFunction : public ExtensionActionHideFunction { ~BrowserActionDisableFunction() override {} }; -class BrowserActionOpenPopupFunction : public UIThreadExtensionFunction, +class BrowserActionOpenPopupFunction : public ExtensionFunction, public content::NotificationObserver { public: DECLARE_EXTENSION_FUNCTION("browserAction.openPopup", 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 c90241d63ad..760b0b8d622 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 @@ -13,6 +13,7 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.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_action.h" #include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_apitest.h" @@ -266,39 +267,6 @@ class MultiActionAPITest return action_manager->GetExtensionAction(extension); } - // Waits for the given |icon| to finish it's first load. - // TODO(devlin): It's unfortunate we need this here. Ideally, either this - // would be less convoluted, or would even be taken care of by the extension - // loading methods. - void WaitForIconLoaded(IconImage* icon) { - class IconImageWaiter : public IconImage::Observer { - public: - IconImageWaiter() : observer_(this) {} - ~IconImageWaiter() override = default; - - void Wait(IconImage* icon) { - if (!icon->did_complete_initial_load()) { - observer_.Add(icon); - run_loop_.Run(); - } - } - - private: - // IconImage::Observer: - void OnExtensionIconImageChanged(IconImage* icon) override { - DCHECK(icon->did_complete_initial_load()); - run_loop_.Quit(); - } - - base::RunLoop run_loop_; - ScopedObserver<IconImage, IconImage::Observer> observer_; - - DISALLOW_COPY_AND_ASSIGN(IconImageWaiter); - }; - - IconImageWaiter().Wait(icon); - } - private: std::unique_ptr<ScopedCurrentChannel> current_channel_; @@ -641,7 +609,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPICanvasTest, DynamicSetIcon) { ASSERT_TRUE(action->default_icon()); // Wait for the default icon to finish loading; otherwise it may be empty // when we check it. - WaitForIconLoaded(action->default_icon_image()); + TestIconImageObserver::WaitForIcon(action->default_icon_image()); int tab_id = GetActiveTabId(); EXPECT_TRUE(ActionHasDefaultState(*action, tab_id)); @@ -889,7 +857,7 @@ IN_PROC_BROWSER_TEST_P(MultiActionAPITest, GettersAndSetters) { ValuePair custom_badge_text2{"custom badge2", "'custom badge2'"}; auto get_badge_text = [](ExtensionAction* action, int tab_id) { - return action->GetBadgeText(tab_id); + return action->GetExplicitlySetBadgeText(tab_id); }; ActionTestHelper badge_text_helper(kApiName, "setBadgeText", "getBadgeText", diff --git a/chromium/chrome/browser/extensions/api/extension_action/extension_action_prefs_unittest.cc b/chromium/chrome/browser/extensions/api/extension_action/extension_action_prefs_unittest.cc deleted file mode 100644 index 9eb67c61f19..00000000000 --- a/chromium/chrome/browser/extensions/api/extension_action/extension_action_prefs_unittest.cc +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <string> - -#include "base/logging.h" -#include "base/macros.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/stringprintf.h" -#include "chrome/browser/extensions/api/extension_action/extension_action_api.h" -#include "chrome/browser/extensions/extension_prefs_unittest.h" -#include "chrome/test/base/testing_profile.h" -#include "extensions/common/extension.h" - -namespace extensions { - -// Tests force hiding browser actions. -class ExtensionPrefsHidingBrowserActions : public ExtensionPrefsTest { - public: - ExtensionPrefsHidingBrowserActions() {} - ~ExtensionPrefsHidingBrowserActions() override {} - - void Initialize() override { - profile_.reset(new TestingProfile()); - - // Install 5 extensions. - for (int i = 0; i < 5; i++) { - std::string name = "test" + base::NumberToString(i); - extensions_.push_back(prefs_.AddExtension(name)); - } - - ExtensionActionAPI* action_api = ExtensionActionAPI::Get(profile_.get()); - action_api->set_prefs_for_testing(prefs()); - for (const scoped_refptr<const Extension>& extension : extensions_) - EXPECT_TRUE(action_api->GetBrowserActionVisibility(extension->id())); - - action_api->SetBrowserActionVisibility(extensions_[0]->id(), false); - action_api->SetBrowserActionVisibility(extensions_[1]->id(), true); - } - - void Verify() override { - ExtensionActionAPI* action_api = ExtensionActionAPI::Get(profile_.get()); - action_api->set_prefs_for_testing(prefs()); - // Make sure the one we hid is hidden. - EXPECT_FALSE(action_api->GetBrowserActionVisibility(extensions_[0]->id())); - - // Make sure the other id's are not hidden. - ExtensionList::const_iterator iter = extensions_.begin() + 1; - for (; iter != extensions_.end(); ++iter) { - SCOPED_TRACE(base::StringPrintf("Loop %d ", - static_cast<int>(iter - extensions_.begin()))); - EXPECT_TRUE(action_api->GetBrowserActionVisibility((*iter)->id())); - } - } - - private: - std::unique_ptr<TestingProfile> profile_; - ExtensionList extensions_; - - DISALLOW_COPY_AND_ASSIGN(ExtensionPrefsHidingBrowserActions); -}; - -TEST_F(ExtensionPrefsHidingBrowserActions, ForceHide) {} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc index 2083a406aa9..054f6a38116 100644 --- a/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc +++ b/chromium/chrome/browser/extensions/api/extension_action/test_extension_action_api_observer.cc @@ -13,6 +13,14 @@ TestExtensionActionAPIObserver::TestExtensionActionAPIObserver( scoped_observer_.Add(ExtensionActionAPI::Get(context)); } +TestExtensionActionAPIObserver::TestExtensionActionAPIObserver( + content::BrowserContext* context, + const ExtensionId& extension_id, + const std::set<content::WebContents*>& contents_to_observe) + : TestExtensionActionAPIObserver(context, extension_id) { + contents_to_observe_ = contents_to_observe; +} + TestExtensionActionAPIObserver::~TestExtensionActionAPIObserver() = default; void TestExtensionActionAPIObserver::Wait() { @@ -25,7 +33,10 @@ void TestExtensionActionAPIObserver::OnExtensionActionUpdated( content::BrowserContext* browser_context) { if (extension_action->extension_id() == extension_id_) { last_web_contents_ = web_contents; - run_loop_.QuitWhenIdle(); + contents_to_observe_.erase(web_contents); + + if (contents_to_observe_.empty()) + run_loop_.QuitWhenIdle(); } } 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 11b35f5b279..981da2f2b36 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 @@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_EXTENSION_ACTION_API_OBSERVER_H_ #define CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_EXTENSION_ACTION_API_OBSERVER_H_ +#include <set> + #include "base/macros.h" #include "base/run_loop.h" #include "base/scoped_observer.h" @@ -23,9 +25,15 @@ class TestExtensionActionAPIObserver : public ExtensionActionAPI::Observer { public: TestExtensionActionAPIObserver(content::BrowserContext* context, const ExtensionId& extension_id); + TestExtensionActionAPIObserver( + content::BrowserContext* context, + const ExtensionId& extension_id, + const std::set<content::WebContents*>& contents_to_observe); ~TestExtensionActionAPIObserver() override; - // Waits till the extension action is updated. + // Waits until the extension action is updated and the update is seen for all + // web contents in |contents_to_observe_| if |contents_to_observe_| is not + // empty. void Wait(); // Returns the web contents for which the extension action was updated. Must @@ -47,6 +55,9 @@ class TestExtensionActionAPIObserver : public ExtensionActionAPI::Observer { ScopedObserver<ExtensionActionAPI, ExtensionActionAPI::Observer> scoped_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); }; diff --git a/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.cc b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.cc new file mode 100644 index 00000000000..5544ebace55 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.cc @@ -0,0 +1,42 @@ +// Copyright 2019 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/extension_action/test_icon_image_observer.h" + +#include "chrome/browser/extensions/extension_action.h" +#include "chrome/browser/extensions/extension_action_manager.h" + +namespace extensions { + +TestIconImageObserver::TestIconImageObserver() : observer_(this) {} +TestIconImageObserver::~TestIconImageObserver() = default; + +void TestIconImageObserver::Wait(IconImage* icon) { + if (!icon->did_complete_initial_load()) { + observer_.Add(icon); + run_loop_.Run(); + } +} + +void TestIconImageObserver::OnExtensionIconImageChanged(IconImage* icon) { + DCHECK(icon->did_complete_initial_load()); + run_loop_.Quit(); +} + +void TestIconImageObserver::WaitForIcon(IconImage* icon) { + TestIconImageObserver().Wait(icon); +} +void TestIconImageObserver::WaitForExtensionActionIcon( + const Extension* extension, + content::BrowserContext* context) { + DCHECK(extension); + auto* action_manager = ExtensionActionManager::Get(context); + ExtensionAction* action = action_manager->GetExtensionAction(*extension); + + DCHECK(action); + DCHECK(action->default_icon_image()); + WaitForIcon(action->default_icon_image()); +} + +} // 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 new file mode 100644 index 00000000000..b8881d8a8a6 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/extension_action/test_icon_image_observer.h @@ -0,0 +1,41 @@ +// Copyright 2019 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_EXTENSION_ACTION_TEST_ICON_IMAGE_OBSERVER_H_ +#define CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_ICON_IMAGE_OBSERVER_H_ + +#include "base/macros.h" +#include "base/run_loop.h" +#include "base/scoped_observer.h" +#include "extensions/browser/extension_icon_image.h" + +namespace extensions { + +class Extension; + +// This class helps to observe action icons. As default action icons load +// asynchronously we need to wait for it to finish before using them. +class TestIconImageObserver : public IconImage::Observer { + public: + TestIconImageObserver(); + ~TestIconImageObserver() override; + + void Wait(IconImage* icon); + + static void WaitForIcon(IconImage* icon); + static void WaitForExtensionActionIcon(const Extension* extension, + content::BrowserContext* context); + + private: + // IconImage::Observer: + void OnExtensionIconImageChanged(IconImage* icon) override; + + base::RunLoop run_loop_; + ScopedObserver<IconImage, IconImage::Observer> observer_; + + DISALLOW_COPY_AND_ASSIGN(TestIconImageObserver); +}; +} // namespace extensions + +#endif // CHROME_BROWSER_EXTENSIONS_API_EXTENSION_ACTION_TEST_ICON_IMAGE_OBSERVER_H_ diff --git a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc index b440c80df8a..c5c066eb388 100644 --- a/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc +++ b/chromium/chrome/browser/extensions/api/file_system/chrome_file_system_delegate.cc @@ -106,7 +106,7 @@ bool GetVolumeListForExtension( // Callback called when consent is granted or denied. void OnConsentReceived( content::BrowserContext* browser_context, - scoped_refptr<UIThreadExtensionFunction> requester, + scoped_refptr<ExtensionFunction> requester, const FileSystemDelegate::FileSystemCallback& success_callback, const FileSystemDelegate::ErrorCallback& error_callback, const std::string& extension_id, @@ -252,7 +252,7 @@ base::FilePath ChromeFileSystemDelegate::GetDefaultDirectory() { } bool ChromeFileSystemDelegate::ShowSelectFileDialog( - scoped_refptr<UIThreadExtensionFunction> extension_function, + scoped_refptr<ExtensionFunction> extension_function, ui::SelectFileDialog::Type type, const base::FilePath& default_path, const ui::SelectFileDialog::FileTypeInfo* file_types, @@ -282,7 +282,7 @@ bool ChromeFileSystemDelegate::ShowSelectFileDialog( return false; } - // The file picker will hold a reference to the UIThreadExtensionFunction + // The file picker will hold a reference to the ExtensionFunction // instance, preventing its destruction (and subsequent sending of the // function response) until the user has selected a file or cancelled the // picker. At that point, the picker will delete itself, which will also free @@ -330,7 +330,7 @@ ChromeFileSystemDelegate::GetGrantVolumesMode( void ChromeFileSystemDelegate::RequestFileSystem( content::BrowserContext* browser_context, - scoped_refptr<UIThreadExtensionFunction> requester, + scoped_refptr<ExtensionFunction> requester, const Extension& extension, std::string volume_id, bool writable, 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 9dd8784bceb..a1276399fa3 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 @@ -32,7 +32,7 @@ class ChromeFileSystemDelegate : public FileSystemDelegate { // FileSystemDelegate: base::FilePath GetDefaultDirectory() override; bool ShowSelectFileDialog( - scoped_refptr<UIThreadExtensionFunction> extension_function, + scoped_refptr<ExtensionFunction> extension_function, ui::SelectFileDialog::Type type, const base::FilePath& default_path, const ui::SelectFileDialog::FileTypeInfo* file_types, @@ -50,7 +50,7 @@ class ChromeFileSystemDelegate : public FileSystemDelegate { content::RenderFrameHost* render_frame_host, const Extension& extension) override; void RequestFileSystem(content::BrowserContext* browser_context, - scoped_refptr<UIThreadExtensionFunction> requester, + scoped_refptr<ExtensionFunction> requester, const Extension& extension, std::string volume_id, bool writable, 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 2ed1d872059..33c14d9d9f5 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 @@ -19,7 +19,7 @@ #include "components/prefs/testing_pref_service.h" #include "components/user_manager/scoped_user_manager.h" #include "components/user_manager/user.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/file_system/file_system_delegate.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" @@ -137,7 +137,7 @@ class FileSystemApiConsentProviderTest : public testing::Test { chromeos::FakeChromeUserManager* user_manager_; // Owned by the scope enabler. std::unique_ptr<user_manager::ScopedUserManager> scoped_user_manager_enabler_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir temp_dir_; std::unique_ptr<Volume> download_volume_; }; 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 880218aba60..6b206d44778 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 @@ -101,7 +101,7 @@ class FontSettingsAPI : public BrowserContextKeyedAPI { }; // fontSettings.clearFont API function. -class FontSettingsClearFontFunction : public UIThreadExtensionFunction { +class FontSettingsClearFontFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.clearFont", FONTSETTINGS_CLEARFONT) @@ -115,7 +115,7 @@ class FontSettingsClearFontFunction : public UIThreadExtensionFunction { }; // fontSettings.getFont API function. -class FontSettingsGetFontFunction : public UIThreadExtensionFunction { +class FontSettingsGetFontFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.getFont", FONTSETTINGS_GETFONT) @@ -127,7 +127,7 @@ class FontSettingsGetFontFunction : public UIThreadExtensionFunction { }; // fontSettings.setFont API function. -class FontSettingsSetFontFunction : public UIThreadExtensionFunction { +class FontSettingsSetFontFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("fontSettings.setFont", FONTSETTINGS_SETFONT) @@ -156,7 +156,7 @@ class FontSettingsGetFontListFunction : public ChromeAsyncExtensionFunction { }; // Base class for extension API functions that clear a browser font pref. -class ClearFontPrefExtensionFunction : public UIThreadExtensionFunction { +class ClearFontPrefExtensionFunction : public ExtensionFunction { protected: ~ClearFontPrefExtensionFunction() override {} @@ -169,7 +169,7 @@ class ClearFontPrefExtensionFunction : public UIThreadExtensionFunction { }; // Base class for extension API functions that get a browser font pref. -class GetFontPrefExtensionFunction : public UIThreadExtensionFunction { +class GetFontPrefExtensionFunction : public ExtensionFunction { protected: ~GetFontPrefExtensionFunction() override {} @@ -186,7 +186,7 @@ class GetFontPrefExtensionFunction : public UIThreadExtensionFunction { }; // Base class for extension API functions that set a browser font pref. -class SetFontPrefExtensionFunction : public UIThreadExtensionFunction { +class SetFontPrefExtensionFunction : public ExtensionFunction { protected: ~SetFontPrefExtensionFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/gcm/gcm_api.h b/chromium/chrome/browser/extensions/api/gcm/gcm_api.h index 40bbd1b1147..8e538f667a5 100644 --- a/chromium/chrome/browser/extensions/api/gcm/gcm_api.h +++ b/chromium/chrome/browser/extensions/api/gcm/gcm_api.h @@ -17,7 +17,7 @@ class Profile; namespace extensions { -class GcmApiFunction : public UIThreadExtensionFunction { +class GcmApiFunction : public ExtensionFunction { public: GcmApiFunction() {} @@ -42,7 +42,7 @@ class GcmRegisterFunction : public GcmApiFunction { protected: ~GcmRegisterFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: @@ -59,7 +59,7 @@ class GcmUnregisterFunction : public GcmApiFunction { protected: ~GcmUnregisterFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: @@ -75,7 +75,7 @@ class GcmSendFunction : public GcmApiFunction { protected: ~GcmSendFunction() override; - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() final; private: diff --git a/chromium/chrome/browser/extensions/api/history/history_api.h b/chromium/chrome/browser/extensions/api/history/history_api.h index 9a0433dbf79..5349fca6a52 100644 --- a/chromium/chrome/browser/extensions/api/history/history_api.h +++ b/chromium/chrome/browser/extensions/api/history/history_api.h @@ -93,7 +93,7 @@ template <> void BrowserContextKeyedAPIFactory<HistoryAPI>::DeclareFactoryDependencies(); // Base class for history function APIs. -class HistoryFunction : public UIThreadExtensionFunction { +class HistoryFunction : public ExtensionFunction { protected: ~HistoryFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/i18n/i18n_api.h b/chromium/chrome/browser/extensions/api/i18n/i18n_api.h index 5576a36339f..88ed7094431 100644 --- a/chromium/chrome/browser/extensions/api/i18n/i18n_api.h +++ b/chromium/chrome/browser/extensions/api/i18n/i18n_api.h @@ -9,7 +9,7 @@ namespace extensions { -class I18nGetAcceptLanguagesFunction : public UIThreadExtensionFunction { +class I18nGetAcceptLanguagesFunction : public ExtensionFunction { ~I18nGetAcceptLanguagesFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("i18n.getAcceptLanguages", I18N_GETACCEPTLANGUAGES) diff --git a/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc b/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc index bd781fbb1e6..1ef3f5eba80 100644 --- a/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc +++ b/chromium/chrome/browser/extensions/api/identity/gaia_web_auth_flow_unittest.cc @@ -7,7 +7,7 @@ #include <vector> #include "base/run_loop.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -94,7 +94,7 @@ class IdentityGaiaWebAuthFlowTest : public testing::Test { protected: testing::StrictMock<MockGaiaWebAuthFlowDelegate> delegate_; GoogleServiceAuthError::State ubertoken_error_state_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(IdentityGaiaWebAuthFlowTest, OAuthError) { diff --git a/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc b/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc index a4d5166c2eb..64262f3b2bf 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_api_unittest.cc @@ -9,7 +9,7 @@ #include "chrome/browser/signin/scoped_account_consistency.h" #include "chrome/test/base/testing_profile.h" #include "components/signin/public/base/signin_buildflags.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -17,7 +17,7 @@ namespace extensions { #if BUILDFLAG(ENABLE_DICE_SUPPORT) // Tests that all accounts in extensions is only enabled when Dice is enabled. TEST(IdentityApiTest, DiceAllAccountsExtensions) { - content::TestBrowserThreadBundle test_thread_bundle; + content::BrowserTaskEnvironment task_environment; base::test::ScopedFeatureList feature_list; feature_list.InitAndEnableFeature(kExtensionsAllAccountsFeature); @@ -43,7 +43,7 @@ TEST(IdentityApiTest, DiceAllAccountsExtensions) { #endif TEST(IdentityApiTest, AllAccountsExtensionDisabled) { - content::TestBrowserThreadBundle test_thread_bundle; + content::BrowserTaskEnvironment task_environment; #if BUILDFLAG(ENABLE_DICE_SUPPORT) base::test::ScopedFeatureList feature_list; feature_list.InitAndDisableFeature(kExtensionsAllAccountsFeature); diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc index 99e6d3972a3..ef79b4e60e5 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc @@ -89,7 +89,7 @@ static const char kExtensionId[] = "ext_id"; // after the call happens. class AsyncFunctionRunner { public: - void RunFunctionAsync(UIThreadExtensionFunction* function, + void RunFunctionAsync(ExtensionFunction* function, const std::string& args, content::BrowserContext* browser_context) { response_delegate_.reset(new api_test_utils::SendResponseHelper(function)); @@ -109,14 +109,14 @@ class AsyncFunctionRunner { function->RunWithValidation()->Execute(); } - std::string WaitForError(UIThreadExtensionFunction* function) { + std::string WaitForError(ExtensionFunction* function) { RunMessageLoopUntilResponse(); CHECK(function->response_type()); EXPECT_EQ(ExtensionFunction::FAILED, *function->response_type()); return function->GetError(); } - base::Value* WaitForSingleResult(UIThreadExtensionFunction* function) { + base::Value* WaitForSingleResult(ExtensionFunction* function) { RunMessageLoopUntilResponse(); EXPECT_TRUE(function->GetError().empty()) << "Unexpected error: " << function->GetError(); @@ -140,18 +140,17 @@ class AsyncFunctionRunner { class AsyncExtensionBrowserTest : public ExtensionBrowserTest { protected: // Provide wrappers of AsynchronousFunctionRunner for convenience. - void RunFunctionAsync(UIThreadExtensionFunction* function, - const std::string& args) { + void RunFunctionAsync(ExtensionFunction* function, const std::string& args) { async_function_runner_ = std::make_unique<AsyncFunctionRunner>(); async_function_runner_->RunFunctionAsync(function, args, browser()->profile()); } - std::string WaitForError(UIThreadExtensionFunction* function) { + std::string WaitForError(ExtensionFunction* function) { return async_function_runner_->WaitForError(function); } - base::Value* WaitForSingleResult(UIThreadExtensionFunction* function) { + base::Value* WaitForSingleResult(ExtensionFunction* function) { return async_function_runner_->WaitForSingleResult(function); } diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h index a123670090e..1b8c765ef1d 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.h @@ -10,7 +10,7 @@ namespace extensions { -class IdentityGetAccountsFunction : public UIThreadExtensionFunction { +class IdentityGetAccountsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("identity.getAccounts", IDENTITY_GETACCOUNTS) @@ -19,7 +19,7 @@ class IdentityGetAccountsFunction : public UIThreadExtensionFunction { private: ~IdentityGetAccountsFunction() override; - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ExtensionFunction::ResponseAction Run() override; }; 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 2efd2f74eb6..1de99c202c3 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 @@ -145,14 +145,14 @@ bool IdentityGetAuthTokenFunction::RunAsync() { if (gaia_id.empty() || IsPrimaryAccountOnly()) { // Try the primary account. // TODO(https://crbug.com/932400): collapse the asynchronicity - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &IdentityGetAuthTokenFunction::GetAuthTokenForPrimaryAccount, weak_ptr_factory_.GetWeakPtr(), gaia_id)); } else { // Get the AccountInfo for the account that the extension wishes to use. - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&IdentityGetAuthTokenFunction::FetchExtensionAccountInfo, weak_ptr_factory_.GetWeakPtr(), gaia_id)); @@ -199,7 +199,8 @@ void IdentityGetAuthTokenFunction::FetchExtensionAccountInfo( const std::string& gaia_id) { OnReceivedExtensionAccountInfo(base::OptionalOrNullptr( IdentityManagerFactory::GetForProfile(GetProfile()) - ->FindAccountInfoForAccountWithRefreshTokenByGaiaId(gaia_id))); + ->FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId( + gaia_id))); } void IdentityGetAuthTokenFunction::OnReceivedExtensionAccountInfo( @@ -261,7 +262,7 @@ void IdentityGetAuthTokenFunction::OnAccountsInCookieUpdated( email_for_default_web_account_ = account.email; OnReceivedExtensionAccountInfo(base::OptionalOrNullptr( IdentityManagerFactory::GetForProfile(GetProfile()) - ->FindAccountInfoForAccountWithRefreshTokenByGaiaId( + ->FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId( account.gaia_id))); } else { OnReceivedExtensionAccountInfo(nullptr); @@ -800,7 +801,7 @@ void IdentityGetAuthTokenFunction::StartGaiaRequest( void IdentityGetAuthTokenFunction::ShowExtensionLoginPrompt() { base::Optional<AccountInfo> account = IdentityManagerFactory::GetForProfile(GetProfile()) - ->FindAccountInfoForAccountWithRefreshTokenByAccountId( + ->FindExtendedAccountInfoForAccountWithRefreshTokenByAccountId( token_key_.account_id); std::string email_hint = account ? account->email : email_for_default_web_account_; 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 0eb440bebac..1b3b46143d4 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 @@ -129,8 +129,8 @@ class IdentityGetAuthTokenFunction : public ChromeAsyncExtensionFunction, // instance, or empty if this was not in the parameters. void GetAuthTokenForPrimaryAccount(const std::string& extension_gaia_id); - // Wrapper to FindAccountInfoForAccountWithRefreshTokenByGaiaId() to avoid a - // synchronous call to IdentityManager in RunAsync(). + // Wrapper to FindExtendedAccountInfoForAccountWithRefreshTokenByGaiaId() to + // avoid a synchronous call to IdentityManager in RunAsync(). void FetchExtensionAccountInfo(const std::string& gaia_id); // Called when the AccountInfo that this instance should use is available. diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h index f68ecc9b21c..84edc0d3488 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.h @@ -10,7 +10,7 @@ namespace extensions { -class IdentityGetProfileUserInfoFunction : public UIThreadExtensionFunction { +class IdentityGetProfileUserInfoFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("identity.getProfileUserInfo", IDENTITY_GETPROFILEUSERINFO) @@ -20,7 +20,7 @@ class IdentityGetProfileUserInfoFunction : public UIThreadExtensionFunction { private: ~IdentityGetProfileUserInfoFunction() override; - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ExtensionFunction::ResponseAction Run() override; }; diff --git a/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h b/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h index 710c2eeff43..e99b46414ab 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h +++ b/chromium/chrome/browser/extensions/api/identity/identity_remove_cached_auth_token_function.h @@ -10,7 +10,7 @@ namespace extensions { -class IdentityRemoveCachedAuthTokenFunction : public UIThreadExtensionFunction { +class IdentityRemoveCachedAuthTokenFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("identity.removeCachedAuthToken", EXPERIMENTAL_IDENTITY_REMOVECACHEDAUTHTOKEN) diff --git a/chromium/chrome/browser/extensions/api/idltest/idltest_api.h b/chromium/chrome/browser/extensions/api/idltest/idltest_api.h index 48b5e9d7d6c..5219e3e07fd 100644 --- a/chromium/chrome/browser/extensions/api/idltest/idltest_api.h +++ b/chromium/chrome/browser/extensions/api/idltest/idltest_api.h @@ -7,7 +7,7 @@ #include "extensions/browser/extension_function.h" -class IdltestSendArrayBufferFunction : public UIThreadExtensionFunction { +class IdltestSendArrayBufferFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.sendArrayBuffer", IDLTEST_SENDARRAYBUFFER) @@ -16,7 +16,7 @@ class IdltestSendArrayBufferFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class IdltestSendArrayBufferViewFunction : public UIThreadExtensionFunction { +class IdltestSendArrayBufferViewFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.sendArrayBufferView", IDLTEST_SENDARRAYBUFFERVIEW) @@ -26,7 +26,7 @@ class IdltestSendArrayBufferViewFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class IdltestGetArrayBufferFunction : public UIThreadExtensionFunction { +class IdltestGetArrayBufferFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("idltest.getArrayBuffer", IDLTEST_GETARRAYBUFFER) diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc index 6b229b022da..8560050c09a 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.cc @@ -9,7 +9,6 @@ #include "chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "content/public/browser/browser_thread.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -21,12 +20,10 @@ const int kPartitionTableSize = 2 * 4096; DestroyPartitionsOperation::DestroyPartitionsOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& storage_unit_id, const base::FilePath& download_folder) : Operation(manager, - std::move(connector), extension_id, storage_unit_id, download_folder) {} diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h index 3373953c3e6..c1fc6448ceb 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h @@ -19,7 +19,6 @@ class DestroyPartitionsOperation : public Operation { public: DestroyPartitionsOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& storage_unit_id, const base::FilePath& download_folder); diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc index 1a49548244c..35ca237f4ef 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation_unittest.cc @@ -9,7 +9,6 @@ #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -42,8 +41,7 @@ TEST_F(ImageWriterDestroyPartitionsOperationTest, EndToEnd) { scoped_refptr<DestroyPartitionsOperation> operation( new DestroyPartitionsOperation( - manager.AsWeakPtr(), - /*connector=*/nullptr, kDummyExtensionId, + manager.AsWeakPtr(), kDummyExtensionId, test_utils_.GetDevicePath().AsUTF8Unsafe(), base::FilePath(FILE_PATH_LITERAL("/var/tmp")))); 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 03aff051004..657ecfd62f8 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 @@ -8,23 +8,26 @@ #include "base/files/file_path.h" #include "base/location.h" #include "base/optional.h" +#include "build/build_config.h" #include "chrome/grit/generated_resources.h" -#include "chrome/services/removable_storage_writer/public/mojom/constants.mojom.h" #include "content/public/browser/browser_thread.h" -#include "mojo/public/cpp/bindings/binding.h" -#include "services/service_manager/public/cpp/connector.h" +#include "content/public/browser/sandbox_type.h" +#include "content/public/browser/service_process_host.h" +#include "mojo/public/cpp/bindings/receiver.h" #include "ui/base/l10n/l10n_util.h" namespace extensions { namespace image_writer { namespace { + ImageWriterUtilityClient::ImageWriterUtilityClientFactory* g_factory_for_testing = nullptr; -void DeleteInterfacePtr(chrome::mojom::RemovableStorageWriterPtr writer_ptr) { - // Just let the parameters go out of scope so they are deleted. +void DeleteRemote(mojo::Remote<chrome::mojom::RemovableStorageWriter> writer) { + // Just let the parameter go out of scope so it's deleted. } + } // namespace class ImageWriterUtilityClient::RemovableStorageWriterClientImpl @@ -32,10 +35,11 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl public: RemovableStorageWriterClientImpl( ImageWriterUtilityClient* owner, - chrome::mojom::RemovableStorageWriterClientPtr* interface_ptr) - : binding_(this, mojo::MakeRequest(interface_ptr)), + mojo::PendingReceiver<chrome::mojom::RemovableStorageWriterClient> + receiver) + : receiver_(this, std::move(receiver)), image_writer_utility_client_(owner) { - binding_.set_connection_error_handler( + receiver_.set_disconnect_handler( base::BindOnce(&ImageWriterUtilityClient::OnConnectionError, image_writer_utility_client_)); } @@ -55,7 +59,8 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl } } - mojo::Binding<chrome::mojom::RemovableStorageWriterClient> binding_; + mojo::Receiver<chrome::mojom::RemovableStorageWriterClient> receiver_; + // |image_writer_utility_client_| owns |this|. ImageWriterUtilityClient* const image_writer_utility_client_; @@ -63,29 +68,23 @@ class ImageWriterUtilityClient::RemovableStorageWriterClientImpl }; ImageWriterUtilityClient::ImageWriterUtilityClient( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector) - : task_runner_(task_runner), connector_(std::move(connector)) {} + const scoped_refptr<base::SequencedTaskRunner>& task_runner) + : task_runner_(task_runner) {} ImageWriterUtilityClient::~ImageWriterUtilityClient() { // We could be running on a different TaskRunner (typically, the UI thread). // Post to be safe. - task_runner_->DeleteSoon(FROM_HERE, std::move(connector_)); - task_runner_->PostTask(FROM_HERE, - base::BindOnce(&DeleteInterfacePtr, - std::move(removable_storage_writer_))); + task_runner_->PostTask( + FROM_HERE, + base::BindOnce(&DeleteRemote, std::move(removable_storage_writer_))); } // static scoped_refptr<ImageWriterUtilityClient> ImageWriterUtilityClient::Create( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector) { - // connector_ can be null in unit-tests. - DCHECK(!connector || !connector->IsBound()); + const scoped_refptr<base::SequencedTaskRunner>& task_runner) { if (g_factory_for_testing) return g_factory_for_testing->Run(); - return base::WrapRefCounted( - new ImageWriterUtilityClient(task_runner, std::move(connector))); + return base::WrapRefCounted(new ImageWriterUtilityClient(task_runner)); } // static @@ -108,11 +107,12 @@ void ImageWriterUtilityClient::Write(const ProgressCallback& progress_callback, BindServiceIfNeeded(); - chrome::mojom::RemovableStorageWriterClientPtr client; + mojo::PendingRemote<chrome::mojom::RemovableStorageWriterClient> + remote_client; removable_storage_writer_client_ = - std::make_unique<RemovableStorageWriterClientImpl>(this, &client); - - removable_storage_writer_->Write(source, target, std::move(client)); + std::make_unique<RemovableStorageWriterClientImpl>( + this, remote_client.InitWithNewPipeAndPassReceiver()); + removable_storage_writer_->Write(source, target, std::move(remote_client)); } void ImageWriterUtilityClient::Verify(const ProgressCallback& progress_callback, @@ -129,11 +129,12 @@ void ImageWriterUtilityClient::Verify(const ProgressCallback& progress_callback, BindServiceIfNeeded(); - chrome::mojom::RemovableStorageWriterClientPtr client; + mojo::PendingRemote<chrome::mojom::RemovableStorageWriterClient> + remote_client; removable_storage_writer_client_ = - std::make_unique<RemovableStorageWriterClientImpl>(this, &client); - - removable_storage_writer_->Verify(source, target, std::move(client)); + std::make_unique<RemovableStorageWriterClientImpl>( + this, remote_client.InitWithNewPipeAndPassReceiver()); + removable_storage_writer_->Verify(source, target, std::move(remote_client)); } void ImageWriterUtilityClient::Cancel(const CancelCallback& cancel_callback) { @@ -157,9 +158,19 @@ void ImageWriterUtilityClient::BindServiceIfNeeded() { if (removable_storage_writer_) return; - connector_->BindInterface(chrome::mojom::kRemovableStorageWriterServiceName, - mojo::MakeRequest(&removable_storage_writer_)); - removable_storage_writer_.set_connection_error_handler( +#if defined(OS_WIN) + constexpr auto kSandboxType = + service_manager::SANDBOX_TYPE_NO_SANDBOX_AND_ELEVATED_PRIVILEGES; +#else + constexpr auto kSandboxType = service_manager::SANDBOX_TYPE_NO_SANDBOX; +#endif + content::ServiceProcessHost::Launch( + removable_storage_writer_.BindNewPipeAndPassReceiver(), + content::ServiceProcessHost::Options() + .WithDisplayName(IDS_UTILITY_PROCESS_IMAGE_WRITER_NAME) + .WithSandboxType(kSandboxType) + .Pass()); + removable_storage_writer_.set_disconnect_handler( base::BindOnce(&ImageWriterUtilityClient::OnConnectionError, this)); } 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 6ac29f5ab5e..63c45483721 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 @@ -16,10 +16,7 @@ #include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" #include "chrome/services/removable_storage_writer/public/mojom/removable_storage_writer.mojom.h" - -namespace service_manager { -class Connector; -} +#include "mojo/public/cpp/bindings/remote.h" namespace extensions { namespace image_writer { @@ -36,10 +33,8 @@ class ImageWriterUtilityClient using ImageWriterUtilityClientFactory = base::Callback<scoped_refptr<ImageWriterUtilityClient>()>; - // |connector| should be a fresh connector not yet bound to any thread. static scoped_refptr<ImageWriterUtilityClient> Create( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector); + const scoped_refptr<base::SequencedTaskRunner>& task_runner); static void SetFactoryForTesting(ImageWriterUtilityClientFactory* factory); @@ -79,9 +74,8 @@ class ImageWriterUtilityClient friend class base::RefCountedThreadSafe<ImageWriterUtilityClient>; friend class ImageWriterUtilityClientTest; - ImageWriterUtilityClient( - const scoped_refptr<base::SequencedTaskRunner>& task_runner, - std::unique_ptr<service_manager::Connector> connector); + explicit ImageWriterUtilityClient( + const scoped_refptr<base::SequencedTaskRunner>& task_runner); virtual ~ImageWriterUtilityClient(); private: @@ -102,9 +96,7 @@ class ImageWriterUtilityClient scoped_refptr<base::SequencedTaskRunner> task_runner_; - std::unique_ptr<service_manager::Connector> connector_; - - chrome::mojom::RemovableStorageWriterPtr removable_storage_writer_; + mojo::Remote<chrome::mojom::RemovableStorageWriter> removable_storage_writer_; std::unique_ptr<RemovableStorageWriterClientImpl> removable_storage_writer_client_; 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 7447bbcab5c..797239e9342 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 @@ -19,8 +19,6 @@ #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/system_connector.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -43,8 +41,8 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { EXPECT_TRUE(base::CreateTemporaryFileInDir(temp_dir_.GetPath(), &image_)); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ImageWriterUtilityClientTest::FillFile, image_, pattern), run_loop.QuitClosure()); @@ -56,8 +54,8 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { device_ = image_.ReplaceExtension(FILE_PATH_LITERAL("out")); base::RunLoop run_loop; - base::PostTaskWithTraitsAndReply( - FROM_HERE, {base::MayBlock()}, + base::PostTaskAndReply( + FROM_HERE, {base::ThreadPool(), base::MayBlock()}, base::BindOnce(&ImageWriterUtilityClientTest::FillFile, device_, pattern), run_loop.QuitClosure()); @@ -102,16 +100,13 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { const std::string& error() const { return error_; } private: - void SetUpOnMainThread() override { - connector_ = content::GetSystemConnector()->Clone(); - } - void StartWriteTest() { DCHECK(IsRunningInCorrectSequence()); - if (!image_writer_utility_client_) + if (!image_writer_utility_client_) { image_writer_utility_client_ = - new ImageWriterUtilityClient(GetTaskRunner(), std::move(connector_)); + new ImageWriterUtilityClient(GetTaskRunner()); + } success_ = false; progress_ = 0; @@ -156,9 +151,10 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { void StartVerifyTest() { DCHECK(IsRunningInCorrectSequence()); - if (!image_writer_utility_client_) + if (!image_writer_utility_client_) { image_writer_utility_client_ = - new ImageWriterUtilityClient(GetTaskRunner(), std::move(connector_)); + new ImageWriterUtilityClient(GetTaskRunner()); + } success_ = false; progress_ = 0; @@ -203,8 +199,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { success_ = cancel_; quit_called_ = true; - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - quit_closure_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_); } void Shutdown() { @@ -213,8 +208,7 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { image_writer_utility_client_->Shutdown(); quit_called_ = true; - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - quit_closure_); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, quit_closure_); } static void FillFile(const base::FilePath& path, char pattern) { @@ -224,8 +218,8 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { base::SequencedTaskRunner* CreateTaskRunner() { DCHECK(!task_runner_.get()); - task_runner_ = base::CreateSequencedTaskRunnerWithTraits( - Operation::blocking_task_traits()); + task_runner_ = + base::CreateSequencedTaskRunner(Operation::blocking_task_traits()); return task_runner_.get(); } @@ -255,7 +249,6 @@ class ImageWriterUtilityClientTest : public InProcessBrowserTest { bool cancel_ = false; std::string error_; scoped_refptr<base::SequencedTaskRunner> task_runner_; - std::unique_ptr<service_manager::Connector> connector_; DISALLOW_COPY_AND_ASSIGN(ImageWriterUtilityClientTest); }; diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc index a3cd8085f6e..330d582ae81 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc @@ -15,7 +15,6 @@ #include "chrome/browser/extensions/api/image_writer_private/unzip_helper.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -29,7 +28,6 @@ const int kMD5BufferSize = 1024; } // namespace Operation::Operation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& device_path, const base::FilePath& download_folder) @@ -41,18 +39,13 @@ Operation::Operation(base::WeakPtr<OperationManager> manager, device_path_(device_path), #endif temp_dir_(std::make_unique<base::ScopedTempDir>()), - connector_(std::move(connector)), stage_(image_writer_api::STAGE_UNKNOWN), progress_(0), download_folder_(download_folder), - task_runner_( - base::CreateSequencedTaskRunnerWithTraits(blocking_task_traits())) { + task_runner_(base::CreateSequencedTaskRunner(blocking_task_traits())) { } Operation::~Operation() { - // The connector_ is bound to the |task_runner_| and must be deleted there. - task_runner_->DeleteSoon(FROM_HERE, std::move(connector_)); - // base::ScopedTempDir must be destroyed on a thread that allows blocking IO // because it will try delete the directory if a call to Delete() hasn't been // made or was unsuccessful. @@ -134,7 +127,7 @@ void Operation::Finish() { CleanUp(); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationManager::OnComplete, manager_, extension_id_)); } @@ -142,7 +135,7 @@ void Operation::Finish() { void Operation::Error(const std::string& error_message) { DCHECK(IsRunningInCorrectSequence()); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&OperationManager::OnError, manager_, extension_id_, stage_, progress_, error_message)); @@ -163,10 +156,9 @@ void Operation::SetProgress(int progress) { progress_ = progress; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OperationManager::OnProgress, manager_, extension_id_, - stage_, progress_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OperationManager::OnProgress, manager_, + extension_id_, stage_, progress_)); } void Operation::SetStage(image_writer_api::Stage stage) { @@ -178,10 +170,9 @@ void Operation::SetStage(image_writer_api::Stage stage) { stage_ = stage; progress_ = 0; - base::PostTaskWithTraits( - FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&OperationManager::OnProgress, manager_, extension_id_, - stage_, progress_)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&OperationManager::OnProgress, manager_, + extension_id_, stage_, progress_)); } bool Operation::IsCancelled() { @@ -205,9 +196,7 @@ void Operation::CompleteAndContinue(const base::Closure& continuation) { void Operation::StartUtilityClient() { DCHECK(IsRunningInCorrectSequence()); if (!image_writer_client_.get()) { - // connector_ can be null in tests. - image_writer_client_ = ImageWriterUtilityClient::Create( - task_runner_, connector_ ? connector_->Clone() : nullptr); + image_writer_client_ = ImageWriterUtilityClient::Create(task_runner_); AddCleanUpFunction(base::BindOnce(&Operation::StopUtilityClient, this)); } } 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 cfc95222395..7444da741d7 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.h @@ -32,10 +32,6 @@ namespace base { class FilePath; } // namespace base -namespace service_manager { -class Connector; -} - namespace extensions { namespace image_writer { @@ -67,7 +63,6 @@ class Operation : public base::RefCountedThreadSafe<Operation> { base::OnceCallback<void(bool, const std::string&)>; Operation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const std::string& device_path, const base::FilePath& download_folder); @@ -219,9 +214,6 @@ class Operation : public base::RefCountedThreadSafe<Operation> { // Runs all cleanup functions. void CleanUp(); - // Connector to the service manager. Used and deleted on |task_runner_|. - std::unique_ptr<service_manager::Connector> connector_; - // |stage_| and |progress_| are owned by the FILE thread, use |SetStage| and // |SetProgress| to update. Progress should be in the interval [0,100] image_writer_api::Stage stage_; @@ -237,6 +229,7 @@ class Operation : public base::RefCountedThreadSafe<Operation> { static constexpr base::TaskTraits blocking_task_traits() { return { + base::ThreadPool(), // Requires I/O. base::MayBlock(), // Apps (e.g. Chromebook Recovery Utility) present UI feedback based on diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc index 60ea32e7ca0..9144e4d6cfd 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_chromeos.cc @@ -26,8 +26,8 @@ namespace { void ClearImageBurner() { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ClearImageBurner)); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ClearImageBurner)); return; } @@ -45,7 +45,7 @@ void Operation::Write(const base::Closure& continuation) { // Note this has to be run on the FILE thread to avoid concurrent access. AddCleanUpFunction(base::Bind(&ClearImageBurner)); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&Operation::UnmountVolumes, this, continuation)); } 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 3f5d95f8bc8..f0dbae03359 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 @@ -7,6 +7,7 @@ #include <utility> #include "base/lazy_instance.h" +#include "base/memory/scoped_refptr.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/image_writer_private/destroy_partitions_operation.h" @@ -20,12 +21,10 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/storage_partition.h" -#include "content/public/browser/system_connector.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" -#include "services/service_manager/public/cpp/connector.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/file_manager/path_util.h" @@ -87,10 +86,10 @@ void OperationManager::StartWriteFromUrl( ->GetURLLoaderFactoryForBrowserProcess() ->Clone(mojo::MakeRequest(&url_loader_factory_info)); - scoped_refptr<Operation> operation(new WriteFromUrlOperation( - weak_factory_.GetWeakPtr(), CreateConnector(), extension_id, + auto operation = base::MakeRefCounted<WriteFromUrlOperation>( + weak_factory_.GetWeakPtr(), extension_id, std::move(url_loader_factory_info), url, hash, device_path, - GetAssociatedDownloadFolder())); + GetAssociatedDownloadFolder()); operations_[extension_id] = operation; operation->PostTask(base::BindOnce(&Operation::Start, operation)); @@ -114,9 +113,9 @@ void OperationManager::StartWriteFromFile( return; } - scoped_refptr<Operation> operation(new WriteFromFileOperation( - weak_factory_.GetWeakPtr(), CreateConnector(), extension_id, path, - device_path, GetAssociatedDownloadFolder())); + auto operation = base::MakeRefCounted<WriteFromFileOperation>( + weak_factory_.GetWeakPtr(), extension_id, path, device_path, + GetAssociatedDownloadFolder()); operations_[extension_id] = operation; operation->PostTask(base::BindOnce(&Operation::Start, operation)); std::move(callback).Run(true, ""); @@ -147,9 +146,9 @@ void OperationManager::DestroyPartitions( return; } - scoped_refptr<Operation> operation(new DestroyPartitionsOperation( - weak_factory_.GetWeakPtr(), CreateConnector(), extension_id, device_path, - GetAssociatedDownloadFolder())); + auto operation = base::MakeRefCounted<DestroyPartitionsOperation>( + weak_factory_.GetWeakPtr(), extension_id, device_path, + GetAssociatedDownloadFolder()); operations_[extension_id] = operation; operation->PostTask(base::BindOnce(&Operation::Start, operation)); std::move(callback).Run(true, ""); @@ -243,11 +242,6 @@ void OperationManager::OnExtensionUnloaded( DeleteOperation(extension->id()); } -std::unique_ptr<service_manager::Connector> -OperationManager::CreateConnector() { - return content::GetSystemConnector()->Clone(); -} - void OperationManager::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { 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 e9c88e3ac22..ae2a04f5658 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 @@ -86,10 +86,6 @@ class OperationManager : public BrowserContextKeyedAPI, static BrowserContextKeyedAPIFactory<OperationManager>* GetFactoryInstance(); static OperationManager* Get(content::BrowserContext* context); - protected: - // Overridden in test. - virtual std::unique_ptr<service_manager::Connector> CreateConnector(); - private: static const char* service_name() { return "OperationManager"; diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc index b27b88e9ab0..2ae9ff7edfd 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_manager_unittest.cc @@ -13,24 +13,12 @@ #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" #include "extensions/browser/test_event_router.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { namespace { -class TestOperationManager : public OperationManager { - public: - explicit TestOperationManager(content::BrowserContext* context) - : OperationManager(context) {} - - private: - std::unique_ptr<service_manager::Connector> CreateConnector() override { - return nullptr; - } -}; - class ImageWriterOperationManagerTest : public ImageWriterUnitTestBase { public: void StartCallback(bool success, const std::string& error) { @@ -68,7 +56,7 @@ class ImageWriterOperationManagerTest : public ImageWriterUnitTestBase { }; TEST_F(ImageWriterOperationManagerTest, WriteFromFile) { - TestOperationManager manager(&test_profile_); + OperationManager manager(&test_profile_); manager.StartWriteFromFile( kDummyExtensionId, test_utils_.GetImagePath(), @@ -93,7 +81,7 @@ TEST_F(ImageWriterOperationManagerTest, WriteFromFile) { } TEST_F(ImageWriterOperationManagerTest, DestroyPartitions) { - TestOperationManager manager(&test_profile_); + OperationManager manager(&test_profile_); manager.DestroyPartitions( kDummyExtensionId, test_utils_.GetDevicePath().AsUTF8Unsafe(), diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc index 4cb18028036..5e90ec2533f 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation_unittest.cc @@ -15,8 +15,7 @@ #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" #include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" -#include "services/service_manager/public/cpp/connector.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/zlib/google/zip.h" @@ -53,11 +52,7 @@ class OperationForTest : public Operation { const ExtensionId& extension_id, const std::string& device_path, const base::FilePath& download_path) - : Operation(manager_, - /*connector=*/nullptr, - extension_id, - device_path, - download_path) {} + : Operation(manager_, extension_id, device_path, download_path) {} void StartImpl() override {} @@ -121,7 +116,7 @@ class ImageWriterOperationTest : public ImageWriterUnitTestBase { // Cancel() will ensure we Shutdown() FakeImageWriterClient. operation_->Cancel(); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ImageWriterUnitTestBase::TearDown(); } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc index 39dee11b2cd..ec433f683f3 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.cc @@ -28,9 +28,9 @@ void RemovableStorageProvider::GetAllDevices(DeviceListReadyCallback callback) { return; } // We need to do some file i/o to get the device block size - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, base::BindOnce(&RemovableStorageProvider::PopulateDeviceList), std::move(callback)); diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h index 5dd00878cfd..e333dd5b7ac 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h @@ -5,6 +5,7 @@ #define CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_REMOVABLE_STORAGE_PROVIDER_H_ #include "base/callback.h" +#include "base/memory/scoped_refptr.h" #include "chrome/common/extensions/api/image_writer_private.h" #include "chrome/common/ref_counted_util.h" diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc index 525557ccce8..780f0c7ecc0 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos.cc @@ -4,6 +4,7 @@ #include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h" +#include "base/memory/scoped_refptr.h" #include "chromeos/disks/disk.h" #include "chromeos/disks/disk_mount_manager.h" @@ -24,7 +25,7 @@ scoped_refptr<StorageDeviceList> RemovableStorageProvider::PopulateDeviceList() { DiskMountManager* disk_mount_manager = DiskMountManager::GetInstance(); const DiskMountManager::DiskMap& disks = disk_mount_manager->disks(); - scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); for (DiskMountManager::DiskMap::const_iterator iter = disks.begin(); iter != disks.end(); diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc index 91fd7c8ec41..431c9e43557 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_chromeos_unittest.cc @@ -8,7 +8,7 @@ #include "base/run_loop.h" #include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h" #include "chromeos/disks/mock_disk_mount_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -104,7 +104,7 @@ class RemovableStorageProviderChromeOsUnitTest : public testing::Test { EXPECT_EQ(capacity, device->capacity); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; MockDiskMountManager* disk_mount_manager_mock_; scoped_refptr<StorageDeviceList> devices_; }; @@ -125,7 +125,7 @@ TEST_F(RemovableStorageProviderChromeOsUnitTest, GetAllDevices) { base::Bind(&RemovableStorageProviderChromeOsUnitTest::DevicesCallback, base::Unretained(this))); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_EQ(2U, devices_->data.size()); @@ -146,7 +146,7 @@ TEST_F(RemovableStorageProviderChromeOsUnitTest, EmptyProductAndModel) { base::Bind(&RemovableStorageProviderChromeOsUnitTest::DevicesCallback, base::Unretained(this))); - thread_bundle_.RunUntilIdle(); + task_environment_.RunUntilIdle(); ASSERT_EQ(2U, devices_->data.size()); diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc index fa04548454b..fa2976bbf96 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_linux.cc @@ -5,6 +5,7 @@ #include <stdint.h> #include "base/files/file_util.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" #include "chrome/browser/extensions/api/image_writer_private/removable_storage_provider.h" #include "content/public/browser/browser_thread.h" @@ -57,7 +58,7 @@ RemovableStorageProvider::PopulateDeviceList() { return nullptr; } - scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); /* Create a list of the devices in the 'block' subsystem. */ device::ScopedUdevEnumeratePtr enumerate( device::udev_enumerate_new(udev.get())); diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc index 4cc10223c1a..d6e49e851fe 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_mac.cc @@ -14,6 +14,7 @@ #include "base/mac/foundation_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/mac/scoped_ioobject.h" +#include "base/memory/scoped_refptr.h" #include "base/strings/sys_string_conversions.h" #include "base/threading/scoped_blocking_call.h" #include "chrome/common/extensions/image_writer/image_writer_util_mac.h" @@ -42,7 +43,7 @@ RemovableStorageProvider::PopulateDeviceList() { } base::mac::ScopedIOObject<io_object_t> disk_obj; - scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); while (disk_obj.reset(IOIteratorNext(disk_iterator)), disk_obj) { std::string bsd_name; uint64_t size_in_bytes; diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc index cd04a90314d..e069f5f485a 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/removable_storage_provider_win.cc @@ -15,6 +15,7 @@ #include <memory> +#include "base/memory/scoped_refptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -197,7 +198,7 @@ RemovableStorageProvider::PopulateDeviceList() { SP_DEVICE_INTERFACE_DATA interface_data; interface_data.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA); - scoped_refptr<StorageDeviceList> device_list(new StorageDeviceList()); + auto device_list = base::MakeRefCounted<StorageDeviceList>(); while (SetupDiEnumDeviceInterfaces( interface_enumerator, NULL, // Device Info data. diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc index 6a745455bab..c7ca25348d9 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.cc @@ -14,7 +14,6 @@ #include "base/threading/thread_task_runner_handle.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" -#include "services/service_manager/public/cpp/connector.h" #if defined(OS_CHROMEOS) #include "chromeos/dbus/dbus_thread_manager.h" @@ -92,11 +91,10 @@ SimulateProgressInfo::SimulateProgressInfo(const SimulateProgressInfo&) = default; FakeImageWriterClient::FakeImageWriterClient() - : ImageWriterUtilityClient( - base::CreateSequencedTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, - base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}), - /*connector=*/nullptr) {} + : ImageWriterUtilityClient(base::CreateSequencedTaskRunner( + {base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})) {} FakeImageWriterClient::~FakeImageWriterClient() {} void FakeImageWriterClient::SimulateProgressAndCompletion( @@ -316,7 +314,7 @@ bool ImageWriterTestUtils::FillFile(const base::FilePath& file, } ImageWriterUnitTestBase::ImageWriterUnitTestBase() - : thread_bundle_(content::TestBrowserThreadBundle::REAL_IO_THREAD) {} + : task_environment_(content::BrowserTaskEnvironment::REAL_IO_THREAD) {} ImageWriterUnitTestBase::~ImageWriterUnitTestBase() { } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h index ab9f77a6752..f2e1b3c5246 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/test_utils.h @@ -12,11 +12,11 @@ #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" -#include "base/test/scoped_task_environment.h" +#include "base/test/task_environment.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h" #include "chrome/browser/extensions/api/image_writer_private/operation_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -204,7 +204,7 @@ class ImageWriterUnitTestBase : public testing::Test { ImageWriterTestUtils test_utils_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; } // namespace image_writer diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc b/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc index f80ddf9dd2e..4ae7b054f1b 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/unzip_helper.cc @@ -34,8 +34,8 @@ UnzipHelper::~UnzipHelper() {} void UnzipHelper::Unzip(const base::FilePath& image_path, const base::FilePath& temp_dir_path) { scoped_refptr<base::SingleThreadTaskRunner> task_runner = - base::CreateSingleThreadTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); + base::CreateSingleThreadTaskRunner({base::ThreadPool(), base::MayBlock(), + base::TaskPriority::USER_VISIBLE}); task_runner->PostTask(FROM_HERE, base::BindOnce(&UnzipHelper::UnzipImpl, this, image_path, temp_dir_path)); } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc index 26b06b178cf..dfb46fe602a 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.cc @@ -8,7 +8,6 @@ #include "base/files/file_util.h" #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "content/public/browser/browser_thread.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -17,16 +16,11 @@ using content::BrowserThread; WriteFromFileOperation::WriteFromFileOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const base::FilePath& user_file_path, const std::string& device_path, const base::FilePath& download_folder) - : Operation(manager, - std::move(connector), - extension_id, - device_path, - download_folder) { + : Operation(manager, extension_id, device_path, download_folder) { image_path_ = user_file_path; } diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h index 5e6951e2ff6..ef82e25f881 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation.h @@ -7,10 +7,6 @@ #include "chrome/browser/extensions/api/image_writer_private/operation.h" -namespace service_manager { -class Connector; -} - namespace extensions { namespace image_writer { @@ -18,7 +14,6 @@ namespace image_writer { class WriteFromFileOperation : public Operation { public: WriteFromFileOperation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, const base::FilePath& user_file_path, const std::string& storage_unit_id, diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc index 11af9bbe4f6..cc3d4473c73 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_file_operation_unittest.cc @@ -9,7 +9,6 @@ #include "chrome/browser/extensions/api/image_writer_private/error_messages.h" #include "chrome/browser/extensions/api/image_writer_private/test_utils.h" #include "chrome/test/base/testing_profile.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -42,8 +41,7 @@ class ImageWriterFromFileTest : public ImageWriterUnitTestBase { TEST_F(ImageWriterFromFileTest, InvalidFile) { scoped_refptr<WriteFromFileOperation> op = new WriteFromFileOperation( - manager_.AsWeakPtr(), - /*connector=*/nullptr, kDummyExtensionId, test_utils_.GetImagePath(), + manager_.AsWeakPtr(), kDummyExtensionId, test_utils_.GetImagePath(), test_utils_.GetDevicePath().AsUTF8Unsafe(), base::FilePath(FILE_PATH_LITERAL("/var/tmp"))); @@ -70,8 +68,7 @@ TEST_F(ImageWriterFromFileTest, WriteFromFileEndToEnd) { #endif scoped_refptr<WriteFromFileOperation> op = new WriteFromFileOperation( - manager_.AsWeakPtr(), - /*connector=*/nullptr, kDummyExtensionId, test_utils_.GetImagePath(), + manager_.AsWeakPtr(), kDummyExtensionId, test_utils_.GetImagePath(), test_utils_.GetDevicePath().AsUTF8Unsafe(), base::FilePath(FILE_PATH_LITERAL("/var/tmp"))); EXPECT_CALL(manager_, diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc index 7c4669b4d8c..fdebd683504 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.cc @@ -12,7 +12,6 @@ #include "net/url_request/url_fetcher.h" #include "services/network/public/cpp/resource_response.h" #include "services/network/public/cpp/simple_url_loader.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -21,18 +20,13 @@ using content::BrowserThread; WriteFromUrlOperation::WriteFromUrlOperation( base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, network::mojom::URLLoaderFactoryPtrInfo factory_info, GURL url, const std::string& hash, const std::string& device_path, const base::FilePath& download_folder) - : Operation(manager, - std::move(connector), - extension_id, - device_path, - download_folder), + : Operation(manager, extension_id, device_path, download_folder), url_loader_factory_ptr_info_(std::move(factory_info)), url_(url), hash_(hash), diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h index 757fc07ffb9..617f609515a 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation.h @@ -25,7 +25,6 @@ class OperationManager; class WriteFromUrlOperation : public Operation { public: WriteFromUrlOperation(base::WeakPtr<OperationManager> manager, - std::unique_ptr<service_manager::Connector> connector, const ExtensionId& extension_id, network::mojom::URLLoaderFactoryPtrInfo factory_info, GURL url, diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc index bcb23055c50..fd04e401865 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/write_from_url_operation_unittest.cc @@ -14,7 +14,6 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/storage_partition.h" #include "content/public/test/url_loader_interceptor.h" -#include "services/service_manager/public/cpp/connector.h" namespace extensions { namespace image_writer { @@ -44,7 +43,6 @@ class WriteFromUrlOperationForTest : public WriteFromUrlOperation { const std::string& hash, const std::string& storage_unit_id) : WriteFromUrlOperation(manager, - /*connector=*/nullptr, extension_id, std::move(factory_info), url, @@ -243,7 +241,7 @@ TEST_F(ImageWriterWriteFromUrlOperationTest, VerifyFile) { // soon. operation->VerifyDownload(base::Bind( [](base::OnceClosure quit_closure) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI, base::TaskPriority::USER_VISIBLE}, std::move(quit_closure)); diff --git a/chromium/chrome/browser/extensions/api/input_ime/OWNERS b/chromium/chrome/browser/extensions/api/input_ime/OWNERS index bed537d50a2..d4bff68b766 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/OWNERS +++ b/chromium/chrome/browser/extensions/api/input_ime/OWNERS @@ -1,5 +1,6 @@ # primary reviewer shuchen@chromium.org +keithlee@chromium.org # backup reviewer googleo@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 de28c1441a6..9bfb7c8e07c 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 @@ -95,10 +95,10 @@ void ImeObserver::OnKeyEvent( extensions::InputImeEventRouter* event_router = extensions::GetInputImeEventRouter(profile_); - if (!event_router || !event_router->GetActiveEngine(extension_id_)) + if (!event_router || !event_router->GetEngineIfActive(extension_id_)) return; const std::string request_id = - event_router->GetActiveEngine(extension_id_) + event_router->GetEngineIfActive(extension_id_) ->AddRequest(component_id, std::move(key_data)); input_ime::KeyboardEvent key_data_value; @@ -312,7 +312,7 @@ ExtensionFunction::ResponseAction InputImeKeyEventHandledFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (engine) { engine->KeyEventHandled(extension_id(), params->request_id, params->response); @@ -324,7 +324,7 @@ ExtensionFunction::ResponseAction InputImeSetCompositionFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (engine) { std::unique_ptr<SetComposition::Params> parent_params( SetComposition::Params::Create(*args_)); @@ -372,7 +372,7 @@ ExtensionFunction::ResponseAction InputImeCommitTextFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (engine) { std::unique_ptr<CommitText::Params> parent_params( CommitText::Params::Create(*args_)); @@ -392,7 +392,7 @@ ExtensionFunction::ResponseAction InputImeSendKeyEventsFunction::Run() { InputImeEventRouter* event_router = GetInputImeEventRouter(Profile::FromBrowserContext(browser_context())); InputMethodEngineBase* engine = - event_router ? event_router->GetActiveEngine(extension_id()) : nullptr; + event_router ? event_router->GetEngineIfActive(extension_id()) : nullptr; if (!engine) return RespondNow(Error(kInputImeApiErrorEngineNotAvailable)); 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 78e9fce74fd..c3fc3b3344e 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 @@ -128,7 +128,7 @@ class InputImeEventRouterFactory { DISALLOW_COPY_AND_ASSIGN(InputImeEventRouterFactory); }; -class InputImeKeyEventHandledFunction : public UIThreadExtensionFunction { +class InputImeKeyEventHandledFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.keyEventHandled", INPUT_IME_KEYEVENTHANDLED) @@ -136,11 +136,11 @@ class InputImeKeyEventHandledFunction : public UIThreadExtensionFunction { protected: ~InputImeKeyEventHandledFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; -class InputImeSetCompositionFunction : public UIThreadExtensionFunction { +class InputImeSetCompositionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setComposition", INPUT_IME_SETCOMPOSITION) @@ -148,29 +148,29 @@ class InputImeSetCompositionFunction : public UIThreadExtensionFunction { protected: ~InputImeSetCompositionFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; -class InputImeCommitTextFunction : public UIThreadExtensionFunction { +class InputImeCommitTextFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.commitText", INPUT_IME_COMMITTEXT) protected: ~InputImeCommitTextFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; -class InputImeSendKeyEventsFunction : public UIThreadExtensionFunction { +class InputImeSendKeyEventsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.sendKeyEvents", INPUT_IME_SENDKEYEVENTS) protected: ~InputImeSendKeyEventsFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; 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 b3d868bd61e..697de915f2f 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 @@ -16,12 +16,12 @@ #include "chrome/browser/chromeos/login/lock/screen_locker.h" #include "chrome/browser/chromeos/login/session/user_session_manager.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/keyboard/chrome_keyboard_controller_client.h" #include "chrome/common/extensions/api/input_ime.h" #include "chrome/common/extensions/api/input_method_private.h" -#include "extensions/browser/extension_system.h" +#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" @@ -271,12 +271,12 @@ class ImeObserverChromeOS : public ui::ImeObserver { // events (e.g. runtime.onMessage) from its other pages. // This is to save memory for steady state Chrome OS on which the users // don't want any IME features. - extensions::ExtensionSystem* extension_system = - extensions::ExtensionSystem::Get(profile_); - if (extension_system) { + extensions::ExtensionRegistry* extension_registry = + extensions::ExtensionRegistry::Get(profile_); + if (extension_registry) { const extensions::Extension* extension = - extension_system->extension_service()->GetExtensionById( - extension_id_, false /* include_disabled */); + extension_registry->GetExtensionById( + extension_id_, extensions::ExtensionRegistry::ENABLED); if (!extension) return; extensions::ProcessManager* process_manager = @@ -370,12 +370,12 @@ class ImeObserverChromeOS : public ui::ImeObserver { namespace extensions { -InputMethodEngine* GetActiveEngine(Profile* profile, - const std::string& extension_id) { +InputMethodEngine* GetEngineIfActive(Profile* profile, + const std::string& extension_id) { InputImeEventRouter* event_router = GetInputImeEventRouter(profile); InputMethodEngine* engine = event_router ? static_cast<InputMethodEngine*>( - event_router->GetActiveEngine(extension_id)) + event_router->GetEngineIfActive(extension_id)) : nullptr; return engine; } @@ -468,7 +468,7 @@ InputMethodEngine* InputImeEventRouter::GetEngine( return (it != engine_map_.end()) ? it->second : nullptr; } -InputMethodEngineBase* InputImeEventRouter::GetActiveEngine( +InputMethodEngineBase* InputImeEventRouter::GetEngineIfActive( const std::string& extension_id) { std::map<std::string, InputMethodEngine*>::iterator it = engine_map_.find(extension_id); @@ -477,7 +477,7 @@ InputMethodEngineBase* InputImeEventRouter::GetActiveEngine( } ExtensionFunction::ResponseAction InputImeClearCompositionFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { return RespondNow(OneArgument(std::make_unique<base::Value>(false))); @@ -498,7 +498,7 @@ ExtensionFunction::ResponseAction InputImeClearCompositionFunction::Run() { } ExtensionFunction::ResponseAction InputImeHideInputViewFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) return RespondNow(NoArguments()); @@ -579,7 +579,7 @@ InputImeSetCandidateWindowPropertiesFunction::Run() { } ExtensionFunction::ResponseAction InputImeSetCandidatesFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { return RespondNow(OneArgument(std::make_unique<base::Value>(true))); @@ -616,7 +616,7 @@ ExtensionFunction::ResponseAction InputImeSetCandidatesFunction::Run() { } ExtensionFunction::ResponseAction InputImeSetCursorPositionFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) { return RespondNow(OneArgument(std::make_unique<base::Value>(false))); @@ -713,7 +713,7 @@ InputMethodPrivateNotifyImeMenuItemActivatedFunction::Run() { std::string active_extension_id = chromeos::extension_ime_util::GetExtensionIDFromInputMethodID( current_input_method.id()); - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), active_extension_id); if (!engine) return RespondNow(Error(kInputImeApiChromeOSErrorEngineNotAvailable)); @@ -728,7 +728,7 @@ InputMethodPrivateNotifyImeMenuItemActivatedFunction::Run() { ExtensionFunction::ResponseAction InputMethodPrivateGetCompositionBoundsFunction::Run() { - InputMethodEngine* engine = GetActiveEngine( + InputMethodEngine* engine = GetEngineIfActive( Profile::FromBrowserContext(browser_context()), extension_id()); if (!engine) return RespondNow(Error(kInputImeApiChromeOSErrorEngineNotAvailable)); @@ -760,7 +760,7 @@ void InputImeAPI::OnExtensionLoaded(content::BrowserContext* browser_context, // can receive the onActivate event to recover itself upon the // unexpected unload. InputMethodEngineBase* engine = - event_router->GetActiveEngine(extension->id()); + event_router->GetEngineIfActive(extension->id()); // When extension is unloaded unexpectedly and reloaded, OS doesn't pass // details.browser_context value in OnListenerAdded callback. So we need // to reactivate engine here. @@ -817,8 +817,8 @@ void InputImeAPI::OnListenerAdded(const EventListenerInfo& details) { if (!details.browser_context) return; InputMethodEngine* engine = - GetActiveEngine(Profile::FromBrowserContext(details.browser_context), - details.extension_id); + GetEngineIfActive(Profile::FromBrowserContext(details.browser_context), + details.extension_id); // Notifies the IME extension for IME ready with onActivate/onFocus events. if (engine) engine->Enable(engine->GetActiveComponentId()); 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 a20921c57d2..c07e7259450 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 @@ -21,7 +21,7 @@ class InputMethodEngine; namespace extensions { -class InputImeClearCompositionFunction : public UIThreadExtensionFunction { +class InputImeClearCompositionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.clearComposition", INPUT_IME_CLEARCOMPOSITION) @@ -33,8 +33,7 @@ class InputImeClearCompositionFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeSetCandidateWindowPropertiesFunction - : public UIThreadExtensionFunction { +class InputImeSetCandidateWindowPropertiesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCandidateWindowProperties", INPUT_IME_SETCANDIDATEWINDOWPROPERTIES) @@ -46,7 +45,7 @@ class InputImeSetCandidateWindowPropertiesFunction ResponseAction Run() override; }; -class InputImeSetCandidatesFunction : public UIThreadExtensionFunction { +class InputImeSetCandidatesFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCandidates", INPUT_IME_SETCANDIDATES) @@ -57,7 +56,7 @@ class InputImeSetCandidatesFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeSetCursorPositionFunction : public UIThreadExtensionFunction { +class InputImeSetCursorPositionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setCursorPosition", INPUT_IME_SETCURSORPOSITION) @@ -69,7 +68,7 @@ class InputImeSetCursorPositionFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeSetMenuItemsFunction : public UIThreadExtensionFunction { +class InputImeSetMenuItemsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.setMenuItems", INPUT_IME_SETMENUITEMS) @@ -80,7 +79,7 @@ class InputImeSetMenuItemsFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeUpdateMenuItemsFunction : public UIThreadExtensionFunction { +class InputImeUpdateMenuItemsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.updateMenuItems", INPUT_IME_UPDATEMENUITEMS) @@ -92,7 +91,7 @@ class InputImeUpdateMenuItemsFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeDeleteSurroundingTextFunction : public UIThreadExtensionFunction { +class InputImeDeleteSurroundingTextFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.deleteSurroundingText", INPUT_IME_DELETESURROUNDINGTEXT) @@ -103,7 +102,7 @@ class InputImeDeleteSurroundingTextFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class InputImeHideInputViewFunction : public UIThreadExtensionFunction { +class InputImeHideInputViewFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.hideInputView", INPUT_IME_HIDEINPUTVIEW) @@ -111,19 +110,19 @@ class InputImeHideInputViewFunction : public UIThreadExtensionFunction { protected: ~InputImeHideInputViewFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; class InputMethodPrivateNotifyImeMenuItemActivatedFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: InputMethodPrivateNotifyImeMenuItemActivatedFunction() {} protected: ~InputMethodPrivateNotifyImeMenuItemActivatedFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -134,7 +133,7 @@ class InputMethodPrivateNotifyImeMenuItemActivatedFunction }; class InputMethodPrivateGetCompositionBoundsFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("inputMethodPrivate.getCompositionBounds", INPUTMETHODPRIVATE_GETCOMPOSITIONBOUNDS) @@ -157,7 +156,7 @@ class InputImeEventRouter : public InputImeEventRouterBase { void UnregisterAllImes(const std::string& extension_id); chromeos::InputMethodEngine* GetEngine(const std::string& extension_id); - input_method::InputMethodEngineBase* GetActiveEngine( + input_method::InputMethodEngineBase* GetEngineIfActive( const std::string& extension_id) override; std::string GetUnloadedExtensionId() const { diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc index 112b9cc3f87..95a52f9e403 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.cc @@ -122,13 +122,13 @@ class ImeObserverNonChromeOS : public ui::ImeObserver { namespace extensions { -InputMethodEngine* GetActiveEngine(content::BrowserContext* browser_context, - const std::string& extension_id) { +InputMethodEngine* GetEngineIfActive(content::BrowserContext* browser_context, + const std::string& extension_id) { Profile* profile = Profile::FromBrowserContext(browser_context); InputImeEventRouter* event_router = GetInputImeEventRouter(profile); InputMethodEngine* engine = event_router ? static_cast<InputMethodEngine*>( - event_router->GetActiveEngine(extension_id)) + event_router->GetEngineIfActive(extension_id)) : nullptr; return engine; } @@ -174,7 +174,7 @@ InputImeEventRouter::~InputImeEventRouter() { DeleteInputMethodEngine(active_engine_->GetExtensionId()); } -InputMethodEngineBase* InputImeEventRouter::GetActiveEngine( +InputMethodEngineBase* InputImeEventRouter::GetEngineIfActive( const std::string& extension_id) { return (ui::IMEBridge::Get()->GetCurrentEngineHandler() && active_engine_ && @@ -324,7 +324,7 @@ void InputImeActivateFunction::OnPermissionBubbleFinished( ExtensionFunction::ResponseAction InputImeDeactivateFunction::Run() { InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); ui::IMEBridge::Get()->SetCurrentEngineHandler(nullptr); if (engine) engine->CloseImeWindows(); @@ -352,7 +352,7 @@ ExtensionFunction::ResponseAction InputImeCreateWindowFunction::Run() { } InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); if (!engine) return RespondNow(Error(kErrorNoActiveEngine)); @@ -375,7 +375,7 @@ ExtensionFunction::ResponseAction InputImeCreateWindowFunction::Run() { ExtensionFunction::ResponseAction InputImeShowWindowFunction::Run() { InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); if (!engine) return RespondNow(Error(kErrorNoActiveEngine)); @@ -388,7 +388,7 @@ ExtensionFunction::ResponseAction InputImeShowWindowFunction::Run() { ExtensionFunction::ResponseAction InputImeHideWindowFunction::Run() { InputMethodEngine* engine = - GetActiveEngine(browser_context(), extension_id()); + GetEngineIfActive(browser_context(), extension_id()); if (!engine) return RespondNow(Error(kErrorNoActiveEngine)); diff --git a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h index da76c4637c6..68e06c59d6a 100644 --- a/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h +++ b/chromium/chrome/browser/extensions/api/input_ime/input_ime_api_nonchromeos.h @@ -34,7 +34,7 @@ class InputImeEventRouter : public InputImeEventRouterBase { ~InputImeEventRouter() override; // Gets the input method engine if the extension is active. - input_method::InputMethodEngineBase* GetActiveEngine( + input_method::InputMethodEngineBase* GetEngineIfActive( const std::string& extension_id) override; // Actives the extension with new input method engine, and deletes the @@ -55,7 +55,7 @@ class InputImeEventRouter : public InputImeEventRouterBase { DISALLOW_COPY_AND_ASSIGN(InputImeEventRouter); }; -class InputImeCreateWindowFunction : public UIThreadExtensionFunction { +class InputImeCreateWindowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.createWindow", INPUT_IME_CREATEWINDOW) @@ -66,7 +66,7 @@ class InputImeCreateWindowFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class InputImeShowWindowFunction : public UIThreadExtensionFunction { +class InputImeShowWindowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.showWindow", INPUT_IME_SHOWWINDOW) @@ -77,7 +77,7 @@ class InputImeShowWindowFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class InputImeHideWindowFunction : public UIThreadExtensionFunction { +class InputImeHideWindowFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.hideWindow", INPUT_IME_HIDEWINDOW) @@ -88,7 +88,7 @@ class InputImeHideWindowFunction : public UIThreadExtensionFunction { ExtensionFunction::ResponseAction Run() override; }; -class InputImeActivateFunction : public UIThreadExtensionFunction { +class InputImeActivateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.activate", INPUT_IME_ACTIVATE) @@ -99,7 +99,7 @@ class InputImeActivateFunction : public UIThreadExtensionFunction { protected: ~InputImeActivateFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; private: @@ -109,14 +109,14 @@ class InputImeActivateFunction : public UIThreadExtensionFunction { void OnPermissionBubbleFinished(ImeWarningBubblePermissionStatus status); }; -class InputImeDeactivateFunction : public UIThreadExtensionFunction { +class InputImeDeactivateFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("input.ime.deactivate", INPUT_IME_DEACTIVATE) protected: ~InputImeDeactivateFunction() override {} - // UIThreadExtensionFunction: + // ExtensionFunction: ResponseAction Run() override; }; 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 132a6a679bc..6e575c382b7 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 @@ -22,7 +22,7 @@ class InputImeEventRouterBase { virtual ~InputImeEventRouterBase(); // Gets the input method engine if the extension is active. - virtual input_method::InputMethodEngineBase* GetActiveEngine( + virtual input_method::InputMethodEngineBase* GetEngineIfActive( const std::string& extension_id) = 0; Profile* GetProfile() const { return profile_; } 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 1f6eb29db33..15ab8552a61 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 @@ -132,7 +132,7 @@ ExtensionFunction::ResponseAction InstanceIDGetTokenFunction::DoWork() { GetInstanceID()->GetToken( params->get_token_params.authorized_entity, params->get_token_params.scope, options, - /*is_lazy=*/false, + /*flags=*/{}, base::Bind(&InstanceIDGetTokenFunction::GetTokenCompleted, this)); return RespondLater(); 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 ffd49612b85..33a0bb0dba5 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 @@ -11,7 +11,7 @@ namespace extensions { -class InstanceIDApiFunction : public UIThreadExtensionFunction { +class InstanceIDApiFunction : public ExtensionFunction { public: InstanceIDApiFunction(); 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 125a7777f72..3e82ec740d5 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 @@ -35,7 +35,9 @@ #include "components/language/core/browser/pref_names.h" #include "components/language/core/common/language_util.h" #include "components/language/core/common/locale_util.h" +#include "components/spellcheck/browser/spellcheck_platform.h" #include "components/spellcheck/common/spellcheck_common.h" +#include "components/spellcheck/common/spellcheck_features.h" #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" @@ -292,6 +294,7 @@ LanguageSettingsPrivateEnableLanguageFunction::Run() { } translate_prefs->AddToLanguageList(language_code, /*force_blocked=*/false); + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -325,6 +328,7 @@ LanguageSettingsPrivateDisableLanguageFunction::Run() { } translate_prefs->RemoveFromLanguageList(language_code); + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -354,6 +358,7 @@ LanguageSettingsPrivateSetEnableTranslationForLanguageFunction::Run() { } else { translate_prefs->BlockLanguage(language_code); } + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -406,6 +411,7 @@ LanguageSettingsPrivateMoveLanguageFunction::Run() { const int offset = 1; translate_prefs->RearrangeLanguage(language_code, where, offset, supported_language_codes); + translate_prefs->ResetRecentTargetLanguage(); return RespondNow(NoArguments()); } @@ -495,6 +501,12 @@ LanguageSettingsPrivateAddSpellcheckWordFunction::Run() { SpellcheckServiceFactory::GetForContext(browser_context()); bool success = service->GetCustomDictionary()->AddWord(params->word); +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) + if (spellcheck::UseBrowserSpellChecker()) { + spellcheck_platform::AddWord(base::UTF8ToUTF16(params->word)); + } +#endif + return RespondNow(OneArgument(std::make_unique<base::Value>(success))); } @@ -514,6 +526,12 @@ LanguageSettingsPrivateRemoveSpellcheckWordFunction::Run() { SpellcheckServiceFactory::GetForContext(browser_context()); bool success = service->GetCustomDictionary()->RemoveWord(params->word); +#if BUILDFLAG(USE_BROWSER_SPELLCHECKER) + if (spellcheck::UseBrowserSpellChecker()) { + spellcheck_platform::RemoveWord(base::UTF8ToUTF16(params->word)); + } +#endif + return RespondNow(OneArgument(std::make_unique<base::Value>(success))); } 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 951f544fa7e..2e745eb503b 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 @@ -14,7 +14,7 @@ namespace extensions { // Implements the languageSettingsPrivate.getLanguageList method. class LanguageSettingsPrivateGetLanguageListFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetLanguageListFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.getLanguageList", @@ -33,8 +33,7 @@ class LanguageSettingsPrivateGetLanguageListFunction }; // Implements the languageSettingsPrivate.enableLanguage method. -class LanguageSettingsPrivateEnableLanguageFunction - : public UIThreadExtensionFunction { +class LanguageSettingsPrivateEnableLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateEnableLanguageFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.enableLanguage", @@ -54,7 +53,7 @@ class LanguageSettingsPrivateEnableLanguageFunction // Implements the languageSettingsPrivate.disableLanguage method. class LanguageSettingsPrivateDisableLanguageFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateDisableLanguageFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.disableLanguage", @@ -75,7 +74,7 @@ class LanguageSettingsPrivateDisableLanguageFunction // Implements the languageSettingsPrivate.setEnableTranslationForLanguage // method. class LanguageSettingsPrivateSetEnableTranslationForLanguageFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateSetEnableTranslationForLanguageFunction(); DECLARE_EXTENSION_FUNCTION( @@ -95,8 +94,7 @@ class LanguageSettingsPrivateSetEnableTranslationForLanguageFunction }; // Implements the languageSettingsPrivate.moveLanguage method. -class LanguageSettingsPrivateMoveLanguageFunction - : public UIThreadExtensionFunction { +class LanguageSettingsPrivateMoveLanguageFunction : public ExtensionFunction { public: LanguageSettingsPrivateMoveLanguageFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.moveLanguage", @@ -116,7 +114,7 @@ class LanguageSettingsPrivateMoveLanguageFunction // Implements the languageSettingsPrivate.getSpellcheckDictionaryStatuses // method. class LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction(); DECLARE_EXTENSION_FUNCTION( @@ -136,7 +134,7 @@ class LanguageSettingsPrivateGetSpellcheckDictionaryStatusesFunction // Implements the languageSettingsPrivate.getSpellcheckWords method. class LanguageSettingsPrivateGetSpellcheckWordsFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public SpellcheckCustomDictionary::Observer { public: LanguageSettingsPrivateGetSpellcheckWordsFunction(); @@ -163,7 +161,7 @@ class LanguageSettingsPrivateGetSpellcheckWordsFunction // Implements the languageSettingsPrivate.addSpellcheckWord method. class LanguageSettingsPrivateAddSpellcheckWordFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateAddSpellcheckWordFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.addSpellcheckWord", @@ -181,7 +179,7 @@ class LanguageSettingsPrivateAddSpellcheckWordFunction // Implements the languageSettingsPrivate.removeSpellcheckWord method. class LanguageSettingsPrivateRemoveSpellcheckWordFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateRemoveSpellcheckWordFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.removeSpellcheckWord", @@ -199,7 +197,7 @@ class LanguageSettingsPrivateRemoveSpellcheckWordFunction // Implements the languageSettingsPrivate.getTranslateTargetLanguage method. class LanguageSettingsPrivateGetTranslateTargetLanguageFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetTranslateTargetLanguageFunction(); DECLARE_EXTENSION_FUNCTION( @@ -221,7 +219,7 @@ class LanguageSettingsPrivateGetTranslateTargetLanguageFunction // Implements the languageSettingsPrivate.getInputMethodLists method. class LanguageSettingsPrivateGetInputMethodListsFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateGetInputMethodListsFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.getInputMethodLists", @@ -238,8 +236,7 @@ class LanguageSettingsPrivateGetInputMethodListsFunction }; // Implements the languageSettingsPrivate.addInputMethod method. -class LanguageSettingsPrivateAddInputMethodFunction - : public UIThreadExtensionFunction { +class LanguageSettingsPrivateAddInputMethodFunction : public ExtensionFunction { public: LanguageSettingsPrivateAddInputMethodFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.addInputMethod", @@ -259,7 +256,7 @@ class LanguageSettingsPrivateAddInputMethodFunction // Implements the languageSettingsPrivate.removeInputMethod method. class LanguageSettingsPrivateRemoveInputMethodFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateRemoveInputMethodFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.removeInputMethod", @@ -279,7 +276,7 @@ class LanguageSettingsPrivateRemoveInputMethodFunction // Implements the languageSettingsPrivate.retryDownloadDictionary method. class LanguageSettingsPrivateRetryDownloadDictionaryFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: LanguageSettingsPrivateRetryDownloadDictionaryFunction(); DECLARE_EXTENSION_FUNCTION("languageSettingsPrivate.retryDownloadDictionary", 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 eb9da3ee60f..9dd95841737 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 @@ -9,8 +9,11 @@ #include "base/bind.h" #include "base/macros.h" +#include "base/strings/strcat.h" #include "base/strings/utf_string_conversions.h" #include "base/task/post_task.h" +#include "chrome/browser/apps/app_service/app_launch_params.h" +#include "chrome/browser/apps/launch_service/launch_service.h" #include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/launch_util.h" @@ -24,14 +27,13 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" -#include "chrome/browser/ui/extensions/app_launch_params.h" -#include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/scoped_tabbed_browser_displayer.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/app_registrar.h" #include "chrome/browser/web_applications/components/install_manager.h" #include "chrome/browser/web_applications/components/web_app_constants.h" +#include "chrome/browser/web_applications/components/web_app_install_utils.h" #include "chrome/browser/web_applications/components/web_app_provider_base.h" #include "chrome/browser/web_applications/components/web_app_utils.h" #include "chrome/common/extensions/extension_metrics.h" @@ -51,16 +53,59 @@ #include "services/data_decoder/public/cpp/safe_json_parser.h" #if defined(OS_CHROMEOS) +#include "chrome/browser/chromeos/arc/arc_util.h" #include "chrome/browser/chromeos/login/demo_mode/demo_session.h" -#endif +#include "chrome/browser/ui/app_list/arc/arc_app_utils.h" +#include "components/arc/arc_service_manager.h" +#include "components/arc/arc_util.h" +#include "components/arc/mojom/intent_helper.mojom.h" +#include "components/arc/session/arc_bridge_service.h" +#endif // OS_CHROMEOS namespace { +#if defined(OS_CHROMEOS) +const char kPlayIntentPrefix[] = + "https://play.google.com/store/apps/details?id="; +const char kChromeWebStoreReferrer[] = "&referrer=chrome_web_store"; +#endif // OS_CHROMEOS + +using InstallAndroidAppCallback = + extensions::ManagementAPIDelegate::InstallAndroidAppCallback; +using AndroidAppInstallStatusCallback = + extensions::ManagementAPIDelegate::AndroidAppInstallStatusCallback; using InstallWebAppCallback = extensions::ManagementAPIDelegate::InstallWebAppCallback; using InstallWebAppResult = extensions::ManagementAPIDelegate::InstallWebAppResult; +#if defined(OS_CHROMEOS) +void OnDidCheckForIntentToPlayStore(const std::string& intent, + InstallAndroidAppCallback callback, + bool installable) { + if (!installable) { + std::move(callback).Run(false); + return; + } + + auto* arc_service_manager = arc::ArcServiceManager::Get(); + if (!arc_service_manager) { + std::move(callback).Run(false); + return; + } + + auto* instance = ARC_GET_INSTANCE_FOR_METHOD( + arc_service_manager->arc_bridge_service()->intent_helper(), HandleUrl); + if (!instance) { + std::move(callback).Run(false); + return; + } + + instance->HandleUrl(intent, arc::kPlayStorePackage); + std::move(callback).Run(true); +} +#endif // OS_CHROMEOS + class ManagementSetEnabledFunctionInstallPromptDelegate : public extensions::InstallPromptDelegate { public: @@ -160,7 +205,8 @@ void OnGenerateAppForLinkCompleted( extensions::ManagementGenerateAppForLinkFunction* function, const web_app::AppId& app_id, web_app::InstallResultCode code) { - const bool install_success = code == web_app::InstallResultCode::kSuccess; + const bool install_success = + code == web_app::InstallResultCode::kSuccessNewInstall; function->FinishCreateWebApp(app_id, install_success); } @@ -178,6 +224,7 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { auto web_app_info = std::make_unique<WebApplicationInfo>(); web_app_info->title = base::UTF8ToUTF16(title); web_app_info->app_url = launch_url; + web_app_info->open_as_window = false; if (!image_result.image.IsEmpty()) { WebApplicationInfo::IconInfo icon; @@ -192,7 +239,7 @@ class ChromeAppForLinkDelegate : public extensions::AppForLinkDelegate { DCHECK(provider); provider->install_manager().InstallWebAppFromInfo( - std::move(web_app_info), /*no_network_install=*/false, + std::move(web_app_info), web_app::ForInstallableSite::kNo, WebappInstallSource::MANAGEMENT_API, base::BindOnce(OnGenerateAppForLinkCompleted, base::RetainedRef(function))); @@ -212,7 +259,7 @@ void OnWebAppInstallCompleted(InstallWebAppCallback callback, // TODO(loyso): Update this when more of the web_app::InstallResultCodes are // actually set. switch (code) { - case web_app::InstallResultCode::kSuccess: + case web_app::InstallResultCode::kSuccessNewInstall: result = InstallWebAppResult::kSuccess; break; default: @@ -257,10 +304,11 @@ void ChromeManagementAPIDelegate::LaunchAppFunctionDelegate( // returned. extensions::LaunchContainer launch_container = GetLaunchContainer(extensions::ExtensionPrefs::Get(context), extension); - OpenApplication(AppLaunchParams( - Profile::FromBrowserContext(context), extension->id(), launch_container, - WindowOpenDisposition::NEW_FOREGROUND_TAB, - extensions::AppLaunchSource::kSourceManagementApi)); + Profile* profile = Profile::FromBrowserContext(context); + apps::LaunchService::Get(profile)->OpenApplication( + AppLaunchParams(profile, extension->id(), launch_container, + WindowOpenDisposition::NEW_FOREGROUND_TAB, + apps::mojom::AppLaunchSource::kSourceManagementApi)); #if defined(OS_CHROMEOS) chromeos::DemoSession::RecordAppLaunchSourceIfInDemoMode( @@ -369,7 +417,7 @@ bool ChromeManagementAPIDelegate::IsWebAppInstalled( auto* provider = web_app::WebAppProviderBase::GetProviderBase( Profile::FromBrowserContext(context)); DCHECK(provider); - return provider->registrar().IsInstalled(web_app_url); + return provider->registrar().IsLocallyInstalled(web_app_url); } bool ChromeManagementAPIDelegate::CanContextInstallWebApps( @@ -391,6 +439,66 @@ void ChromeManagementAPIDelegate::InstallReplacementWebApp( std::move(callback))); } +bool ChromeManagementAPIDelegate::CanContextInstallAndroidApps( + content::BrowserContext* context) const { +#if defined(OS_CHROMEOS) + return arc::IsArcAllowedForProfile(Profile::FromBrowserContext(context)); +#else + return false; +#endif // defined(OS_CHROMEOS) +} + +void ChromeManagementAPIDelegate::CheckAndroidAppInstallStatus( + const std::string& package_name, + AndroidAppInstallStatusCallback callback) const { +#if defined(OS_CHROMEOS) + auto* arc_service_manager = arc::ArcServiceManager::Get(); + if (!arc_service_manager) { + std::move(callback).Run(false); + return; + } + + auto* instance = ARC_GET_INSTANCE_FOR_METHOD( + arc_service_manager->arc_bridge_service()->app(), IsInstallable); + if (!instance) { + std::move(callback).Run(false); + return; + } + + instance->IsInstallable(package_name, std::move(callback)); +#else + std::move(callback).Run(false); +#endif // OS_CHROMEOS +} + +void ChromeManagementAPIDelegate::InstallReplacementAndroidApp( + const std::string& package_name, + InstallAndroidAppCallback callback) const { +#if defined(OS_CHROMEOS) + std::string intent = + base::StrCat({kPlayIntentPrefix, package_name, kChromeWebStoreReferrer}); + + auto* arc_service_manager = arc::ArcServiceManager::Get(); + if (!arc_service_manager) { + std::move(callback).Run(false); + return; + } + + auto* instance = ARC_GET_INSTANCE_FOR_METHOD( + arc_service_manager->arc_bridge_service()->app(), IsInstallable); + if (!instance) { + std::move(callback).Run(false); + return; + } + + instance->IsInstallable( + package_name, base::BindOnce(&OnDidCheckForIntentToPlayStore, intent, + std::move(callback))); +#else + std::move(callback).Run(false); +#endif // defined(OS_CHROMEOS) +} + void ChromeManagementAPIDelegate::EnableExtension( content::BrowserContext* context, const std::string& extension_id) const { diff --git a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h index 8088380e0bb..83587591a41 100644 --- a/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h +++ b/chromium/chrome/browser/extensions/api/management/chrome_management_api_delegate.h @@ -54,6 +54,15 @@ class ChromeManagementAPIDelegate : public extensions::ManagementAPIDelegate { content::BrowserContext* context, const GURL& web_app_url, ManagementAPIDelegate::InstallWebAppCallback callback) const override; + bool CanContextInstallAndroidApps( + content::BrowserContext* context) const override; + void CheckAndroidAppInstallStatus( + const std::string& package_name, + ManagementAPIDelegate::AndroidAppInstallStatusCallback callback) + const override; + void InstallReplacementAndroidApp( + const std::string& package_name, + ManagementAPIDelegate::InstallAndroidAppCallback callback) const override; void EnableExtension(content::BrowserContext* context, const std::string& extension_id) const override; void DisableExtension( 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 16f29ac9da4..93f3c8d8979 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc @@ -26,7 +26,7 @@ #include "extensions/browser/extension_dialog_auto_confirm.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/notification_types.h" #include "extensions/common/extension_builder.h" #include "extensions/test/extension_test_message_listener.h" @@ -243,17 +243,17 @@ class ExtensionManagementApiEscalationTest : scoped_temp_dir_.GetPath().AppendASCII("permissions2.crx"), pem_path, base::FilePath()); - ExtensionService* service = ExtensionSystem::Get(browser()->profile())-> - extension_service(); - // Install low-permission version of the extension. ASSERT_TRUE(InstallExtension(path_v1, 1)); - EXPECT_TRUE(service->GetExtensionById(kId, false) != NULL); + EXPECT_TRUE(extension_registry()->GetExtensionById( + kId, ExtensionRegistry::ENABLED)); // Update to a high-permission version - it should get disabled. EXPECT_FALSE(UpdateExtension(kId, path_v2, -1)); - EXPECT_TRUE(service->GetExtensionById(kId, false) == NULL); - EXPECT_TRUE(service->GetExtensionById(kId, true) != NULL); + EXPECT_FALSE(extension_registry()->GetExtensionById( + kId, ExtensionRegistry::ENABLED)); + EXPECT_TRUE(extension_registry()->GetExtensionById( + kId, ExtensionRegistry::COMPATIBILITY)); EXPECT_TRUE(ExtensionPrefs::Get(browser()->profile()) ->DidExtensionEscalatePermissions(kId)); } @@ -344,14 +344,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiEscalationTest, // Register the target extension with extension service. scoped_refptr<const Extension> target_extension = ExtensionBuilder("TargetExtension").SetID(kId).Build(); - ExtensionService* const service = - ExtensionSystem::Get(browser()->profile())->extension_service(); - service->AddExtension(target_extension.get()); + extension_service()->AddExtension(target_extension.get()); SetEnabled(false, true, std::string(), source_extension); SetEnabled(true, true, std::string(), source_extension); - const Extension* extension = ExtensionSystem::Get(browser()->profile()) - ->extension_service() - ->GetExtensionById(kId, false); + const Extension* extension = + extension_registry()->GetExtensionById(kId, ExtensionRegistry::ENABLED); EXPECT_TRUE(extension); } } 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 af20dd95ad9..febd21f6435 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 @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +#include "chrome/browser/extensions/browsertest_util.h" #include "chrome/browser/extensions/extension_action_runner.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/test/base/ui_test_utils.h" @@ -14,26 +15,7 @@ namespace extensions { -namespace { -enum class ContextType { - kEventPage, - kServiceWorker, -}; - -// Returns the newly added WebContents. -// TODO(lazyboy): We have at least 3 versions of this AddTab within -// //extensions, put this in a central place and use that instead. -content::WebContents* AddTab(Browser* browser, const GURL& url) { - int starting_tab_count = browser->tab_strip_model()->count(); - ui_test_utils::NavigateToURLWithDisposition( - browser, url, WindowOpenDisposition::NEW_FOREGROUND_TAB, - ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); - int tab_count = browser->tab_strip_model()->count(); - EXPECT_EQ(starting_tab_count + 1, tab_count); - return browser->tab_strip_model()->GetActiveWebContents(); -} - -} // namespace +using ContextType = ExtensionBrowserTest::ContextType; // Tests management API from a non-persistent extension (event page or // Service Worker). @@ -82,10 +64,7 @@ IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, UninstallSelf) { extensions::ExtensionRegistry::Get(browser()->profile())); base::FilePath path = test_dir.Pack(); - // NOTE: Do not use a scoped_refptr<Extension> as the |extension| might get - // uninstalled right away. - const Extension* extension = LoadExtension(path); - + scoped_refptr<const Extension> extension = LoadExtension(path); EXPECT_EQ(extension, observer.WaitForExtensionUninstalled()); } @@ -124,7 +103,8 @@ IN_PROC_BROWSER_TEST_P(ManagementApiNonPersistentApiTest, // Click on browser action to start the test, |extension_a| will uninstall // |extension_b|. { - content::WebContents* web_contents = AddTab(browser(), GURL("about:blank")); + content::WebContents* web_contents = + browsertest_util::AddTab(browser(), GURL("about:blank")); ASSERT_TRUE(web_contents); ExtensionActionRunner::GetForWebContents( browser()->tab_strip_model()->GetActiveWebContents()) 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 9b7ea704b0e..5f753cc87b3 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc @@ -62,7 +62,7 @@ class ManagementApiUnitTest : public ExtensionServiceTestWithInstall { // A wrapper around extension_function_test_utils::RunFunction that runs with // the associated browser, no flags, and can take stack-allocated arguments. - bool RunFunction(const scoped_refptr<UIThreadExtensionFunction>& function, + bool RunFunction(const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args); Browser* browser() { return browser_.get(); } @@ -80,7 +80,7 @@ class ManagementApiUnitTest : public ExtensionServiceTestWithInstall { }; bool ManagementApiUnitTest::RunFunction( - const scoped_refptr<UIThreadExtensionFunction>& function, + const scoped_refptr<ExtensionFunction>& function, const base::ListValue& args) { return extension_function_test_utils::RunFunction( function.get(), base::WrapUnique(args.DeepCopy()), browser(), @@ -98,7 +98,7 @@ void ManagementApiUnitTest::SetUp() { browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); } @@ -271,7 +271,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstall) { ScopedTestDialogAutoConfirm::ACCEPT); // Uninstall requires a user gesture, so this should fail. - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); EXPECT_FALSE(RunFunction(function, uninstall_args)); EXPECT_EQ(std::string(constants::kGestureNeededForUninstallError), @@ -295,7 +295,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstall) { ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; service()->AddExtension(extension.get()); - scoped_refptr<UIThreadExtensionFunction> function = + scoped_refptr<ExtensionFunction> function = new ManagementUninstallFunction(); EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id)); EXPECT_FALSE(RunFunction(function, uninstall_args)); @@ -347,7 +347,7 @@ TEST_F(ManagementApiUnitTest, ManagementWebStoreUninstall) { ScopedTestDialogAutoConfirm::CANCEL); ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); function->set_extension(triggering_extension); EXPECT_TRUE(registry()->enabled_extensions().Contains(extension_id)); @@ -360,7 +360,7 @@ TEST_F(ManagementApiUnitTest, ManagementWebStoreUninstall) { } { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); function->set_extension(triggering_extension); @@ -397,7 +397,7 @@ TEST_F(ManagementApiUnitTest, ManagementProgrammaticUninstall) { base::ListValue uninstall_args; uninstall_args.AppendString(extension->id()); { - scoped_refptr<UIThreadExtensionFunction> function( + scoped_refptr<ExtensionFunction> function( new ManagementUninstallFunction()); function->set_extension(triggering_extension); @@ -435,8 +435,7 @@ TEST_F(ManagementApiUnitTest, ManagementUninstallBlacklisted) { ScopedTestDialogAutoConfirm auto_confirm(ScopedTestDialogAutoConfirm::ACCEPT); ExtensionFunction::ScopedUserGestureForTests scoped_user_gesture; - scoped_refptr<UIThreadExtensionFunction> function( - new ManagementUninstallFunction()); + scoped_refptr<ExtensionFunction> function(new ManagementUninstallFunction()); base::ListValue uninstall_args; uninstall_args.AppendString(id); EXPECT_TRUE(RunFunction(function, uninstall_args)) << function->GetError(); @@ -452,7 +451,7 @@ TEST_F(ManagementApiUnitTest, ManagementEnableOrDisableBlacklisted) { service()->BlacklistExtensionForTest(id); EXPECT_NE(nullptr, registry()->GetInstalledExtension(id)); - scoped_refptr<UIThreadExtensionFunction> function; + scoped_refptr<ExtensionFunction> function; // Test enabling it. { @@ -486,7 +485,7 @@ TEST_F(ManagementApiUnitTest, ExtensionInfo_MayEnable) { const std::string args = base::StringPrintf("[\"%s\"]", extension->id().c_str()); - scoped_refptr<UIThreadExtensionFunction> function; + scoped_refptr<ExtensionFunction> function; // Initially the extension should show as enabled. 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 b9b4b8e09b0..bbc3cb9f617 100644 --- a/chromium/chrome/browser/extensions/api/management/management_apitest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_apitest.cc @@ -22,6 +22,7 @@ #include "chrome/common/extensions/extension_constants.h" #include "extensions/browser/api/management/management_api.h" #include "extensions/browser/extension_dialog_auto_confirm.h" +#include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/test_management_policy.h" #include "extensions/common/manifest.h" @@ -281,10 +282,10 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, InstallableWebApp) { auto* provider = web_app::WebAppProviderBase::GetProviderBase(browser()->profile()); - EXPECT_FALSE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_FALSE(provider->registrar().IsLocallyInstalled(good_web_app_url)); RunTest(kManifest, kGoodWebAppURL, kBackground, true /* from_webstore */); - EXPECT_TRUE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_TRUE(provider->registrar().IsLocallyInstalled(good_web_app_url)); chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false); } @@ -318,10 +319,10 @@ IN_PROC_BROWSER_TEST_F(InstallReplacementWebAppApiTest, auto* provider = web_app::WebAppProviderBase::GetProviderBase(browser()->profile()); - EXPECT_FALSE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_FALSE(provider->registrar().IsLocallyInstalled(good_web_app_url)); RunTest(kAppManifest, kGoodWebAppURL, kBackground, true /* from_webstore */); - EXPECT_TRUE(provider->registrar().IsInstalled(good_web_app_url)); + EXPECT_TRUE(provider->registrar().IsLocallyInstalled(good_web_app_url)); chrome::SetAutoAcceptPWAInstallConfirmationForTesting(false); } @@ -337,11 +338,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LoadExtensions(); extensions::ScopedTestDialogAutoConfirm auto_confirm( extensions::ScopedTestDialogAutoConfirm::ACCEPT); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - EXPECT_TRUE(service->GetExtensionById(extension_ids_["enabled_extension"], - false)); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); + EXPECT_TRUE( + registry->GetExtensionById(extension_ids_["enabled_extension"], + extensions::ExtensionRegistry::ENABLED)); // Ensure that all actions are allowed. extensions::ExtensionSystem::Get( @@ -350,8 +351,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, ASSERT_TRUE(RunExtensionSubtest("management/management_policy", "allowed.html")); // The last thing the test does is uninstall the "enabled_extension". - EXPECT_FALSE(service->GetExtensionById(extension_ids_["enabled_extension"], - true)); + EXPECT_FALSE( + registry->GetExtensionById(extension_ids_["enabled_extension"], + extensions::ExtensionRegistry::COMPATIBILITY)); } // Fails often on Windows dbg bots. http://crbug.com/177163 @@ -364,11 +366,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_ManagementPolicyProhibited) { LoadExtensions(); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - EXPECT_TRUE(service->GetExtensionById(extension_ids_["enabled_extension"], - false)); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); + EXPECT_TRUE( + registry->GetExtensionById(extension_ids_["enabled_extension"], + extensions::ExtensionRegistry::ENABLED)); // Prohibit status changes. extensions::ManagementPolicy* policy = extensions::ExtensionSystem::Get( @@ -382,10 +384,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, } IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - // Load an extension that calls launchApp() on any app that gets // installed. ExtensionTestMessageListener launcher_loaded("launcher loaded", false); @@ -401,16 +399,18 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { // Find the app's browser. Check that it is a popup. ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile())); Browser* app_browser = FindOtherBrowser(browser()); - ASSERT_TRUE(app_browser->is_type_popup()); - ASSERT_TRUE(app_browser->is_app()); + ASSERT_TRUE(app_browser->is_type_app()); // Close the app panel. CloseBrowserSynchronously(app_browser); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); // Unload the extension. UninstallExtension(app_id); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); - ASSERT_FALSE(service->GetExtensionById(app_id, true)); + ASSERT_FALSE(registry->GetExtensionById( + app_id, extensions::ExtensionRegistry::COMPATIBILITY)); // Set a pref indicating that the user wants to launch in a regular tab. // This should be ignored, because panel apps always load in a popup. @@ -429,8 +429,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { // prefs, so we should still see the launch in a popup. ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile())); app_browser = FindOtherBrowser(browser()); - ASSERT_TRUE(app_browser->is_type_popup()); - ASSERT_TRUE(app_browser->is_app()); + ASSERT_TRUE(app_browser->is_type_app()); } // Disabled: crbug.com/230165, crbug.com/915339, crbug.com/979399 @@ -442,10 +441,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, LaunchPanelApp) { #endif IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchTabApp) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - // Load an extension that calls launchApp() on any app that gets // installed. ExtensionTestMessageListener launcher_loaded("launcher loaded", false); @@ -467,10 +462,13 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchTabApp) { ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); ASSERT_EQ(2, browser()->tab_strip_model()->count()); + extensions::ExtensionRegistry* registry = + extensions::ExtensionRegistry::Get(browser()->profile()); // Unload the extension. UninstallExtension(app_id); ASSERT_EQ(1u, chrome::GetBrowserCount(browser()->profile())); - ASSERT_FALSE(service->GetExtensionById(app_id, true)); + ASSERT_FALSE(registry->GetExtensionById( + app_id, extensions::ExtensionRegistry::COMPATIBILITY)); // Set a pref indicating that the user wants to launch in a window. extensions::SetLaunchType(browser()->profile(), app_id, @@ -487,7 +485,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementApiTest, MAYBE_LaunchTabApp) { // a new browser. ASSERT_EQ(2u, chrome::GetBrowserCount(browser()->profile())); Browser* app_browser = FindOtherBrowser(browser()); - ASSERT_TRUE(app_browser->is_app()); + ASSERT_TRUE(app_browser->is_type_app()); } // Flaky on MacOS: crbug.com/915339 diff --git a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc index b05f8f0c8cd..91b2e2ceb0a 100644 --- a/chromium/chrome/browser/extensions/api/management/management_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_browsertest.cc @@ -33,6 +33,7 @@ #include "content/public/test/browser_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_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" @@ -40,16 +41,18 @@ #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/browser/updater/extension_downloader.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_background_page_first_load_observer.h" #include "net/url_request/test_url_request_interceptor.h" #include "testing/gmock/include/gmock/gmock.h" using content::BrowserThread; using extensions::Extension; using extensions::ExtensionRegistry; +using extensions::ExtensionService; using extensions::Manifest; using policy::PolicyMap; -using testing::Return; using testing::_; +using testing::Return; namespace { @@ -58,6 +61,50 @@ 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_)), + extension_host_observer_(this) { + DCHECK(host_); + extension_host_observer_.Add(host_); + } + + void WaitForDestructionThenWaitForFirstLoad() { + run_loop_.Run(); + + extensions::TestBackgroundPageFirstLoadObserver first_load_observer( + profile_, extension_id_); + first_load_observer.Wait(); + } + + // ExtensionHostObserver: + void OnExtensionHostDestroyed( + const extensions::ExtensionHost* host) override { + if (host == host_) { + extension_host_observer_.Remove(host_); + run_loop_.Quit(); + } + } + + private: + Profile* const profile_ = nullptr; + const extensions::ExtensionId extension_id_; + extensions::ExtensionHost* const host_ = nullptr; + base::RunLoop run_loop_; + ScopedObserver<extensions::ExtensionHost, extensions::ExtensionHostObserver> + extension_host_observer_; + + DISALLOW_COPY_AND_ASSIGN(ExtensionHostDestructionObserver); +}; + } // namespace class ExtensionManagementTest : public extensions::ExtensionBrowserTest { @@ -114,15 +161,8 @@ class ExtensionManagementTest : public extensions::ExtensionBrowserTest { extensions::ScopedInstallVerifierBypassForTest install_verifier_bypass_; }; -#if defined(OS_LINUX) || defined(OS_WIN) -// Times out sometimes on Linux and Win XP. http://crbug.com/89727 -#define MAYBE_InstallSameVersion DISABLED_InstallSameVersion -#else -#define MAYBE_InstallSameVersion InstallSameVersion -#endif - // Tests that installing the same version overwrites. -IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_InstallSameVersion) { +IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallSameVersion) { base::ScopedAllowBlockingForTesting allow_blocking; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); @@ -142,10 +182,22 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_InstallSameVersion) { ASSERT_TRUE(extension); base::FilePath old_path = extension->path(); - // Install an extension with the same version. The previous install should be - // overwritten. - extension = InstallExtension(second_path, 0); - ASSERT_TRUE(extension); + const extensions::ExtensionId extension_id = extension->id(); + { + ExtensionHostDestructionObserver host_destruction_observer(profile(), + extension_id); + + // Install an extension with the same version. The previous install should + // be overwritten. + extension = InstallExtension(second_path, 0); + ASSERT_TRUE(extension); + + // Wait for the old ExtensionHost destruction first before waiting for the + // 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(); + } base::FilePath new_path = extension->path(); EXPECT_FALSE(IsExtensionAtVersion(extension, "1.0")); @@ -207,12 +259,10 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, InstallThenCancel) { IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_InstallRequiresConfirm) { // Installing the extension without an auto confirming UI should result in // it being disabled, since good.crx has permissions that require approval. - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); std::string id = "ldnnhddmnhbkjipkidpdiheffobcpfmf"; ASSERT_FALSE(InstallExtension(test_data_dir_.AppendASCII("good.crx"), 0)); - ASSERT_TRUE(service->GetExtensionById(id, true)); + ASSERT_TRUE(extension_registry()->GetExtensionById( + id, ExtensionRegistry::COMPATIBILITY)); UninstallExtension(id); // And the install should succeed when the permissions are accepted. @@ -373,10 +423,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ExtensionService* service = extension_service(); + ExtensionRegistry* registry = extension_registry(); const size_t size_before = registry->enabled_extensions().size(); ASSERT_TRUE(registry->disabled_extensions().is_empty()); const Extension* extension = InstallExtension(v1_path, 1); @@ -397,8 +445,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { install_observer.WaitForExtensionWillBeInstalled(); EXPECT_TRUE(listener2.WaitUntilSatisfied()); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", false); + extension = registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); ASSERT_TRUE(notification_listener.started()); @@ -422,8 +470,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, MAYBE_AutoUpdate) { // Make sure the extension state is the same as before. ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", false); + extension = registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); } @@ -474,10 +522,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, // Install version 1 of the extension. ExtensionTestMessageListener listener1("v1 installed", false); - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); - ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ExtensionService* service = extension_service(); + ExtensionRegistry* registry = extension_registry(); const size_t enabled_size_before = registry->enabled_extensions().size(); const size_t disabled_size_before = registry->disabled_extensions().size(); const Extension* extension = InstallExtension(v1_path, 1); @@ -500,11 +546,11 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, install_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(disabled_size_before + 1, registry->disabled_extensions().size()); ASSERT_EQ(enabled_size_before, registry->enabled_extensions().size()); - extension = service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", true); + extension = registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::COMPATIBILITY); ASSERT_TRUE(extension); - ASSERT_FALSE(service->GetExtensionById( - "ogjcoiohnmldgjemafoockdghcjciccf", false)); + ASSERT_FALSE(registry->GetExtensionById("ogjcoiohnmldgjemafoockdghcjciccf", + ExtensionRegistry::ENABLED)); ASSERT_EQ("2.0", extension->VersionString()); // The extension should have not made the callback because it is disabled. @@ -520,9 +566,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, } IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalUrlUpdate) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); + ExtensionService* service = extension_service(); const char kExtensionId[] = "ogjcoiohnmldgjemafoockdghcjciccf"; base::ScopedAllowBlockingForTesting allow_blocking; @@ -550,7 +594,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalUrlUpdate) { return false; })); - ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + ExtensionRegistry* registry = extension_registry(); const size_t size_before = registry->enabled_extensions().size(); ASSERT_TRUE(registry->disabled_extensions().is_empty()); @@ -576,7 +620,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalUrlUpdate) { service->updater()->CheckNow(extensions::ExtensionUpdater::CheckParams()); install_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - const Extension* extension = service->GetExtensionById(kExtensionId, false); + const Extension* extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); @@ -629,9 +674,6 @@ const char kForceInstallNotEmptyHelp[] = // See http://crbug.com/57378 for flakiness details. IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { - extensions::ExtensionService* service = - extensions::ExtensionSystem::Get(browser()->profile()) - ->extension_service(); const char kExtensionId[] = "ogjcoiohnmldgjemafoockdghcjciccf"; base::ScopedAllowBlockingForTesting allow_blocking; @@ -683,7 +725,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { // Check if the extension got installed. ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - const Extension* extension = service->GetExtensionById(kExtensionId, false); + const Extension* extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); ASSERT_EQ("2.0", extension->VersionString()); EXPECT_EQ(Manifest::EXTERNAL_POLICY_DOWNLOAD, extension->location()); @@ -708,7 +751,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, ExternalPolicyRefresh) { policies.Erase(policy::key::kExtensionInstallForcelist); UpdateProviderPolicy(policies); EXPECT_EQ(size_before + 1, registry->enabled_extensions().size()); - EXPECT_FALSE(service->GetExtensionById(kExtensionId, true)); + EXPECT_FALSE(registry->GetExtensionById(kExtensionId, + ExtensionRegistry::COMPATIBILITY)); } // See http://crbug.com/103371 and http://crbug.com/120640. @@ -763,7 +807,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, // User install of the extension. ASSERT_TRUE(InstallExtension(v2_path, 1)); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - const Extension* extension = service->GetExtensionById(kExtensionId, false); + const Extension* extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::INTERNAL, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); @@ -782,7 +827,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, install_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, false); + extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::EXTERNAL_POLICY_DOWNLOAD, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); @@ -794,13 +840,15 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, policies.Erase(policy::key::kExtensionInstallForcelist); UpdateProviderPolicy(policies); ASSERT_EQ(size_before, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, true); + extension = registry->GetExtensionById(kExtensionId, + ExtensionRegistry::COMPATIBILITY); EXPECT_FALSE(extension); // User install again, but have it disabled too before setting the policy. ASSERT_TRUE(InstallExtension(v2_path, 1)); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, false); + extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::INTERNAL, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); @@ -808,7 +856,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, DisableExtension(kExtensionId); EXPECT_EQ(1u, registry->disabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, true); + extension = registry->GetExtensionById(kExtensionId, + ExtensionRegistry::COMPATIBILITY); EXPECT_TRUE(extension); EXPECT_FALSE(service->IsExtensionEnabled(kExtensionId)); @@ -824,7 +873,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionManagementTest, extension_observer.WaitForExtensionWillBeInstalled(); ASSERT_EQ(size_before + 1, registry->enabled_extensions().size()); - extension = service->GetExtensionById(kExtensionId, false); + extension = + registry->GetExtensionById(kExtensionId, ExtensionRegistry::ENABLED); ASSERT_TRUE(extension); EXPECT_EQ(Manifest::EXTERNAL_POLICY_DOWNLOAD, extension->location()); EXPECT_TRUE(service->IsExtensionEnabled(kExtensionId)); diff --git a/chromium/chrome/browser/extensions/api/mdns/mdns_api.h b/chromium/chrome/browser/extensions/api/mdns/mdns_api.h index 19464a2ef76..dbfe3b46e41 100644 --- a/chromium/chrome/browser/extensions/api/mdns/mdns_api.h +++ b/chromium/chrome/browser/extensions/api/mdns/mdns_api.h @@ -118,7 +118,7 @@ class MDnsAPI : public BrowserContextKeyedAPI, DISALLOW_COPY_AND_ASSIGN(MDnsAPI); }; -class MdnsForceDiscoveryFunction : public UIThreadExtensionFunction { +class MdnsForceDiscoveryFunction : public ExtensionFunction { public: MdnsForceDiscoveryFunction(); @@ -126,7 +126,7 @@ class MdnsForceDiscoveryFunction : public UIThreadExtensionFunction { ~MdnsForceDiscoveryFunction() override; private: - // UIThreadExtensionFunction override. + // ExtensionFunction override. ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("mdns.forceDiscovery", MDNS_FORCEDISCOVERY) diff --git a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc index 633d8ff73d2..69ddd3fbc6a 100644 --- a/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.cc @@ -13,12 +13,9 @@ #include "content/public/browser/browser_thread.h" #include "content/public/browser/chromeos/delegate_to_browser_gpu_service_accelerator_factory.h" #include "content/public/browser/render_frame_host.h" -#include "content/public/browser/system_connector.h" +#include "content/public/browser/video_capture_service.h" #include "mojo/public/cpp/bindings/strong_binding.h" -#include "services/service_manager/public/cpp/connector.h" -#include "services/video_capture/public/mojom/constants.mojom.h" #include "services/video_capture/public/mojom/device_factory.mojom.h" -#include "services/video_capture/public/mojom/device_factory_provider.mojom.h" namespace extensions { @@ -42,12 +39,40 @@ std::string GetComponentNameForComponentType( return ""; } +api::media_perception_private::ComponentInstallationError +GetComponentInstallationErrorForCrOSComponentManagerError( + const component_updater::CrOSComponentManager::Error error) { + switch (error) { + case component_updater::CrOSComponentManager::Error::ERROR_MAX: + case component_updater::CrOSComponentManager::Error::NONE: + return api::media_perception_private::COMPONENT_INSTALLATION_ERROR_NONE; + case component_updater::CrOSComponentManager::Error::UNKNOWN_COMPONENT: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_UNKNOWN_COMPONENT; + case component_updater::CrOSComponentManager::Error::INSTALL_FAILURE: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_INSTALL_FAILURE; + case component_updater::CrOSComponentManager::Error::MOUNT_FAILURE: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_MOUNT_FAILURE; + case component_updater::CrOSComponentManager::Error:: + COMPATIBILITY_CHECK_FAILED: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_COMPATIBILITY_CHECK_FAILED; + case component_updater::CrOSComponentManager::Error::NOT_FOUND: + return api::media_perception_private:: + COMPONENT_INSTALLATION_ERROR_NOT_FOUND; + } + NOTREACHED() << "Reached component error type not in switch."; + return api::media_perception_private::COMPONENT_INSTALLATION_ERROR_NONE; +} + void OnLoadComponent( MediaPerceptionAPIDelegate::LoadCrOSComponentCallback load_callback, component_updater::CrOSComponentManager::Error error, const base::FilePath& mount_point) { std::move(load_callback) - .Run(error == component_updater::CrOSComponentManager::Error::NONE, + .Run(GetComponentInstallationErrorForCrOSComponentManagerError(error), mount_point); } @@ -68,22 +93,18 @@ void MediaPerceptionAPIDelegateChromeOS::LoadCrOSComponent( base::BindOnce(OnLoadComponent, std::move(load_callback))); } -void MediaPerceptionAPIDelegateChromeOS:: - BindDeviceFactoryProviderToVideoCaptureService( - video_capture::mojom::DeviceFactoryProviderPtr* provider) { +void MediaPerceptionAPIDelegateChromeOS::BindVideoSourceProvider( + mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> receiver) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - // In unit test environments, there may not be any connector. - service_manager::Connector* connector = content::GetSystemConnector(); - if (!connector) - return; - connector->BindInterface(video_capture::mojom::kServiceName, provider); - video_capture::mojom::AcceleratorFactoryPtr accelerator_factory; mojo::MakeStrongBinding( std::make_unique< content::DelegateToBrowserGpuServiceAcceleratorFactory>(), mojo::MakeRequest(&accelerator_factory)); - (*provider)->InjectGpuDependencies(std::move(accelerator_factory)); + + auto& service = content::GetVideoCaptureService(); + service.InjectGpuDependencies(std::move(accelerator_factory)); + service.ConnectToVideoSourceProvider(std::move(receiver)); } void MediaPerceptionAPIDelegateChromeOS::SetMediaPerceptionRequestHandler( 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 1d765110283..45abc51201e 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 @@ -20,8 +20,9 @@ class MediaPerceptionAPIDelegateChromeOS void LoadCrOSComponent( const api::media_perception_private::ComponentType& type, LoadCrOSComponentCallback load_callback) override; - void BindDeviceFactoryProviderToVideoCaptureService( - video_capture::mojom::DeviceFactoryProviderPtr* provider) override; + void BindVideoSourceProvider( + mojo::PendingReceiver<video_capture::mojom::VideoSourceProvider> receiver) + override; void SetMediaPerceptionRequestHandler( MediaPerceptionRequestHandler handler) override; void ForwardMediaPerceptionRequest( diff --git a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc index b19df51e216..ff4cc1c31a6 100644 --- a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc +++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc @@ -98,8 +98,7 @@ content::WebContents* ChromeMessagingDelegate::GetWebContentsByTabId( int tab_id) { content::WebContents* contents = nullptr; if (!ExtensionTabUtil::GetTabById(tab_id, browser_context, - /*incognito_enabled=*/true, nullptr, - nullptr, &contents, nullptr)) { + /*incognito_enabled=*/true, &contents)) { return nullptr; } return contents; diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc index 1ba3053c6d1..e0305176d49 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_host_chromeos.cc @@ -95,10 +95,8 @@ struct BuiltInHost { std::unique_ptr<NativeMessageHost> CreateIt2MeHost() { return remoting::CreateIt2MeNativeMessagingHostForChromeOS( - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}), - base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::UI}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}), + base::CreateSingleThreadTaskRunner({content::BrowserThread::UI}), g_browser_process->policy_service()); } @@ -127,7 +125,9 @@ static const BuiltInHost kBuiltInHost[] = { {arc::ArcSupportMessageHost::kHostName, arc::ArcSupportMessageHost::kHostOrigin, 1, &arc::ArcSupportMessageHost::Create}, - {chromeos::kWilcoDtcSupportdUiMessageHost, nullptr, 0, + {chromeos::kWilcoDtcSupportdUiMessageHost, + chromeos::kWilcoDtcSupportdHostOrigins, + chromeos::kWilcoDtcSupportdHostOriginsSize, &chromeos::CreateExtensionOwnedWilcoDtcSupportdMessageHost}, }; diff --git a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc index b6e5a3e5595..4efb28cd942 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_message_process_host.cc @@ -71,8 +71,8 @@ NativeMessageProcessHost::NativeMessageProcessHost( write_pending_(false) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); - task_runner_ = base::CreateSingleThreadTaskRunnerWithTraits( - {content::BrowserThread::IO}); + task_runner_ = + base::CreateSingleThreadTaskRunner({content::BrowserThread::IO}); } NativeMessageProcessHost::~NativeMessageProcessHost() { @@ -83,8 +83,9 @@ NativeMessageProcessHost::~NativeMessageProcessHost() { // TODO(https://crbug.com/806451): On OSX EnsureProcessTerminated() may // block, so we have to post a task on the blocking pool. #if defined(OS_MACOSX) - base::PostTaskWithTraits( - FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT}, + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::BEST_EFFORT}, base::BindOnce(&base::EnsureProcessTerminated, Passed(&process_))); #else base::EnsureProcessTerminated(std::move(process_)); @@ -106,7 +107,8 @@ std::unique_ptr<NativeMessageHost> NativeMessageHost::Create( allow_user_level, native_view, GetProfilePathIfEnabled(Profile::FromBrowserContext(browser_context), source_extension_id, native_host_name), - /* require_native_initiated_connections = */ false)); + /* require_native_initiated_connections = */ false, + /* connect_id = */ "")); } // static @@ -162,8 +164,8 @@ void NativeMessageProcessHost::OnHostProcessLaunched( read_file_ = read_file.GetPlatformFile(); #endif - scoped_refptr<base::TaskRunner> task_runner(base::CreateTaskRunnerWithTraits( - {base::MayBlock(), base::TaskPriority::USER_VISIBLE, + scoped_refptr<base::TaskRunner> task_runner(base::CreateTaskRunner( + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE, base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN})); read_stream_.reset(new net::FileStream(std::move(read_file), task_runner)); 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 ddab3fb0276..afb9c77adc7 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 @@ -40,7 +40,7 @@ #include "chrome/test/base/testing_profile.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_thread.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "extensions/common/features/feature_channel.h" #include "testing/gtest/include/gtest/gtest.h" @@ -115,7 +115,7 @@ class NativeMessagingTest : public ::testing::Test, protected: NativeMessagingTest() : current_channel_(version_info::Channel::DEV), - thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP), channel_closed_(false) {} void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } @@ -177,7 +177,7 @@ class NativeMessagingTest : public ::testing::Test, ScopedCurrentChannel current_channel_; std::unique_ptr<NativeMessageHost> native_message_host_; std::unique_ptr<base::RunLoop> run_loop_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; std::string last_message_; @@ -315,6 +315,10 @@ TEST_F(NativeMessagingTest, EchoConnect) { const base::Value* args = nullptr; ASSERT_TRUE(last_message_parsed_->Get("args", &args)); EXPECT_TRUE(args->is_none()); + + const base::Value* connect_id_value = nullptr; + ASSERT_TRUE(last_message_parsed_->Get("connect_id", &connect_id_value)); + EXPECT_TRUE(connect_id_value->is_none()); } // Test send message with a real client. The args passed when launching the @@ -425,6 +429,10 @@ TEST_F(NativeMessagingTest, ReconnectArgsIfNativeConnectionDisallowed) { const base::Value* args_value = nullptr; ASSERT_TRUE(last_message_parsed_->Get("args", &args_value)); EXPECT_TRUE(args_value->is_none()); + + const base::Value* connect_id_value = nullptr; + ASSERT_TRUE(last_message_parsed_->Get("connect_id", &connect_id_value)); + EXPECT_TRUE(connect_id_value->is_none()); } TEST_F(NativeMessagingTest, UserLevel) { 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 e8cc9ae6148..33042b32456 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_apitest.cc @@ -92,6 +92,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_NativeMessagingLaunch) { switches::kNativeMessagingConnectHost, ScopedTestNativeMessagingHost:: kSupportsNativeInitiatedConnectionsHostName); + command_line.AppendSwitchASCII(switches::kNativeMessagingConnectId, + "test-connect-id"); StartupBrowserCreator::ProcessCommandLineAlreadyRunning(command_line, {}, profile()->GetPath()); 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 eabfae9941d..d0ccab75d99 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 @@ -7,6 +7,7 @@ #include <memory> #include <utility> +#include "base/strings/string_util.h" #include "chrome/browser/extensions/api/messaging/native_message_port.h" #include "chrome/browser/extensions/api/messaging/native_message_process_host.h" #include "chrome/browser/extensions/api/messaging/native_process_launcher.h" @@ -94,9 +95,21 @@ ScopedAllowNativeAppConnectionForTest:: g_allow_native_app_connection_for_test = nullptr; } +bool IsValidConnectionId(const base::StringPiece connection_id) { + return connection_id.size() <= 20 && + base::ContainsOnlyChars( + connection_id, + "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-"); +} + void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id, const std::string& host_id, + const std::string& connection_id, Profile* profile) { + if (!IsValidConnectionId(connection_id)) { + // TODO(crbug.com/967262): Report errors to the native messaging host. + return; + } if (!ExtensionSupportsConnectionFromNativeApp(extension_id, host_id, profile, /* log_errors = */ true)) { // TODO(crbug.com/967262): Report errors to the native messaging host. @@ -112,7 +125,7 @@ void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id, NativeProcessLauncher::CreateDefault( /* allow_user_level = */ true, /* native_view = */ nullptr, profile->GetPath(), - /* require_native_initiated_connections = */ true)); + /* require_native_initiated_connections = */ true, connection_id)); auto native_message_port = std::make_unique<extensions::NativeMessagePort>( message_service->GetChannelDelegate(), port_id, std::move(native_message_host)); 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 d730422c455..2bb104678ee 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 @@ -24,6 +24,7 @@ bool ExtensionSupportsConnectionFromNativeApp(const std::string& extension_id, // |host_id|. void LaunchNativeMessageHostFromNativeApp(const std::string& extension_id, const std::string& host_id, + const std::string& connection_id, Profile* profile); class ScopedAllowNativeAppConnectionForTest { diff --git a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc index 48ab25ef66f..63134b0e411 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_messaging_launch_from_native_unittest.cc @@ -12,7 +12,7 @@ #include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h" #include "chrome/test/base/testing_profile.h" #include "components/version_info/version_info.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/event_router.h" #include "extensions/browser/event_router_factory.h" #include "extensions/browser/extension_prefs.h" @@ -115,7 +115,7 @@ class ExtensionSupportsConnectionFromNativeAppTest : public ::testing::Test { } ScopedCurrentChannel channel_; - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; bool has_listener_result_ = true; TestingProfile profile_; std::string extension_id_; 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 fc731d68f81..edfdcbf0bc5 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc @@ -19,6 +19,7 @@ #include "base/logging.h" #include "base/macros.h" #include "base/memory/ref_counted.h" +#include "base/memory/scoped_refptr.h" #include "base/path_service.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" @@ -47,7 +48,8 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { NativeProcessLauncherImpl(bool allow_user_level_hosts, intptr_t native_window, const base::FilePath& profile_directory, - bool require_native_initiated_connections); + bool require_native_initiated_connections, + const std::string& connect_id); ~NativeProcessLauncherImpl() override; void Launch(const GURL& origin, @@ -60,7 +62,8 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { Core(bool allow_user_level_hosts, intptr_t native_window, const base::FilePath& profile_directory, - bool require_native_initiated_connections); + bool require_native_initiated_connections, + const std::string& connect_id); void Launch(const GURL& origin, const std::string& native_host_name, const LaunchedCallback& callback); @@ -91,6 +94,8 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { const base::FilePath profile_directory_; const bool require_native_initiated_connections_; + + const std::string connect_id_; #if defined(OS_WIN) // Handle of the native window corresponding to the extension. intptr_t window_handle_; @@ -107,12 +112,14 @@ class NativeProcessLauncherImpl : public NativeProcessLauncher { NativeProcessLauncherImpl::Core::Core(bool allow_user_level_hosts, intptr_t window_handle, const base::FilePath& profile_directory, - bool require_native_initiated_connections) + bool require_native_initiated_connections, + const std::string& connect_id) : detached_(false), allow_user_level_hosts_(allow_user_level_hosts), profile_directory_(profile_directory), require_native_initiated_connections_( - require_native_initiated_connections) + require_native_initiated_connections), + connect_id_(connect_id) #if defined(OS_WIN) , window_handle_(window_handle) @@ -132,10 +139,11 @@ void NativeProcessLauncherImpl::Core::Launch( const GURL& origin, const std::string& native_host_name, const LaunchedCallback& callback) { - base::PostTaskWithTraits(FROM_HERE, - {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, - base::BindOnce(&Core::DoLaunchOnThreadPool, this, - origin, native_host_name, callback)); + base::PostTask( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::BindOnce(&Core::DoLaunchOnThreadPool, this, origin, + native_host_name, callback)); } void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool( @@ -259,6 +267,11 @@ void NativeProcessLauncherImpl::Core::DoLaunchOnThreadPool( base::Base64Encode(encoded_reconnect_command, &encoded_reconnect_command); command_line.AppendArg( base::StrCat({"--reconnect-command=", encoded_reconnect_command})); + + if (!connect_id_.empty()) { + command_line.AppendArg(base::StrCat( + {"--", switches::kNativeMessagingConnectId, "=", connect_id_})); + } } base::Process process; @@ -290,7 +303,7 @@ void NativeProcessLauncherImpl::Core::CallCallbackOnIOThread( void NativeProcessLauncherImpl::Core::PostErrorResult( const LaunchedCallback& callback, LaunchResult error) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, this, callback, error, base::Process(), base::File(), @@ -302,7 +315,7 @@ void NativeProcessLauncherImpl::Core::PostResult( base::Process process, base::File read_file, base::File write_file) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, this, callback, RESULT_SUCCESS, std::move(process), @@ -313,11 +326,13 @@ NativeProcessLauncherImpl::NativeProcessLauncherImpl( bool allow_user_level_hosts, intptr_t window_handle, const base::FilePath& profile_directory, - bool require_native_initiated_connections) - : core_(new Core(allow_user_level_hosts, - window_handle, - profile_directory, - require_native_initiated_connections)) {} + bool require_native_initiated_connections, + const std::string& connect_id) + : core_(base::MakeRefCounted<Core>(allow_user_level_hosts, + window_handle, + profile_directory, + require_native_initiated_connections, + connect_id)) {} NativeProcessLauncherImpl::~NativeProcessLauncherImpl() { core_->Detach(); @@ -336,7 +351,8 @@ std::unique_ptr<NativeProcessLauncher> NativeProcessLauncher::CreateDefault( bool allow_user_level_hosts, gfx::NativeView native_view, const base::FilePath& profile_directory, - bool require_native_initiated_connections) { + bool require_native_initiated_connections, + const std::string& connect_id) { intptr_t window_handle = 0; #if defined(OS_WIN) window_handle = reinterpret_cast<intptr_t>( @@ -344,7 +360,7 @@ std::unique_ptr<NativeProcessLauncher> NativeProcessLauncher::CreateDefault( #endif return std::make_unique<NativeProcessLauncherImpl>( allow_user_level_hosts, window_handle, profile_directory, - require_native_initiated_connections); + require_native_initiated_connections, connect_id); } } // namespace extensions 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 51102bc3247..9ee0a8f3d62 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.h @@ -51,7 +51,8 @@ class NativeProcessLauncher { bool allow_user_level_hosts, gfx::NativeView native_view, const base::FilePath& profile_directory, - bool require_native_initiated_connections); + bool require_native_initiated_connections, + const std::string& connect_id); NativeProcessLauncher() {} virtual ~NativeProcessLauncher() {} diff --git a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc index c0843625742..e458a0501f0 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher_posix.cc @@ -84,6 +84,12 @@ bool NativeProcessLauncher::LaunchNativeProcess( options.allow_new_privs = true; #endif +#if defined(OS_MACOSX) + // This is executing a third-party binary, so do not associate any system + // private data requests with Chrome. + options.disclaim_responsibility = true; +#endif + base::Process local_process = base::LaunchProcess(command_line, options); if (!local_process.IsValid()) { LOG(ERROR) << "Error launching process"; diff --git a/chromium/chrome/browser/extensions/api/module/module.h b/chromium/chrome/browser/extensions/api/module/module.h index de81de0d8a8..cbdde206799 100644 --- a/chromium/chrome/browser/extensions/api/module/module.h +++ b/chromium/chrome/browser/extensions/api/module/module.h @@ -16,7 +16,7 @@ std::string GetUpdateURLData(const ExtensionPrefs* prefs, const std::string& extension_id); } // namespace extension -class ExtensionSetUpdateUrlDataFunction : public UIThreadExtensionFunction { +class ExtensionSetUpdateUrlDataFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.setUpdateUrlData", EXTENSION_SETUPDATEURLDATA) @@ -28,8 +28,7 @@ class ExtensionSetUpdateUrlDataFunction : public UIThreadExtensionFunction { ResponseAction Run() override; }; -class ExtensionIsAllowedIncognitoAccessFunction - : public UIThreadExtensionFunction { +class ExtensionIsAllowedIncognitoAccessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.isAllowedIncognitoAccess", EXTENSION_ISALLOWEDINCOGNITOACCESS) @@ -41,8 +40,7 @@ class ExtensionIsAllowedIncognitoAccessFunction ResponseAction Run() override; }; -class ExtensionIsAllowedFileSchemeAccessFunction - : public UIThreadExtensionFunction { +class ExtensionIsAllowedFileSchemeAccessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("extension.isAllowedFileSchemeAccess", EXTENSION_ISALLOWEDFILESCHEMEACCESS) diff --git a/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc b/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc index 27060f8ca72..db66f4b2e6b 100644 --- a/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc +++ b/chromium/chrome/browser/extensions/api/networking_cast_private/chrome_networking_cast_private_delegate.cc @@ -133,8 +133,9 @@ void ChromeNetworkingCastPrivateDelegate::VerifyDestination( std::unique_ptr<Credentials> credentials, const VerifiedCallback& success_callback, const FailureCallback& failure_callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&RunDecodeAndVerifyCredentials, base::Passed(&credentials)), base::Bind(&VerifyDestinationCompleted, success_callback, failure_callback)); @@ -145,8 +146,9 @@ void ChromeNetworkingCastPrivateDelegate::VerifyAndEncryptData( std::unique_ptr<Credentials> credentials, const DataCallback& success_callback, const FailureCallback& failure_callback) { - base::PostTaskWithTraitsAndReplyWithResult( - FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, + base::PostTaskAndReplyWithResult( + FROM_HERE, + {base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::Bind(&RunVerifyAndEncryptData, data, base::Passed(&credentials)), base::Bind(&VerifyAndEncryptDataCompleted, success_callback, failure_callback)); diff --git a/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h b/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h index 4f12d14f07a..daf23fbaef8 100644 --- a/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h +++ b/chromium/chrome/browser/extensions/api/networking_cast_private/networking_cast_private_api.h @@ -18,7 +18,7 @@ class DictionaryValue; namespace extensions { class NetworkingCastPrivateVerifyDestinationFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateVerifyDestinationFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.verifyDestination", @@ -38,7 +38,7 @@ class NetworkingCastPrivateVerifyDestinationFunction }; class NetworkingCastPrivateVerifyAndEncryptDataFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateVerifyAndEncryptDataFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.verifyAndEncryptData", @@ -58,7 +58,7 @@ class NetworkingCastPrivateVerifyAndEncryptDataFunction }; class NetworkingCastPrivateSetWifiTDLSEnabledStateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateSetWifiTDLSEnabledStateFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.setWifiTDLSEnabledState", @@ -82,7 +82,7 @@ class NetworkingCastPrivateSetWifiTDLSEnabledStateFunction }; class NetworkingCastPrivateGetWifiTDLSStatusFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: NetworkingCastPrivateGetWifiTDLSStatusFunction() {} DECLARE_EXTENSION_FUNCTION("networking.castPrivate.getWifiTDLSStatus", 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 d8121216c4c..bedfe826489 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 @@ -363,9 +363,6 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { // Sends a notification about the added profile. profile_test_->AddProfile(kUser1ProfilePath, userhash_); - // Enable technologies. - manager_test_->AddTechnology("wimax", true); - // Add IPConfigs base::DictionaryValue ipconfig; ipconfig.SetKey(shill::kAddressProperty, base::Value("0.0.0.0")); @@ -442,15 +439,6 @@ class NetworkingPrivateChromeOSApiTest : public extensions::ExtensionApiTest { kWifi2ServicePath, shill::kTetheringProperty, base::Value(shill::kTetheringNotDetectedState)); - AddService("stub_wimax", "wimax", shill::kTypeWimax, shill::kStateOnline); - service_test_->SetServiceProperty( - "stub_wimax", shill::kSignalStrengthProperty, base::Value(40)); - service_test_->SetServiceProperty("stub_wimax", shill::kProfileProperty, - base::Value(kUser1ProfilePath)); - service_test_->SetServiceProperty("stub_wimax", shill::kConnectableProperty, - base::Value(true)); - profile_test_->AddService(kUser1ProfilePath, "stub_wimax"); - base::ListValue frequencies2; frequencies2.AppendInteger(2400); frequencies2.AppendInteger(5000); @@ -573,8 +561,6 @@ IN_PROC_BROWSER_TEST_F(NetworkingPrivateChromeOSApiTest, GetDeviceStates) { manager_test_->RemoveTechnology("cellular"); manager_test_->AddTechnology("cellular", false /* disabled */); manager_test_->SetTechnologyInitializing("cellular", true); - manager_test_->RemoveTechnology("wimax"); - manager_test_->AddTechnology("wimax", false /* disabled */); EXPECT_TRUE(RunNetworkingSubtest("getDeviceStates")) << message_; } 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 459f5333e41..5ccf99f3f54 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 @@ -12,7 +12,7 @@ #include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" #include "chrome/test/base/testing_profile_manager.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -59,7 +59,7 @@ class ExtensionNotificationHandlerTest : public testing::Test { ExtensionNotificationHandlerTest() {} private: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; }; TEST_F(ExtensionNotificationHandlerTest, CloseHandler) { diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc index 4826ad17a57..427be63bed1 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc @@ -10,6 +10,8 @@ #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" +#include "chrome/browser/apps/app_service/app_launch_params.h" +#include "chrome/browser/apps/launch_service/launch_service.h" #include "chrome/browser/apps/platform_apps/app_browsertest_util.h" #include "chrome/browser/extensions/api/notifications/extension_notification_display_helper.h" #include "chrome/browser/extensions/api/notifications/extension_notification_display_helper_factory.h" @@ -22,8 +24,6 @@ #include "chrome/browser/notifications/notifier_state_tracker.h" #include "chrome/browser/notifications/notifier_state_tracker_factory.h" #include "chrome/browser/profiles/profile_manager.h" -#include "chrome/browser/ui/extensions/app_launch_params.h" -#include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/common/chrome_features.h" #include "chrome/test/base/interactive_test_utils.h" #include "content/public/browser/notification_service.h" @@ -205,11 +205,12 @@ class NotificationsApiTest : public extensions::ExtensionApiTest { } void LaunchPlatformApp(const Extension* extension) { - OpenApplication( - AppLaunchParams(browser()->profile(), extension->id(), - extensions::LaunchContainer::kLaunchContainerNone, - WindowOpenDisposition::NEW_WINDOW, - extensions::AppLaunchSource::kSourceTest)); + apps::LaunchService::Get(browser()->profile()) + ->OpenApplication( + AppLaunchParams(browser()->profile(), extension->id(), + apps::mojom::LaunchContainer::kLaunchContainerNone, + WindowOpenDisposition::NEW_WINDOW, + apps::mojom::AppLaunchSource::kSourceTest)); } std::unique_ptr<NotificationDisplayServiceTester> display_service_tester_; diff --git a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h index 27c7981cfc1..435ea6456f9 100644 --- a/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h +++ b/chromium/chrome/browser/extensions/api/omnibox/omnibox_api.h @@ -74,7 +74,7 @@ class ExtensionOmniboxEventRouter { DISALLOW_COPY_AND_ASSIGN(ExtensionOmniboxEventRouter); }; -class OmniboxSendSuggestionsFunction : public UIThreadExtensionFunction { +class OmniboxSendSuggestionsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("omnibox.sendSuggestions", OMNIBOX_SENDSUGGESTIONS) @@ -147,7 +147,7 @@ class OmniboxAPI : public BrowserContextKeyedAPI, template <> void BrowserContextKeyedAPIFactory<OmniboxAPI>::DeclareFactoryDependencies(); -class OmniboxSetDefaultSuggestionFunction : public UIThreadExtensionFunction { +class OmniboxSetDefaultSuggestionFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("omnibox.setDefaultSuggestion", OMNIBOX_SETDEFAULTSUGGESTION) 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 1d92faec7e4..9ea3a3c7610 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 @@ -52,6 +52,7 @@ const char kPageCaptureNotAllowed[] = const char kUserDenied[] = "User denied request."; #endif constexpr base::TaskTraits kCreateTemporaryFileTaskTraits = { + base::ThreadPool(), // Requires IO. base::MayBlock(), @@ -74,7 +75,7 @@ PageCaptureSaveAsMHTMLFunction::PageCaptureSaveAsMHTMLFunction() { PageCaptureSaveAsMHTMLFunction::~PageCaptureSaveAsMHTMLFunction() { if (mhtml_file_.get()) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&ClearFileReferenceOnIOThread, std::move(mhtml_file_))); } @@ -118,7 +119,7 @@ bool PageCaptureSaveAsMHTMLFunction::RunAsync() { if (!CanCaptureCurrentPage()) { return false; } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); @@ -179,7 +180,7 @@ bool PageCaptureSaveAsMHTMLFunction::OnMessageReceived( void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest( const PermissionIDSet& allowed_permissions) { if (allowed_permissions.ContainsID(APIPermission::kPageCapture)) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, kCreateTemporaryFileTaskTraits, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile, this)); @@ -191,7 +192,7 @@ void PageCaptureSaveAsMHTMLFunction::ResolvePermissionRequest( void PageCaptureSaveAsMHTMLFunction::CreateTemporaryFile() { bool success = base::CreateTemporaryFile(&mhtml_path_); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::IO}, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO, this, success)); @@ -204,8 +205,8 @@ void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO(bool success) { // once it is no longer used. mhtml_file_ = ShareableFileReference::GetOrCreate( mhtml_path_, ShareableFileReference::DELETE_ON_FINAL_RELEASE, - base::CreateSequencedTaskRunnerWithTraits( - {// Requires IO. + base::CreateSequencedTaskRunner( + {base::ThreadPool(), // Requires IO. base::MayBlock(), // TaskPriority: Inherit. @@ -217,7 +218,7 @@ void PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnIO(bool success) { base::TaskShutdownBehavior::BLOCK_SHUTDOWN}) .get()); } - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce(&PageCaptureSaveAsMHTMLFunction::TemporaryFileCreatedOnUI, this, success)); diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h index 5b944787663..b9521497512 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.h @@ -17,7 +17,7 @@ namespace extensions { class PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction() {} DECLARE_EXTENSION_FUNCTION( @@ -35,8 +35,7 @@ class PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction PasswordsPrivateRecordPasswordsPageAccessInSettingsFunction); }; -class PasswordsPrivateChangeSavedPasswordFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateChangeSavedPasswordFunction : public ExtensionFunction { public: PasswordsPrivateChangeSavedPasswordFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.changeSavedPassword", @@ -52,8 +51,7 @@ class PasswordsPrivateChangeSavedPasswordFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateChangeSavedPasswordFunction); }; -class PasswordsPrivateRemoveSavedPasswordFunction : - public UIThreadExtensionFunction { +class PasswordsPrivateRemoveSavedPasswordFunction : public ExtensionFunction { public: PasswordsPrivateRemoveSavedPasswordFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.removeSavedPassword", @@ -69,8 +67,8 @@ class PasswordsPrivateRemoveSavedPasswordFunction : DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateRemoveSavedPasswordFunction); }; -class PasswordsPrivateRemovePasswordExceptionFunction : - public UIThreadExtensionFunction { +class PasswordsPrivateRemovePasswordExceptionFunction + : public ExtensionFunction { public: PasswordsPrivateRemovePasswordExceptionFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.removePasswordException", @@ -87,7 +85,7 @@ class PasswordsPrivateRemovePasswordExceptionFunction : }; class PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction() {} DECLARE_EXTENSION_FUNCTION( @@ -105,8 +103,8 @@ class PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction PasswordsPrivateUndoRemoveSavedPasswordOrExceptionFunction); }; -class PasswordsPrivateRequestPlaintextPasswordFunction : - public UIThreadExtensionFunction { +class PasswordsPrivateRequestPlaintextPasswordFunction + : public ExtensionFunction { public: PasswordsPrivateRequestPlaintextPasswordFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.requestPlaintextPassword", @@ -124,8 +122,7 @@ class PasswordsPrivateRequestPlaintextPasswordFunction : DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateRequestPlaintextPasswordFunction); }; -class PasswordsPrivateGetSavedPasswordListFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateGetSavedPasswordListFunction : public ExtensionFunction { public: PasswordsPrivateGetSavedPasswordListFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.getSavedPasswordList", @@ -145,7 +142,7 @@ class PasswordsPrivateGetSavedPasswordListFunction }; class PasswordsPrivateGetPasswordExceptionListFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateGetPasswordExceptionListFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.getPasswordExceptionList", @@ -164,8 +161,7 @@ class PasswordsPrivateGetPasswordExceptionListFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateGetPasswordExceptionListFunction); }; -class PasswordsPrivateImportPasswordsFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateImportPasswordsFunction : public ExtensionFunction { public: PasswordsPrivateImportPasswordsFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.importPasswords", @@ -181,8 +177,7 @@ class PasswordsPrivateImportPasswordsFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateImportPasswordsFunction); }; -class PasswordsPrivateExportPasswordsFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateExportPasswordsFunction : public ExtensionFunction { public: PasswordsPrivateExportPasswordsFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.exportPasswords", @@ -200,8 +195,7 @@ class PasswordsPrivateExportPasswordsFunction DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateExportPasswordsFunction); }; -class PasswordsPrivateCancelExportPasswordsFunction - : public UIThreadExtensionFunction { +class PasswordsPrivateCancelExportPasswordsFunction : public ExtensionFunction { public: PasswordsPrivateCancelExportPasswordsFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.cancelExportPasswords", @@ -218,7 +212,7 @@ class PasswordsPrivateCancelExportPasswordsFunction }; class PasswordsPrivateRequestExportProgressStatusFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: PasswordsPrivateRequestExportProgressStatusFunction() {} DECLARE_EXTENSION_FUNCTION("passwordsPrivate.requestExportProgressStatus", 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 5ac9e7e8782..94758ce1b54 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 @@ -69,24 +69,10 @@ class TestDelegate : public PasswordsPrivateDelegate { } ~TestDelegate() override {} - void SendSavedPasswordsList() override { - PasswordsPrivateEventRouter* router = - PasswordsPrivateEventRouterFactory::GetForProfile(profile_); - if (router) - router->OnSavedPasswordsListChanged(current_entries_); - } - void GetSavedPasswordsList(UiEntriesCallback callback) override { std::move(callback).Run(current_entries_); } - void SendPasswordExceptionsList() override { - PasswordsPrivateEventRouter* router = - PasswordsPrivateEventRouterFactory::GetForProfile(profile_); - if (router) - router->OnPasswordExceptionsListChanged(current_exceptions_); - } - void GetPasswordExceptionsList( const ExceptionEntriesCallback& callback) override { callback.Run(current_exceptions_); @@ -181,6 +167,20 @@ class TestDelegate : public PasswordsPrivateDelegate { bool cancelExportPasswordsTriggered = false; private: + void SendSavedPasswordsList() { + PasswordsPrivateEventRouter* router = + PasswordsPrivateEventRouterFactory::GetForProfile(profile_); + if (router) + router->OnSavedPasswordsListChanged(current_entries_); + } + + void SendPasswordExceptionsList() { + PasswordsPrivateEventRouter* router = + PasswordsPrivateEventRouterFactory::GetForProfile(profile_); + if (router) + router->OnPasswordExceptionsListChanged(current_exceptions_); + } + // The current list of entries/exceptions. Cached here so that when new // observers are added, this delegate can send the current lists without // having to request them from |password_manager_presenter_| again. diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h index 9ea44f8d204..5c4bb1067a0 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h @@ -27,9 +27,9 @@ class WebContents; namespace extensions { -// Delegate used by the chrome.passwordsPrivate API to facilitate removing saved -// passwords and password exceptions and to notify listeners when these values -// have changed. +// Delegate used by the chrome.passwordsPrivate API to facilitate working with +// saved passwords and password exceptions (reading, changing, removing, +// import/export) and to notify listeners when these values have changed. class PasswordsPrivateDelegate : public KeyedService { public: using PlaintextPasswordCallback = @@ -37,17 +37,11 @@ class PasswordsPrivateDelegate : public KeyedService { ~PasswordsPrivateDelegate() override {} - // Sends the saved passwords list to the event router. - virtual void SendSavedPasswordsList() = 0; - // Gets the saved passwords list. using UiEntries = std::vector<api::passwords_private::PasswordUiEntry>; using UiEntriesCallback = base::OnceCallback<void(const UiEntries&)>; virtual void GetSavedPasswordsList(UiEntriesCallback callback) = 0; - // Sends the password exceptions list to the event router. - virtual void SendPasswordExceptionsList() = 0; - // Gets the password exceptions list. using ExceptionEntries = std::vector<api::passwords_private::ExceptionEntry>; using ExceptionEntriesCallback = 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 105f7e63375..03d191b747e 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 @@ -44,9 +44,7 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, ~PasswordsPrivateDelegateImpl() override; // PasswordsPrivateDelegate implementation. - void SendSavedPasswordsList() override; void GetSavedPasswordsList(UiEntriesCallback callback) override; - void SendPasswordExceptionsList() override; void GetPasswordExceptionsList( const ExceptionEntriesCallback& callback) override; void ChangeSavedPassword( @@ -99,6 +97,9 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, // has been initialized or by deferring it until initialization has completed. void ExecuteFunction(const base::Closure& callback); + void SendSavedPasswordsList(); + void SendPasswordExceptionsList(); + void RemoveSavedPasswordInternal(int id); void RemovePasswordExceptionInternal(int id); void UndoRemoveSavedPasswordOrExceptionInternal(); 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 84d25a7782d..274e5ac9496 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 @@ -25,7 +25,7 @@ #include "components/password_manager/core/browser/password_list_sorter.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/test_password_store.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/test_event_router.h" #include "testing/gtest/include/gtest/gtest.h" @@ -147,7 +147,7 @@ class PasswordsPrivateDelegateImplTest : public testing::Test { void SetUpRouters(); protected: - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; extensions::TestEventRouter* event_router_ = nullptr; diff --git a/chromium/chrome/browser/extensions/api/permissions/permissions_api.h b/chromium/chrome/browser/extensions/api/permissions/permissions_api.h index 87c04d94592..e25d14c49e0 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api.h +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api.h @@ -16,7 +16,7 @@ namespace extensions { // chrome.permissions.contains -class PermissionsContainsFunction : public UIThreadExtensionFunction { +class PermissionsContainsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.contains", PERMISSIONS_CONTAINS) @@ -28,7 +28,7 @@ class PermissionsContainsFunction : public UIThreadExtensionFunction { }; // chrome.permissions.getAll -class PermissionsGetAllFunction : public UIThreadExtensionFunction { +class PermissionsGetAllFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.getAll", PERMISSIONS_GETALL) @@ -40,7 +40,7 @@ class PermissionsGetAllFunction : public UIThreadExtensionFunction { }; // chrome.permissions.remove -class PermissionsRemoveFunction : public UIThreadExtensionFunction { +class PermissionsRemoveFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.remove", PERMISSIONS_REMOVE) @@ -52,7 +52,7 @@ class PermissionsRemoveFunction : public UIThreadExtensionFunction { }; // chrome.permissions.request -class PermissionsRequestFunction : public UIThreadExtensionFunction { +class PermissionsRequestFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("permissions.request", PERMISSIONS_REQUEST) 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 e762b4a7776..02fb0b0860b 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc @@ -143,7 +143,7 @@ class PermissionsAPIUnitTest : public ExtensionServiceTestWithInstall { InitializeEmptyExtensionService(); browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); } diff --git a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h index b632e4e2700..4d1ece03673 100644 --- a/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h +++ b/chromium/chrome/browser/extensions/api/platform_keys/platform_keys_api.h @@ -33,7 +33,7 @@ std::string PlatformKeysTokenIdToApiId( } // namespace platform_keys class PlatformKeysInternalSelectClientCertificatesFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~PlatformKeysInternalSelectClientCertificatesFunction() override; ResponseAction Run() override; @@ -47,8 +47,7 @@ class PlatformKeysInternalSelectClientCertificatesFunction PLATFORMKEYSINTERNAL_SELECTCLIENTCERTIFICATES) }; -class PlatformKeysInternalGetPublicKeyFunction - : public UIThreadExtensionFunction { +class PlatformKeysInternalGetPublicKeyFunction : public ExtensionFunction { private: ~PlatformKeysInternalGetPublicKeyFunction() override; ResponseAction Run() override; @@ -57,7 +56,7 @@ class PlatformKeysInternalGetPublicKeyFunction PLATFORMKEYSINTERNAL_GETPUBLICKEY) }; -class PlatformKeysInternalSignFunction : public UIThreadExtensionFunction { +class PlatformKeysInternalSignFunction : public ExtensionFunction { private: ~PlatformKeysInternalSignFunction() override; ResponseAction Run() override; @@ -71,7 +70,7 @@ class PlatformKeysInternalSignFunction : public UIThreadExtensionFunction { }; class PlatformKeysVerifyTLSServerCertificateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { private: ~PlatformKeysVerifyTLSServerCertificateFunction() override; ResponseAction Run() override; 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 f6600316db6..2b6386c993b 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 @@ -53,7 +53,7 @@ class PlatformKeysTest : public PlatformKeysTestBase { // |PlatformKeysTestBase::SetUpOnMainThread| triggers the user sign-in. ASSERT_TRUE(user_private_slot_db_.is_open()); base::RunLoop loop; - base::PostTaskWithTraitsAndReply( + base::PostTaskAndReply( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTest::SetPrivateSoftwareSlotOnIO, base::Unretained(this), @@ -188,11 +188,13 @@ class PlatformKeysTest : public PlatformKeysTestBase { EXPECT_EQ(user_private_slot_db_.slot(), cert_db->GetPrivateSlot().get()); EXPECT_NE(cert_db->GetPrivateSlot().get(), cert_db->GetPublicSlot().get()); - auto* slot = user_client_cert_slot_ == UserClientCertSlot::kPrivateSlot - ? cert_db->GetPrivateSlot().get() - : cert_db->GetPublicSlot().get(); + crypto::ScopedPK11Slot slot = + user_client_cert_slot_ == UserClientCertSlot::kPrivateSlot + ? cert_db->GetPrivateSlot() + : cert_db->GetPublicSlot(); client_cert1_ = net::ImportClientCertAndKeyFromFile( - net::GetTestCertsDirectory(), "client_1.pem", "client_1.pk8", slot); + net::GetTestCertsDirectory(), "client_1.pem", "client_1.pk8", + slot.get()); ASSERT_TRUE(client_cert1_.get()); // Import a second client cert signed by another CA than client_1 into the 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 305c68f0abf..166d76a626f 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 @@ -155,7 +155,7 @@ void PlatformKeysTestBase::SetUpOnMainThread() { if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTestBase::SetUpTestSystemSlotOnIO, base::Unretained(this), loop.QuitClosure())); @@ -170,7 +170,7 @@ void PlatformKeysTestBase::TearDownOnMainThread() { if (system_token_status() == SystemTokenStatus::EXISTS) { base::RunLoop loop; - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&PlatformKeysTestBase::TearDownTestSystemSlotOnIO, base::Unretained(this), loop.QuitClosure())); @@ -211,14 +211,14 @@ void PlatformKeysTestBase::SetUpTestSystemSlotOnIO( PrepareTestSystemSlotOnIO(test_system_slot_.get()); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(done_callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(done_callback)); } void PlatformKeysTestBase::TearDownTestSystemSlotOnIO( base::OnceClosure done_callback) { test_system_slot_.reset(); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - std::move(done_callback)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + std::move(done_callback)); } 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 d05673e9883..7462a0021d7 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 @@ -91,7 +91,7 @@ void BrowserContextKeyedAPIFactory< } VerifyTrustAPI::VerifyTrustAPI(content::BrowserContext* context) - : io_part_(new IOPart), registry_observer_(this), weak_factory_(this) { + : io_part_(new IOPart), registry_observer_(this) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); registry_observer_.Add(ExtensionRegistry::Get(context)); } @@ -112,7 +112,7 @@ void VerifyTrustAPI::Verify(std::unique_ptr<Params> params, &CallBackOnUI, base::Bind(&VerifyTrustAPI::FinishedVerificationOnUI, weak_factory_.GetWeakPtr(), ui_callback))); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&IOPart::Verify, base::Unretained(io_part_.get()), base::Passed(¶ms), extension_id, finish_callback)); @@ -122,7 +122,7 @@ void VerifyTrustAPI::OnExtensionUnloaded( content::BrowserContext* browser_context, const Extension* extension, UnloadedExtensionReason reason) { - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::IO}, base::BindOnce(&IOPart::OnExtensionUnloaded, base::Unretained(io_part_.get()), extension->id())); @@ -142,9 +142,8 @@ void VerifyTrustAPI::CallBackOnUI(const VerifyCallback& ui_callback, const std::string& error, int return_value, int cert_status) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(ui_callback, error, return_value, cert_status)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(ui_callback, error, return_value, cert_status)); } VerifyTrustAPI::IOPart::~IOPart() { 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 85a022ff8c9..7c08e3d6a3e 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 @@ -100,7 +100,7 @@ class VerifyTrustAPI : public BrowserContextKeyedAPI, ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> registry_observer_; - base::WeakPtrFactory<VerifyTrustAPI> weak_factory_; + base::WeakPtrFactory<VerifyTrustAPI> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(VerifyTrustAPI); }; diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api.h b/chromium/chrome/browser/extensions/api/preference/preference_api.h index 80d27cc4f79..086434a7653 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api.h +++ b/chromium/chrome/browser/extensions/api/preference/preference_api.h @@ -175,7 +175,7 @@ class PrefTransformerInterface { // A base class to provide functionality common to the other *PreferenceFunction // classes. -class PreferenceFunction : public UIThreadExtensionFunction { +class PreferenceFunction : public ExtensionFunction { protected: enum PermissionType { PERMISSION_TYPE_READ, PERMISSION_TYPE_WRITE }; diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.cc b/chromium/chrome/browser/extensions/api/processes/processes_api.cc index 462bda64f31..093fa4fd495 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.cc @@ -509,7 +509,7 @@ ExtensionFunction::ResponseAction ProcessesTerminateFunction::Run() { // This could be a non-renderer child process like a plugin or a nacl // process. Try to get its handle from the BrowserChildProcessHost on the // IO thread. - base::PostTaskWithTraitsAndReplyWithResult( + base::PostTaskAndReplyWithResult( FROM_HERE, {content::BrowserThread::IO}, base::Bind(&ProcessesTerminateFunction::GetProcessHandleOnIO, this, child_process_host_id_), diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.h b/chromium/chrome/browser/extensions/api/processes/processes_api.h index f1ef0d6870d..f72d0525e5b 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.h +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.h @@ -110,9 +110,9 @@ class ProcessesAPI : public BrowserContextKeyedAPI, //////////////////////////////////////////////////////////////////////////////// // This extension function returns the Process object for the renderer process // currently in use by the specified Tab. -class ProcessesGetProcessIdForTabFunction : public UIThreadExtensionFunction { +class ProcessesGetProcessIdForTabFunction : public ExtensionFunction { public: - // UIThreadExtensionFunction: + // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("processes.getProcessIdForTab", @@ -128,9 +128,9 @@ class ProcessesGetProcessIdForTabFunction : public UIThreadExtensionFunction { // Using unique IDs instead of OS process IDs allows two advantages: // * guaranteed uniqueness, since OS process IDs can be reused. // * guards against killing non-Chrome processes. -class ProcessesTerminateFunction : public UIThreadExtensionFunction { +class ProcessesTerminateFunction : public ExtensionFunction { public: - // UIThreadExtensionFunction: + // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("processes.terminate", PROCESSES_TERMINATE) @@ -157,13 +157,13 @@ class ProcessesTerminateFunction : public UIThreadExtensionFunction { //////////////////////////////////////////////////////////////////////////////// // Extension function which returns a set of Process objects, containing the // details corresponding to the process IDs supplied as input. -class ProcessesGetProcessInfoFunction : - public UIThreadExtensionFunction, - public task_manager::TaskManagerObserver { +class ProcessesGetProcessInfoFunction + : public ExtensionFunction, + public task_manager::TaskManagerObserver { public: ProcessesGetProcessInfoFunction(); - // UIThreadExtensionFunction: + // ExtensionFunction: ExtensionFunction::ResponseAction Run() override; // task_manager::TaskManagerObserver: diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc index 9bb8242b4e7..3c7a5953cae 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api.cc @@ -49,11 +49,12 @@ void ProxyEventRouter::OnProxyError( event_router->DispatchEventToRenderers( events::PROXY_ON_PROXY_ERROR, proxy_api_constants::kProxyEventOnProxyError, std::move(args), profile, - true, GURL()); + true, GURL(), false); } else { event_router->BroadcastEventToRenderers( events::PROXY_ON_PROXY_ERROR, - proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL()); + proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL(), + false); } } @@ -82,11 +83,12 @@ void ProxyEventRouter::OnPACScriptError( event_router->DispatchEventToRenderers( events::PROXY_ON_PROXY_ERROR, proxy_api_constants::kProxyEventOnProxyError, std::move(args), profile, - true, GURL()); + true, GURL(), false); } else { event_router->BroadcastEventToRenderers( events::PROXY_ON_PROXY_ERROR, - proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL()); + proxy_api_constants::kProxyEventOnProxyError, std::move(args), GURL(), + false); } } 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 ce37f9dcb86..4440d65734f 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 @@ -10,7 +10,7 @@ namespace extensions { -class ResourcesPrivateGetStringsFunction : public UIThreadExtensionFunction { +class ResourcesPrivateGetStringsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("resourcesPrivate.getStrings", RESOURCESPRIVATE_GETSTRINGS) diff --git a/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS b/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS index ba1319fe08a..fede9e2915a 100644 --- a/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS +++ b/chromium/chrome/browser/extensions/api/safe_browsing_private/OWNERS @@ -1,3 +1,4 @@ +drubery@chromium.org nparker@chromium.org vakh@chromium.org 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 9ad16e7df19..579d813e1be 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 @@ -46,8 +46,8 @@ SafeBrowsingPrivateGetReferrerChainFunction::Run() { content::WebContents* contents = nullptr; if (!ExtensionTabUtil::GetTabById(params->tab_id, browser_context(), - include_incognito_information(), nullptr, - nullptr, &contents, nullptr)) { + include_incognito_information(), + &contents)) { return RespondNow(Error( base::StringPrintf("Could not find tab with id %d.", params->tab_id))); } 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 d28ce05089d..13980a7608a 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 @@ -9,8 +9,7 @@ namespace extensions { -class SafeBrowsingPrivateGetReferrerChainFunction - : public UIThreadExtensionFunction { +class SafeBrowsingPrivateGetReferrerChainFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("safeBrowsingPrivate.getReferrerChain", SAFEBROWSINGPRIVATE_GETREFERRERCHAIN) 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 e9e97071061..bafb52e22ec 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 @@ -25,7 +25,7 @@ #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/navigation_entry.h" #include "content/public/test/browser_side_navigation_test_utils.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "content/public/test/web_contents_tester.h" #include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_test_util.h" @@ -91,7 +91,7 @@ void SafeBrowsingPrivateApiUnitTest::SetUp() { browser_window_ = std::make_unique<TestBrowserWindow>(); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_ = std::make_unique<Browser>(params); 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 5516d33789c..7b0692cb8de 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 @@ -8,13 +8,22 @@ #include "base/strings/stringprintf.h" #include "base/time/time.h" #include "chrome/browser/browser_process.h" +#include "chrome/browser/chrome_content_browser_client.h" #include "chrome/browser/policy/browser_dm_token_storage.h" #include "chrome/browser/policy/chrome_browser_policy_connector.h" +#include "chrome/browser/policy/machine_level_user_cloud_policy_controller.h" #include "chrome/browser/profiles/profile.h" +#include "chrome/browser/profiles/profile_attributes_entry.h" +#include "chrome/browser/profiles/profile_attributes_storage.h" +#include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/identity_manager_factory.h" #include "chrome/common/extensions/api/safe_browsing_private.h" #include "components/policy/core/common/cloud/cloud_policy_client.h" #include "components/policy/core/common/cloud/device_management_service.h" +#include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h" +#include "components/prefs/pref_service.h" +#include "components/safe_browsing/common/safe_browsing_prefs.h" +#include "components/safe_browsing/proto/webprotect.pb.h" #include "components/signin/public/identity_manager/identity_manager.h" #include "content/public/browser/browser_context.h" #include "extensions/browser/event_router.h" @@ -24,7 +33,7 @@ namespace extensions { const base::Feature SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature{ - "SafeBrowsingRealtimeReporting", base::FEATURE_DISABLED_BY_DEFAULT}; + "SafeBrowsingRealtimeReporting", base::FEATURE_ENABLED_BY_DEFAULT}; // Key names used with when building the dictionary to pass to the real-time // reporting API. @@ -41,6 +50,9 @@ const char SafeBrowsingPrivateEventRouter::kKeyReason[] = "reason"; const char SafeBrowsingPrivateEventRouter::kKeyNetErrorCode[] = "netErrorCode"; const char SafeBrowsingPrivateEventRouter::kKeyClickedThrough[] = "clickedThrough"; +const char SafeBrowsingPrivateEventRouter::kKeyTriggeredRules[] = + "triggeredRules"; +const char SafeBrowsingPrivateEventRouter::kKeyThreatType[] = "threatType"; const char SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent[] = "passwordReuseEvent"; @@ -50,12 +62,51 @@ const char SafeBrowsingPrivateEventRouter::kKeyDangerousDownloadEvent[] = "dangerousDownloadEvent"; const char SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent[] = "interstitialEvent"; +const char SafeBrowsingPrivateEventRouter::kKeySensitiveDataEvent[] = + "sensitiveDataEvent"; +const char SafeBrowsingPrivateEventRouter::kKeyLargeUnscannedFileEvent[] = + "largeUnscannedFileEvent"; SafeBrowsingPrivateEventRouter::SafeBrowsingPrivateEventRouter( content::BrowserContext* context) : context_(context) { event_router_ = EventRouter::Get(context_); - InitRealtimeReportingClient(); + + // g_browser_process and/or g_browser_process->local_state() may be null + // in tests. + if (g_browser_process && g_browser_process->local_state()) { + RealtimeReportingPrefChanged(std::string()); + registrar_.Init(g_browser_process->local_state()); + registrar_.Add( + prefs::kUnsafeEventsReportingEnabled, + base::BindRepeating( + &SafeBrowsingPrivateEventRouter::RealtimeReportingPrefChanged, + base::Unretained(this))); + } +} + +// TODO(rogerta): once new event types are implemented, will likely want to +// move this to a more common place. +base::Value BuildRealtimeReport(Profile* profile, base::Value event) { + base::Value context(base::Value::Type::DICTIONARY); + + ProfileAttributesStorage& storage = + g_browser_process->profile_manager()->GetProfileAttributesStorage(); + ProfileAttributesEntry* entry = nullptr; + if (storage.GetProfileAttributesWithPath(profile->GetPath(), &entry)) { + context.SetStringPath("profile.profileName", entry->GetName()); + context.SetStringPath("profile.gaiaEmail", entry->GetUserName()); + } + + context.SetStringPath("profile.profilePath", profile->GetPath().value()); + context.SetStringPath("browser.userAgent", GetUserAgent()); + + base::Value report(base::Value::Type::DICTIONARY); + report.SetKey(policy::RealtimeReportingJobConfiguration::kContextKey, + std::move(context)); + report.SetKey(policy::RealtimeReportingJobConfiguration::kEventKey, + std::move(event)); + return report; } SafeBrowsingPrivateEventRouter::~SafeBrowsingPrivateEventRouter() {} @@ -83,7 +134,7 @@ void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordReuseDetected( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -108,7 +159,7 @@ void SafeBrowsingPrivateEventRouter::OnPolicySpecifiedPasswordChanged( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUserName, user_name); @@ -139,7 +190,7 @@ void SafeBrowsingPrivateEventRouter::OnDangerousDownloadOpened( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -175,7 +226,7 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialShown( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -212,7 +263,7 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded( event_router_->BroadcastEvent(std::move(extension_event)); } - if (client_) { + if (IsRealtimeReportingEnabled()) { // Convert |params| to a real-time event dictionary and report it. base::Value event(base::Value::Type::DICTIONARY); event.SetStringKey(kKeyUrl, params.url); @@ -224,6 +275,60 @@ void SafeBrowsingPrivateEventRouter::OnSecurityInterstitialProceeded( } } +void SafeBrowsingPrivateEventRouter::OnDangerousDeepScanningResult( + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256, + const std::string& threat_type) { + if (IsRealtimeReportingEnabled()) { + // Create a real-time event dictionary from the arguments and report it. + base::Value event(base::Value::Type::DICTIONARY); + event.SetStringKey(kKeyUrl, url.spec()); + event.SetStringKey(kKeyFileName, file_name); + event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + event.SetStringKey(kKeyThreatType, threat_type); + ReportRealtimeEvent(kKeyDangerousDownloadEvent, std::move(event)); + } +} + +void SafeBrowsingPrivateEventRouter::OnSensitiveDataEvent( + const safe_browsing::DlpDeepScanningVerdict& verdict, + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256) { + if (IsRealtimeReportingEnabled()) { + // Create a real-time event dictionary from the arguments and report it. + base::Value event(base::Value::Type::DICTIONARY); + event.SetStringKey(kKeyUrl, url.spec()); + event.SetStringKey(kKeyFileName, file_name); + event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + + base::ListValue triggered_rules; + for (auto rule : verdict.triggered_rules()) { + triggered_rules.AppendString(rule.rule_name()); + } + event.SetKey(kKeyTriggeredRules, std::move(triggered_rules)); + ReportRealtimeEvent(kKeySensitiveDataEvent, std::move(event)); + } +} + +void SafeBrowsingPrivateEventRouter::OnLargeUnscannedFileEvent( + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256) { + if (IsRealtimeReportingEnabled()) { + // Create a real-time event dictionary from the arguments and report it. + base::Value event(base::Value::Type::DICTIONARY); + event.SetStringKey(kKeyUrl, url.spec()); + event.SetStringKey(kKeyFileName, file_name); + event.SetStringKey(kKeyDownloadDigestSha256, download_digest_sha256); + event.SetStringKey(kKeyProfileUserName, GetProfileUserName()); + ReportRealtimeEvent(kKeyLargeUnscannedFileEvent, std::move(event)); + } +} + void SafeBrowsingPrivateEventRouter::SetCloudPolicyClientForTesting( std::unique_ptr<policy::CloudPolicyClient> client) { DCHECK_EQ(nullptr, client_.get()); @@ -231,6 +336,20 @@ void SafeBrowsingPrivateEventRouter::SetCloudPolicyClientForTesting( } void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() { +#if !defined(OS_CHROMEOS) + // This method is not compiled on chromeos because + // MachineLevelUserCloudPolicyController does not exist. Also, + // policy::BrowserDMTokenStorage::Get()->RetrieveDMToken() does return a + // valid token either. Once these are fixed the #if !define can be removed. + // If already initialized, do nothing. + if (client_) + return; + + if (!policy::MachineLevelUserCloudPolicyController:: + IsMachineLevelUserCloudPolicyEnabled()) { + return; + } + if (!base::FeatureList::IsEnabled(kRealtimeReportingFeature)) return; @@ -242,7 +361,7 @@ void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() { if (!identity_manager_) return; - // |device_management_service| may be null in tests. If there is no device + // |device_management_service| may be null in tests. If there is no device // management service don't enable the real-time reporting API since the // router won't be able to create the reporting server client below. policy::DeviceManagementService* device_management_service = @@ -284,6 +403,22 @@ void SafeBrowsingPrivateEventRouter::InitRealtimeReportingClient() { dm_token, client_id, /*user_affiliation_ids=*/std::vector<std::string>()); } +#endif +} + +bool SafeBrowsingPrivateEventRouter::IsRealtimeReportingEnabled() { + // g_browser_process and/or g_browser_process->local_state() may be null + // in tests. + return g_browser_process && g_browser_process->local_state() && + g_browser_process->local_state()->GetBoolean( + prefs::kUnsafeEventsReportingEnabled); +} + +void SafeBrowsingPrivateEventRouter::RealtimeReportingPrefChanged( + const std::string& pref) { + // If the reporting policy has been turned on, try to initialized now. + if (IsRealtimeReportingEnabled()) + InitRealtimeReportingClient(); } void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent(const char* name, @@ -300,7 +435,10 @@ void SafeBrowsingPrivateEventRouter::ReportRealtimeEvent(const char* name, wrapper.SetStringKey("time", now_str); wrapper.SetKey(name, std::move(event)); - client_->UploadRealtimeReport(std::move(wrapper), base::DoNothing()); + client_->UploadRealtimeReport( + BuildRealtimeReport(Profile::FromBrowserContext(context_), + std::move(wrapper)), + base::DoNothing()); } std::string SafeBrowsingPrivateEventRouter::GetProfileUserName() { 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 aa247397917..9a3441613dc 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 @@ -12,6 +12,7 @@ #include "base/macros.h" #include "base/values.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/prefs/pref_change_registrar.h" namespace content { class BrowserContext; @@ -31,6 +32,10 @@ namespace policy { class CloudPolicyClient; } +namespace safe_browsing { +class DlpDeepScanningVerdict; +} + namespace extensions { // An event router that observes Safe Browsing events and notifies listeners. @@ -52,11 +57,15 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { static const char kKeyReason[]; static const char kKeyNetErrorCode[]; static const char kKeyClickedThrough[]; + static const char kKeyTriggeredRules[]; + static const char kKeyThreatType[]; static const char kKeyPasswordReuseEvent[]; static const char kKeyPasswordChangedEvent[]; static const char kKeyDangerousDownloadEvent[]; static const char kKeyInterstitialEvent[]; + static const char kKeySensitiveDataEvent[]; + static const char kKeyLargeUnscannedFileEvent[]; explicit SafeBrowsingPrivateEventRouter(content::BrowserContext* context); @@ -86,6 +95,24 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { const std::string& reason, int net_error_code); + // Notifies listeners that deep scanning detected a dangerous download. + void OnDangerousDeepScanningResult(const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256, + const std::string& threat_type); + + // Notifies listeners that scanning for sensitive data detected a violation. + void OnSensitiveDataEvent( + const safe_browsing::DlpDeepScanningVerdict& verdict, + const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256); + + // Notifies listeners that deep scanning failed, since the file was too large. + void OnLargeUnscannedFileEvent(const GURL& url, + const std::string& file_name, + const std::string& download_digest_sha256); + void SetCloudPolicyClientForTesting( std::unique_ptr<policy::CloudPolicyClient> client); @@ -95,6 +122,12 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { // with CBCM and the appropriate policies are enabled. void InitRealtimeReportingClient(); + // Determines if the real-time reporting feature is enabled. + bool IsRealtimeReportingEnabled(); + + // Called whenever the real-time reporting policy changes. + void RealtimeReportingPrefChanged(const std::string& pref); + // Report safe browsing event through real-time reporting channel, if enabled. void ReportRealtimeEvent(const char* name, base::Value event); @@ -106,6 +139,7 @@ class SafeBrowsingPrivateEventRouter : public KeyedService { signin::IdentityManager* identity_manager_ = nullptr; EventRouter* event_router_ = nullptr; std::unique_ptr<policy::CloudPolicyClient> client_; + PrefChangeRegistrar registrar_; DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouter); }; 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 bf6702672f3..26c8393207c 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 @@ -6,13 +6,16 @@ #include "base/bind.h" #include "base/strings/utf_string_conversions.h" #include "base/test/mock_callback.h" -#include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chrome/browser/extensions/api/safe_browsing_private/safe_browsing_private_event_router_factory.h" #include "chrome/common/extensions/api/safe_browsing_private.h" +#include "chrome/test/base/testing_browser_process.h" #include "chrome/test/base/testing_profile.h" +#include "chrome/test/base/testing_profile_manager.h" #include "components/policy/core/common/cloud/mock_cloud_policy_client.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "components/policy/core/common/cloud/realtime_reporting_job_configuration.h" +#include "components/safe_browsing/common/safe_browsing_prefs.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/test_event_router.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -67,64 +70,77 @@ std::unique_ptr<KeyedService> BuildSafeBrowsingPrivateEventRouter( class SafeBrowsingPrivateEventRouterTest : public testing::Test { public: - SafeBrowsingPrivateEventRouterTest() = default; + SafeBrowsingPrivateEventRouterTest() + : profile_manager_(TestingBrowserProcess::GetGlobal()) { + EXPECT_TRUE(profile_manager_.SetUp()); + profile_ = profile_manager_.CreateTestingProfile("test-user"); + } + ~SafeBrowsingPrivateEventRouterTest() override = default; void TriggerOnPolicySpecifiedPasswordReuseDetectedEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnPolicySpecifiedPasswordReuseDetected(GURL("https://phishing.com/"), "user_name_1", /*is_phishing_url*/ true); } void TriggerOnPolicySpecifiedPasswordChangedEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnPolicySpecifiedPasswordChanged("user_name_2"); } void TriggerOnDangerousDownloadOpenedEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnDangerousDownloadOpened(GURL("https://evil.com/malware.exe"), "/path/to/malware.exe", "sha256_or_malware_exe"); } void TriggerOnSecurityInterstitialShownEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnSecurityInterstitialShown(GURL("https://phishing.com/"), "PHISHING", 0); } void TriggerOnSecurityInterstitialProceededEvent() { - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->OnSecurityInterstitialProceeded(GURL("https://phishing.com/"), "PHISHING", -201); } - void SetUpRouters() { - event_router_ = extensions::CreateAndUseTestEventRouter(&profile_); - SafeBrowsingPrivateEventRouterFactory::GetInstance()->SetTestingFactory( - &profile_, base::BindRepeating(&BuildSafeBrowsingPrivateEventRouter)); + void SetReportingPolicy(bool enabled) { + TestingBrowserProcess::GetGlobal()->local_state()->SetBoolean( + prefs::kUnsafeEventsReportingEnabled, enabled); - // Make sure real-time feature is eanbled so that the tests will run. - scoped_feature_list_.InitAndEnableFeature( - SafeBrowsingPrivateEventRouter::kRealtimeReportingFeature); + // If we are not enabling reporting, or if the client has already been + // set for testing, just return. + if (!enabled || client_) + return; // Set a mock cloud policy client in the router. The router will own the // client, but a pointer to the client is maintained in the test class to // manage expectations. client_ = new policy::MockCloudPolicyClient(); std::unique_ptr<policy::CloudPolicyClient> client(client_); - SafeBrowsingPrivateEventRouterFactory::GetForProfile(&profile_) + SafeBrowsingPrivateEventRouterFactory::GetForProfile(profile_) ->SetCloudPolicyClientForTesting(std::move(client)); } + void SetUpRouters(bool realtime_reporting_enable = true) { + event_router_ = extensions::CreateAndUseTestEventRouter(profile_); + SafeBrowsingPrivateEventRouterFactory::GetInstance()->SetTestingFactory( + profile_, base::BindRepeating(&BuildSafeBrowsingPrivateEventRouter)); + + SetReportingPolicy(realtime_reporting_enable); + } + protected: - content::TestBrowserThreadBundle thread_bundle_; - base::test::ScopedFeatureList scoped_feature_list_; - TestingProfile profile_; + content::BrowserTaskEnvironment task_environment_; + TestingProfileManager profile_manager_; + TestingProfile* profile_; extensions::TestEventRouter* event_router_ = nullptr; - policy::MockCloudPolicyClient* client_; + policy::MockCloudPolicyClient* client_ = nullptr; private: DISALLOW_COPY_AND_ASSIGN(SafeBrowsingPrivateEventRouterTest); @@ -137,9 +153,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnReuseDetected) { kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnPolicySpecifiedPasswordReuseDetectedEvent(); base::RunLoop().RunUntilIdle(); @@ -149,9 +165,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnReuseDetected) { EXPECT_EQ("user_name_1", captured_args.FindKey("userName")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent); + wrapper->FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordReuseEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("https://phishing.com/", *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyUrl)); @@ -165,9 +185,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnPasswordChanged) { api::safe_browsing_private::OnPolicySpecifiedPasswordChanged::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnPolicySpecifiedPasswordChangedEvent(); base::RunLoop().RunUntilIdle(); @@ -176,9 +196,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnPasswordChanged) { EXPECT_EQ("user_name_2", captured_args.GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); - base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyPasswordChangedEvent); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); + base::Value* event = wrapper->FindKey( + SafeBrowsingPrivateEventRouter::kKeyPasswordChangedEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("user_name_2", *event->FindStringKey( SafeBrowsingPrivateEventRouter::kKeyUserName)); @@ -190,9 +214,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnDangerousDownloadOpened) { api::safe_browsing_private::OnDangerousDownloadOpened::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnDangerousDownloadOpenedEvent(); base::RunLoop().RunUntilIdle(); @@ -207,8 +231,12 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnDangerousDownloadOpened) { captured_args.FindKey("downloadDigestSha256")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); - base::Value* event = wrapper.FindKey( + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); + base::Value* event = wrapper->FindKey( SafeBrowsingPrivateEventRouter::kKeyDangerousDownloadEvent); EXPECT_NE(nullptr, event); EXPECT_EQ( @@ -223,9 +251,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, api::safe_browsing_private::OnSecurityInterstitialProceeded::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnSecurityInterstitialProceededEvent(); base::RunLoop().RunUntilIdle(); @@ -237,9 +265,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, EXPECT_EQ("", captured_args.FindKey("userName")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); + wrapper->FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("PHISHING", *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyReason)); @@ -255,9 +287,9 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) { api::safe_browsing_private::OnSecurityInterstitialShown::kEventName); event_router_->AddEventObserver(&event_observer); - base::Value wrapper; + base::Value report; EXPECT_CALL(*client_, UploadRealtimeReport(_, _)) - .WillOnce(CaptureArg(&wrapper)); + .WillOnce(CaptureArg(&report)); TriggerOnSecurityInterstitialShownEvent(); base::RunLoop().RunUntilIdle(); @@ -269,9 +301,13 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) { EXPECT_EQ("", captured_args.FindKey("userName")->GetString()); Mock::VerifyAndClearExpectations(client_); - EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper.type()); + EXPECT_EQ(base::Value::Type::DICTIONARY, report.type()); + base::Value* wrapper = + report.FindKey(policy::RealtimeReportingJobConfiguration::kEventKey); + ASSERT_NE(nullptr, wrapper); + EXPECT_EQ(base::Value::Type::DICTIONARY, wrapper->type()); base::Value* event = - wrapper.FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); + wrapper->FindKey(SafeBrowsingPrivateEventRouter::kKeyInterstitialEvent); EXPECT_NE(nullptr, event); EXPECT_EQ("PHISHING", *event->FindStringKey(SafeBrowsingPrivateEventRouter::kKeyReason)); @@ -280,4 +316,45 @@ TEST_F(SafeBrowsingPrivateEventRouterTest, TestOnSecurityInterstitialShown) { EXPECT_FALSE( *event->FindBoolKey(SafeBrowsingPrivateEventRouter::kKeyClickedThrough)); } + +TEST_F(SafeBrowsingPrivateEventRouterTest, PolicyControlOnToOffIsDynamic) { + SetUpRouters(); + SafeBrowsingEventObserver event_observer( + api::safe_browsing_private::OnSecurityInterstitialShown::kEventName); + event_router_->AddEventObserver(&event_observer); + + EXPECT_CALL(*client_, UploadRealtimeReport(_, _)).Times(1); + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + Mock::VerifyAndClearExpectations(client_); + + // Now turn off policy. This time no report should be generated. + SetReportingPolicy(false); + EXPECT_CALL(*client_, UploadRealtimeReport(_, _)).Times(0); + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + Mock::VerifyAndClearExpectations(client_); +} + +TEST_F(SafeBrowsingPrivateEventRouterTest, PolicyControlOffToOnIsDynamic) { + SetUpRouters(/*realtime_reporting_enable=*/false); + SafeBrowsingEventObserver event_observer( + api::safe_browsing_private::OnSecurityInterstitialShown::kEventName); + event_router_->AddEventObserver(&event_observer); + + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + + // Now turn on policy. + SetReportingPolicy(true); + EXPECT_CALL(*client_, UploadRealtimeReport(_, _)).Times(1); + TriggerOnSecurityInterstitialShownEvent(); + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(1u, event_observer.PassEventArgs().GetList().size()); + Mock::VerifyAndClearExpectations(client_); +} + } // 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 7156357f02b..882f22b3fdf 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc @@ -81,7 +81,8 @@ api::tabs::Tab CreateTabModelHelper( int index, bool pinned, bool active, - const Extension* extension) { + const Extension* extension, + Feature::Context context) { api::tabs::Tab tab_struct; const GURL& url = current_navigation.virtual_url(); @@ -100,7 +101,13 @@ api::tabs::Tab CreateTabModelHelper( tab_struct.index = index; tab_struct.pinned = pinned; tab_struct.active = active; - ExtensionTabUtil::ScrubTabForExtension(extension, nullptr, &tab_struct); + + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, context, url); + if (scrub_tab_behavior != ExtensionTabUtil::kDontScrubTab) { + ExtensionTabUtil::ScrubTabForExtension(extension, nullptr, &tab_struct, + scrub_tab_behavior); + } return tab_struct; } @@ -148,7 +155,7 @@ api::tabs::Tab SessionsGetRecentlyClosedFunction::CreateTabModel( return CreateTabModelHelper(tab.navigations[tab.current_navigation_index], base::NumberToString(tab.id.id()), tab.tabstrip_index, tab.pinned, active, - extension()); + extension(), source_context_type()); } std::unique_ptr<api::windows::Window> @@ -228,7 +235,7 @@ api::tabs::Tab SessionsGetDevicesFunction::CreateTabModel( std::string session_id = SessionId(session_tag, tab.tab_id.id()).ToString(); return CreateTabModelHelper( tab.navigations[tab.normalized_navigation_index()], session_id, tab_index, - tab.pinned, active, extension()); + tab.pinned, active, extension(), source_context_type()); } std::unique_ptr<api::windows::Window> @@ -269,12 +276,18 @@ SessionsGetDevicesFunction::CreateWindowModel( api::windows::WindowType type = api::windows::WINDOW_TYPE_NONE; switch (window.type) { - case sessions::SessionWindow::TYPE_TABBED: + case sessions::SessionWindow::TYPE_NORMAL: type = api::windows::WINDOW_TYPE_NORMAL; break; case sessions::SessionWindow::TYPE_POPUP: type = api::windows::WINDOW_TYPE_POPUP; break; + case sessions::SessionWindow::TYPE_APP: + type = api::windows::WINDOW_TYPE_APP; + break; + case sessions::SessionWindow::TYPE_DEVTOOLS: + type = api::windows::WINDOW_TYPE_DEVTOOLS; + break; } api::windows::WindowState state = api::windows::WINDOW_STATE_NONE; @@ -383,8 +396,11 @@ ExtensionFunction::ResponseAction SessionsGetDevicesFunction::Run() { ExtensionFunction::ResponseValue SessionsRestoreFunction::GetRestoredTabResult( content::WebContents* contents) { + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension(), source_context_type(), + contents); std::unique_ptr<api::tabs::Tab> tab(ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension())); + contents, scrub_tab_behavior, extension())); std::unique_ptr<api::sessions::Session> restored_session( CreateSessionModelHelper(base::Time::Now().ToTimeT(), std::move(tab), std::unique_ptr<api::windows::Window>())); @@ -401,7 +417,8 @@ SessionsRestoreFunction::GetRestoredWindowResult(int window_id) { } std::unique_ptr<base::DictionaryValue> window_value( ExtensionTabUtil::CreateWindowValueForExtension( - *browser, extension(), ExtensionTabUtil::kPopulateTabs)); + *browser, extension(), ExtensionTabUtil::kPopulateTabs, + source_context_type())); std::unique_ptr<api::windows::Window> window( api::windows::Window::FromValue(*window_value)); return ArgumentList(Restore::Results::Create(*CreateSessionModelHelper( diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h index d859f6434bb..6d177c1ce6e 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.h +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.h @@ -27,7 +27,7 @@ namespace extensions { class SessionId; -class SessionsGetRecentlyClosedFunction : public UIThreadExtensionFunction { +class SessionsGetRecentlyClosedFunction : public ExtensionFunction { protected: ~SessionsGetRecentlyClosedFunction() override {} ResponseAction Run() override; @@ -43,7 +43,7 @@ class SessionsGetRecentlyClosedFunction : public UIThreadExtensionFunction { const sessions::TabRestoreService::Entry& entry); }; -class SessionsGetDevicesFunction : public UIThreadExtensionFunction { +class SessionsGetDevicesFunction : public ExtensionFunction { protected: ~SessionsGetDevicesFunction() override {} ResponseAction Run() override; @@ -64,7 +64,7 @@ class SessionsGetDevicesFunction : public UIThreadExtensionFunction { const sync_sessions::SyncedSession* session); }; -class SessionsRestoreFunction : public UIThreadExtensionFunction { +class SessionsRestoreFunction : public ExtensionFunction { protected: ~SessionsRestoreFunction() override {} ResponseAction Run() override; 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 3d9892b6d8b..ed9c0d567e0 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 @@ -190,7 +190,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionBrowserTest, OverridenDSEPersists) { std::string new_tab_url_ext = ext_turl.new_tab_url_ref().ReplaceSearchTerms( TemplateURLRef::SearchTermsArgs(base::string16()), - UIThreadSearchTermsData(profile)); + UIThreadSearchTermsData()); EXPECT_EQ(new_tab_url_ext, search::GetNewTabPageURL(profile).spec()); diff --git a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc index 620e7fa6e2f..9e1dae7356f 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/generated_time_zone_pref_base.cc @@ -42,11 +42,14 @@ void GeneratedTimeZonePrefBase::UpdateTimeZonePrefControlledBy( IsTimeZoneResolutionPolicyControlled()) { out_pref->controlled_by = settings_api::CONTROLLED_BY_DEVICE_POLICY; out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED; - } else if (profile_->IsChild() && - !base::FeatureList::IsEnabled( - features::kParentAccessCodeForTimeChange)) { - out_pref->controlled_by = settings_api::ControlledBy::CONTROLLED_BY_PARENT; - out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED; + } else if (profile_->IsChild()) { + out_pref->controlled_by = settings_api::CONTROLLED_BY_PARENT; + if (base::FeatureList::IsEnabled( + features::kParentAccessCodeForTimeChange)) { + out_pref->enforcement = settings_api::ENFORCEMENT_PARENT_SUPERVISED; + } else { + out_pref->enforcement = settings_api::ENFORCEMENT_ENFORCED; + } } else if (!profile_->IsSameProfile( ProfileManager::GetPrimaryUserProfile())) { out_pref->controlled_by = settings_api::CONTROLLED_BY_PRIMARY_USER; 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 f41d39b5833..40e299858d2 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/settings_private/prefs_util.h" #include "base/feature_list.h" +#include "build/branding_buildflags.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/api/settings_private/generated_prefs.h" @@ -50,11 +51,10 @@ #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/settings/cros_settings.h" +#include "chrome/browser/chromeos/settings/supervised_user_cros_settings_provider.h" #include "chrome/browser/chromeos/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 "chrome/browser/supervised_user/supervised_user_service.h" -#include "chrome/browser/supervised_user/supervised_user_service_factory.h" #include "chromeos/constants/chromeos_features.h" #include "chromeos/services/assistant/public/cpp/assistant_prefs.h" #include "chromeos/settings/cros_settings_names.h" @@ -83,8 +83,9 @@ bool IsRestrictedCrosSettingForChildUser(Profile* profile, if (!profile->IsChild()) return false; - return SupervisedUserServiceFactory::GetForProfile(profile) - ->IsRestrictedCrosSettingForChildUser(pref_name); + return chromeos::CrosSettings::Get() + ->supervised_user_cros_settings_provider() + ->HandlesSetting(pref_name); } const base::Value* GetRestrictedCrosSettingValueForChildUser( @@ -94,8 +95,9 @@ const base::Value* GetRestrictedCrosSettingValueForChildUser( // pre-set. DCHECK(IsRestrictedCrosSettingForChildUser(profile, pref_name)); - return SupervisedUserServiceFactory::GetForProfile(profile) - ->GetRestrictedCrosSettingValueForChildUser(pref_name); + return chromeos::CrosSettings::Get() + ->supervised_user_cros_settings_provider() + ->Get(pref_name); } #endif @@ -230,6 +232,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[password_manager::prefs::kCredentialsEnableAutosignin] = settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[password_manager::prefs::kPasswordLeakDetectionEnabled] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; // Privacy page (*s_whitelist)[::prefs::kSigninAllowedOnNextStartup] = @@ -410,6 +414,9 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[ash::prefs::kAccessibilitySwitchAccessAutoScanSpeedMs] = settings_api::PrefType::PREF_TYPE_NUMBER; + (*s_whitelist) + [ash::prefs::kAccessibilitySwitchAccessAutoScanKeyboardSpeedMs] = + settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[ash::prefs::kAccessibilityVirtualKeyboardEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[ash::prefs::kAccessibilityMonoAudioEnabled] = @@ -444,13 +451,13 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[chromeos::assistant::prefs::kAssistantDisabledByPolicy] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[arc::prefs::kVoiceInteractionEnabled] = + (*s_whitelist)[chromeos::assistant::prefs::kAssistantEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[arc::prefs::kVoiceInteractionContextEnabled] = + (*s_whitelist)[chromeos::assistant::prefs::kAssistantContextEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[chromeos::assistant::prefs::kAssistantHotwordAlwaysOn] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[arc::prefs::kVoiceInteractionHotwordEnabled] = + (*s_whitelist)[chromeos::assistant::prefs::kAssistantHotwordEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[chromeos::assistant::prefs::kAssistantLaunchWithMicOpen] = settings_api::PrefType::PREF_TYPE_BOOLEAN; @@ -470,7 +477,9 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[prefs::kRestoreLastLockScreenNote] = settings_api::PrefType::PREF_TYPE_BOOLEAN; - (*s_whitelist)[ash::prefs::kLockScreenMediaKeysEnabled] = + (*s_whitelist)[::prefs::kSettingsShowBrowserBanner] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kSettingsShowOSBanner] = settings_api::PrefType::PREF_TYPE_BOOLEAN; // Bluetooth & Internet settings. @@ -546,6 +555,10 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kMouseReverseScroll] = settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kMouseAcceleration] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[::prefs::kTouchpadAcceleration] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kMouseSensitivity] = settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[::prefs::kLanguageRemapSearchKeyTo] = @@ -578,8 +591,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_DICTIONARY; (*s_whitelist)[chromeos::kDisplayRotationDefault] = settings_api::PrefType::PREF_TYPE_DICTIONARY; - (*s_whitelist)[arc::prefs::kArcHasAccessToRemovableMedia] = - settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[arc::prefs::kArcVisibleExternalStorages] = + settings_api::PrefType::PREF_TYPE_LIST; // Native Printing settings. (*s_whitelist)[::prefs::kUserNativePrintersAllowed] = @@ -612,12 +625,12 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { (*s_whitelist)[proxy_config::prefs::kProxy] = settings_api::PrefType::PREF_TYPE_DICTIONARY; -#if defined(GOOGLE_CHROME_BUILD) +#if BUILDFLAG(GOOGLE_CHROME_BRANDING) (*s_whitelist)[::prefs::kMediaRouterEnableCloudServices] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[::prefs::kUserFeedbackAllowed] = settings_api::PrefType::PREF_TYPE_BOOLEAN; -#endif // defined(GOOGLE_CHROME_BUILD) +#endif // BUILDFLAG(GOOGLE_CHROME_BRANDING) // Media Remoting settings. (*s_whitelist)[::prefs::kMediaRouterMediaRemotingEnabled] = @@ -773,7 +786,7 @@ std::unique_ptr<settings_api::PrefObject> PrefsUtil::GetPref( if (IsRestrictedCrosSettingForChildUser(profile_, name)) { pref_object->controlled_by = - settings_api::ControlledBy::CONTROLLED_BY_CHILD_RESTRICTIONS; + settings_api::ControlledBy::CONTROLLED_BY_CHILD_RESTRICTION; pref_object->enforcement = settings_api::Enforcement::ENFORCEMENT_ENFORCED; pref_object->value = std::make_unique<base::Value>( GetRestrictedCrosSettingValueForChildUser(profile_, name)->Clone()); 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 f9a377d7a86..ec333f223f1 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 @@ -13,7 +13,7 @@ namespace extensions { // Implements the chrome.settingsPrivate.setPref method. -class SettingsPrivateSetPrefFunction : public UIThreadExtensionFunction { +class SettingsPrivateSetPrefFunction : public ExtensionFunction { public: SettingsPrivateSetPrefFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.setPref", SETTINGSPRIVATE_SETPREF) @@ -21,14 +21,14 @@ class SettingsPrivateSetPrefFunction : public UIThreadExtensionFunction { protected: ~SettingsPrivateSetPrefFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateSetPrefFunction); }; // Implements the chrome.settingsPrivate.getAllPrefs method. -class SettingsPrivateGetAllPrefsFunction : public UIThreadExtensionFunction { +class SettingsPrivateGetAllPrefsFunction : public ExtensionFunction { public: SettingsPrivateGetAllPrefsFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.getAllPrefs", @@ -37,14 +37,14 @@ class SettingsPrivateGetAllPrefsFunction : public UIThreadExtensionFunction { protected: ~SettingsPrivateGetAllPrefsFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetAllPrefsFunction); }; // Implements the chrome.settingsPrivate.getPref method. -class SettingsPrivateGetPrefFunction : public UIThreadExtensionFunction { +class SettingsPrivateGetPrefFunction : public ExtensionFunction { public: SettingsPrivateGetPrefFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.getPref", SETTINGSPRIVATE_GETPREF) @@ -52,15 +52,14 @@ class SettingsPrivateGetPrefFunction : public UIThreadExtensionFunction { protected: ~SettingsPrivateGetPrefFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetPrefFunction); }; // Implements the chrome.settingsPrivate.getDefaultZoom method. -class SettingsPrivateGetDefaultZoomFunction - : public UIThreadExtensionFunction { +class SettingsPrivateGetDefaultZoomFunction : public ExtensionFunction { public: SettingsPrivateGetDefaultZoomFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.getDefaultZoom", @@ -69,15 +68,14 @@ class SettingsPrivateGetDefaultZoomFunction protected: ~SettingsPrivateGetDefaultZoomFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateGetDefaultZoomFunction); }; // Implements the chrome.settingsPrivate.setDefaultZoom method. -class SettingsPrivateSetDefaultZoomFunction - : public UIThreadExtensionFunction { +class SettingsPrivateSetDefaultZoomFunction : public ExtensionFunction { public: SettingsPrivateSetDefaultZoomFunction() {} DECLARE_EXTENSION_FUNCTION("settingsPrivate.setDefaultZoom", @@ -86,7 +84,7 @@ class SettingsPrivateSetDefaultZoomFunction protected: ~SettingsPrivateSetDefaultZoomFunction() override; - // UIThreadExtensionFunction overrides. + // ExtensionFunction overrides. ResponseAction Run() override; DISALLOW_COPY_AND_ASSIGN(SettingsPrivateSetDefaultZoomFunction); 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 6b7a7b7f1c6..877aebd6539 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 @@ -3,7 +3,6 @@ // found in the LICENSE file. #include "base/values.h" -#include "chrome/browser/chromeos/login/mixin_based_in_process_browser_test.h" #include "chrome/browser/chromeos/login/test/guest_session_mixin.h" #include "chrome/browser/extensions/api/settings_private/prefs_util_enums.h" #include "chrome/browser/extensions/api/settings_private/settings_private_api.h" @@ -13,14 +12,14 @@ #include "chrome/browser/extensions/api/settings_private/settings_private_event_router_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" +#include "chrome/test/base/mixin_based_in_process_browser_test.h" #include "content/public/test/browser_test.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { namespace { -class SettingsPrivateGuestModeTest - : public chromeos::MixinBasedInProcessBrowserTest { +class SettingsPrivateGuestModeTest : public MixinBasedInProcessBrowserTest { protected: chromeos::GuestSessionMixin guest_session_{&mixin_host_}; }; diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h index b24066be1e8..c46442ec14b 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h @@ -37,7 +37,7 @@ std::vector<std::unique_ptr<syncer::DeviceInfo>> GetAllSignedInDevices( syncer::DeviceInfoTracker* device_tracker, ExtensionPrefs* extension_prefs); -class SignedInDevicesGetFunction : public UIThreadExtensionFunction { +class SignedInDevicesGetFunction : public ExtensionFunction { protected: ~SignedInDevicesGetFunction() override {} diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc index ad64682385f..1d5d4eac138 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api_unittest.cc @@ -20,7 +20,7 @@ #include "components/sync_device_info/device_info.h" #include "components/sync_device_info/device_info_sync_service.h" #include "components/sync_device_info/fake_device_info_tracker.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/common/extension.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -32,7 +32,7 @@ using testing::Return; namespace extensions { TEST(SignedInDevicesAPITest, GetSignedInDevices) { - content::TestBrowserThreadBundle thread_bundle; + content::BrowserTaskEnvironment task_environment; TestingProfile profile; FakeDeviceInfoTracker device_tracker; TestExtensionPrefs extension_prefs(base::ThreadTaskRunnerHandle::Get().get()); diff --git a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc index 17081c07d58..73286a5e48d 100644 --- a/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/signed_in_devices/signed_in_devices_manager_unittest.cc @@ -14,7 +14,7 @@ #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_store.h" #include "components/signin/public/identity_manager/identity_test_environment.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/event_router.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" @@ -23,7 +23,7 @@ namespace extensions { // Adds a listener and removes it. TEST(SignedInDevicesManager, UpdateListener) { - content::TestBrowserThreadBundle thread_bundle; + content::BrowserTaskEnvironment task_environment; std::unique_ptr<TestingProfile> profile = IdentityTestEnvironmentProfileAdaptor:: 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 5baa299ebe1..10356bc10a2 100644 --- a/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc @@ -38,13 +38,13 @@ class UDPSocketUnitTest : public extensions::ExtensionServiceTestBase { content::BrowserContext::GetDefaultStoragePartition(profile()) ->GetNetworkContext(); network::mojom::UDPSocketPtrInfo socket; - network::mojom::UDPSocketReceiverPtr receiver_ptr; - network::mojom::UDPSocketReceiverRequest receiver_request = - mojo::MakeRequest(&receiver_ptr); + network::mojom::UDPSocketListenerPtr listener_ptr; + network::mojom::UDPSocketListenerRequest listener_request = + mojo::MakeRequest(&listener_ptr); network_context->CreateUDPSocket(mojo::MakeRequest(&socket), - std::move(receiver_ptr)); + std::move(listener_ptr)); return std::make_unique<UDPSocket>( - std::move(socket), std::move(receiver_request), "abcdefghijklmnopqrst"); + std::move(socket), std::move(listener_request), "abcdefghijklmnopqrst"); } }; @@ -174,7 +174,7 @@ TEST_F(UDPSocketUnitTest, TestUDPMulticastRecv) { std::unique_ptr<UDPSocket> src = CreateSocket(); std::unique_ptr<UDPSocket> dest = CreateSocket(); - // Receiver + // Listener { net::TestCompletionCallback callback; dest->Bind("0.0.0.0", kPort, callback.callback()); 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 ef8acf121ef..91b42ede413 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 @@ -205,9 +205,9 @@ void ManagedValueStoreCache::ExtensionTracker::LoadSchemasOnFileTaskRunner( (*components)[(*it)->id()] = schema; } - base::PostTaskWithTraits(FROM_HERE, {BrowserThread::UI}, - base::BindOnce(&ExtensionTracker::Register, self, - base::Owned(components.release()))); + base::PostTask(FROM_HERE, {BrowserThread::UI}, + base::BindOnce(&ExtensionTracker::Register, self, + base::Owned(components.release()))); } void ManagedValueStoreCache::ExtensionTracker::Register( 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 c0ff25c4e0c..0da80d2208f 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 @@ -15,7 +15,7 @@ #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 "content/public/test/test_browser_thread_bundle.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" @@ -126,7 +126,7 @@ class PolicyValueStoreTest : public testing::Test { } base::ScopedTempDir scoped_temp_dir_; - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; std::unique_ptr<PolicyValueStore> store_; MockSettingsObserver observer_; scoped_refptr<SettingsObserverList> observers_; @@ -174,7 +174,7 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { const base::Value value("111"); { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("aaa", nullptr, value.CreateDeepCopy())); + changes.push_back(ValueStoreChange("aaa", base::nullopt, value.Clone())); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, @@ -190,7 +190,7 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { // Notify when new policies are added. { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("bbb", nullptr, value.CreateDeepCopy())); + changes.push_back(ValueStoreChange("bbb", base::nullopt, value.Clone())); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, @@ -206,8 +206,8 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { const base::Value new_value("222"); { ValueStoreChangeList changes; - changes.push_back(ValueStoreChange("bbb", value.CreateDeepCopy(), - new_value.CreateDeepCopy())); + changes.push_back( + ValueStoreChange("bbb", value.Clone(), new_value.Clone())); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, @@ -224,7 +224,7 @@ TEST_F(PolicyValueStoreTest, NotifyOnChanges) { { ValueStoreChangeList changes; changes.push_back( - ValueStoreChange("bbb", new_value.CreateDeepCopy(), nullptr)); + ValueStoreChange("bbb", new_value.Clone(), base::nullopt)); EXPECT_CALL(observer_, OnSettingsChanged(kTestExtensionId, settings_namespace::MANAGED, 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 3d81dd4973e..12638792609 100644 --- a/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc +++ b/chromium/chrome/browser/extensions/api/storage/settings_sync_unittest.cc @@ -22,7 +22,7 @@ #include "components/sync/model/sync_change_processor_wrapper_for_test.h" #include "components/sync/model/sync_error_factory.h" #include "components/sync/model/sync_error_factory_mock.h" -#include "content/public/test/test_browser_thread_bundle.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" @@ -261,7 +261,7 @@ class ExtensionSettingsSyncTest : public testing::Test { } // Needed so that the DCHECKs for running on FILE or UI threads pass. - content::TestBrowserThreadBundle test_browser_thread_bundle_; + content::BrowserTaskEnvironment task_environment_; base::ScopedTempDir temp_dir_; std::unique_ptr<TestingProfile> profile_; 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 7088ea82779..28d68f7dced 100644 --- a/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc +++ b/chromium/chrome/browser/extensions/api/storage/syncable_settings_storage.cc @@ -191,7 +191,7 @@ syncer::SyncError SyncableSettingsStorage::SendLocalSettingsToSync( std::string key = base::DictionaryValue::Iterator(*local_state).key(); std::unique_ptr<base::Value> value; local_state->RemoveWithoutPathExpansion(key, &value); - changes.push_back(ValueStoreChange(key, nullptr, std::move(value))); + changes.push_back(ValueStoreChange(key, base::nullopt, std::move(*value))); } syncer::SyncError error = sync_processor_->SendChanges(changes); @@ -356,7 +356,8 @@ syncer::SyncError SyncableSettingsStorage::OnSyncAdd( result.status().message.c_str()), sync_processor_->type()); } - changes->push_back(ValueStoreChange(key, nullptr, std::move(new_value))); + changes->push_back( + ValueStoreChange(key, base::nullopt, std::move(*new_value))); return syncer::SyncError(); } @@ -377,7 +378,7 @@ syncer::SyncError SyncableSettingsStorage::OnSyncUpdate( sync_processor_->type()); } changes->push_back( - ValueStoreChange(key, std::move(old_value), std::move(new_value))); + ValueStoreChange(key, std::move(*old_value), std::move(*new_value))); return syncer::SyncError(); } @@ -394,7 +395,8 @@ syncer::SyncError SyncableSettingsStorage::OnSyncDelete( result.status().message.c_str()), sync_processor_->type()); } - changes->push_back(ValueStoreChange(key, std::move(old_value), nullptr)); + changes->push_back( + ValueStoreChange(key, std::move(*old_value), base::nullopt)); return syncer::SyncError(); } diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h index 5506ae5e985..01197a0c561 100644 --- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h +++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_api.h @@ -20,12 +20,11 @@ class StreamsPrivateAPI { // Send the onExecuteMimeTypeHandler event to |extension_id|. If the viewer is // being opened in a BrowserPlugin, specify a non-empty |view_id| of the // plugin. |embedded| should be set to whether the document is embedded - // within another document. The |frame_tree_node_id| parameter is used for - // PlzNavigate for the top level plugins case. (PDF, etc). If this parameter - // has a valid value then it overrides the |render_process_id| and - // |render_frame_id| parameters. The |render_process_id| is the id of the - // renderer process. The |render_frame_id| is the routing id of the - // RenderFrameHost. + // within another document. The |frame_tree_node_id| parameter is used for the + // top level plugins case. (PDF, etc). If this parameter has a valid value + // then it overrides the |render_process_id| and |render_frame_id| parameters. + // The |render_process_id| is the id of the renderer process. The + // |render_frame_id| is the routing id of the RenderFrameHost. // // If the network service is not enabled, |stream| is used; otherwise, // |transferrable_loader| and |original_url| are used instead. 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 ccf9916eb27..b2ce3b0cacd 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 @@ -35,7 +35,7 @@ IN_PROC_BROWSER_TEST_F(SystemDisplayChromeOSApiTest, extensions::DisplayInfoProvider::Get()); // Change Tablet Mode then ensure that OnDisplayChangedEvent is triggered - provider->OnTabletModeToggled(true); + provider->OnTabletModeStarted(); extensions::ResultCatcher catcher; EXPECT_TRUE(catcher.GetNextResult()); diff --git a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h index b0bd25e0404..5b3ca7b5bc5 100644 --- a/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h +++ b/chromium/chrome/browser/extensions/api/system_indicator/system_indicator_api.h @@ -9,7 +9,7 @@ namespace extensions { -class SystemIndicatorSetIconFunction : public UIThreadExtensionFunction { +class SystemIndicatorSetIconFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemIndicator.setIcon", SYSTEMINDICATOR_SETICON) @@ -19,7 +19,7 @@ class SystemIndicatorSetIconFunction : public UIThreadExtensionFunction { ~SystemIndicatorSetIconFunction() override {} }; -class SystemIndicatorEnableFunction : public UIThreadExtensionFunction { +class SystemIndicatorEnableFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemIndicator.enable", SYSTEMINDICATOR_ENABLE) @@ -29,7 +29,7 @@ class SystemIndicatorEnableFunction : public UIThreadExtensionFunction { ~SystemIndicatorEnableFunction() override {} }; -class SystemIndicatorDisableFunction : public UIThreadExtensionFunction { +class SystemIndicatorDisableFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemIndicator.disable", SYSTEMINDICATOR_DISABLE) diff --git a/chromium/chrome/browser/extensions/api/system_private/system_private_api.h b/chromium/chrome/browser/extensions/api/system_private/system_private_api.h index 5d6fb2bcc71..9c912f005a3 100644 --- a/chromium/chrome/browser/extensions/api/system_private/system_private_api.h +++ b/chromium/chrome/browser/extensions/api/system_private/system_private_api.h @@ -13,7 +13,7 @@ namespace extensions { class SystemPrivateGetIncognitoModeAvailabilityFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getIncognitoModeAvailability", SYSTEMPRIVATE_GETINCOGNITOMODEAVAILABILITY) @@ -26,7 +26,7 @@ class SystemPrivateGetIncognitoModeAvailabilityFunction }; // API function which returns the status of system update. -class SystemPrivateGetUpdateStatusFunction : public UIThreadExtensionFunction { +class SystemPrivateGetUpdateStatusFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getUpdateStatus", SYSTEMPRIVATE_GETUPDATESTATUS) @@ -39,7 +39,7 @@ class SystemPrivateGetUpdateStatusFunction : public UIThreadExtensionFunction { }; // API function which returns the Google API key. -class SystemPrivateGetApiKeyFunction : public UIThreadExtensionFunction { +class SystemPrivateGetApiKeyFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("systemPrivate.getApiKey", SYSTEMPRIVATE_GETAPIKEY) 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 cbeaa34fdf3..0fdb361b5a2 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 @@ -412,8 +412,8 @@ ExtensionFunction::ResponseAction TabCaptureGetMediaStreamIdFunction::Run() { content::WebContents* target_contents = nullptr; if (params->options && params->options->target_tab_id) { if (!ExtensionTabUtil::GetTabById(*(params->options->target_tab_id), - browser_context(), true, nullptr, nullptr, - &target_contents, nullptr)) { + browser_context(), true, + &target_contents)) { return RespondNow(Error(kInvalidTabIdError)); } } else { @@ -447,8 +447,8 @@ ExtensionFunction::ResponseAction TabCaptureGetMediaStreamIdFunction::Run() { GURL origin; if (params->options && params->options->consumer_tab_id) { if (!ExtensionTabUtil::GetTabById(*(params->options->consumer_tab_id), - browser_context(), true, nullptr, nullptr, - &consumer_contents, nullptr)) { + browser_context(), true, + &consumer_contents)) { return RespondNow(Error(kInvalidTabIdError)); } diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h index 2f3979bf75a..15c0827eec9 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_api.h @@ -22,7 +22,7 @@ extern const char* const kStableChromecastExtensionId; // Extension ids for the chromecast. extern const char* const kChromecastExtensionIds[6]; -class TabCaptureCaptureFunction : public UIThreadExtensionFunction { +class TabCaptureCaptureFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.capture", TABCAPTURE_CAPTURE) @@ -33,7 +33,7 @@ class TabCaptureCaptureFunction : public UIThreadExtensionFunction { ResponseAction Run() final; }; -class TabCaptureGetCapturedTabsFunction : public UIThreadExtensionFunction { +class TabCaptureGetCapturedTabsFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.getCapturedTabs", TABCAPTURE_GETCAPTUREDTABS) @@ -45,7 +45,7 @@ class TabCaptureGetCapturedTabsFunction : public UIThreadExtensionFunction { ResponseAction Run() final; }; -class TabCaptureCaptureOffscreenTabFunction : public UIThreadExtensionFunction { +class TabCaptureCaptureOffscreenTabFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.captureOffscreenTab", TABCAPTURE_CAPTUREOFFSCREENTAB) @@ -62,7 +62,7 @@ class TabCaptureCaptureOffscreenTabFunction : public UIThreadExtensionFunction { ResponseAction Run() final; }; -class TabCaptureGetMediaStreamIdFunction : public UIThreadExtensionFunction { +class TabCaptureGetMediaStreamIdFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabCapture.getMediaStreamId", TABCAPTURE_GETMEDIASTREAMID) 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 2e1bab0f511..414887222cd 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 @@ -161,8 +161,9 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_ApiTests) { ASSERT_TRUE(RunExtensionSubtest("tab_capture", "api_tests.html")) << message_; } -#if defined(OS_MACOSX) && defined(ADDRESS_SANITIZER) -// Flaky on ASAN on Mac. See https://crbug.com/674497. +#if (defined(OS_MACOSX) && defined(ADDRESS_SANITIZER)) || defined(OS_LINUX) || \ + defined(OS_WIN) +// Flaky on ASAN on Mac, and on Linux and Windows. See https://crbug.com/674497. #define MAYBE_MaxOffscreenTabs DISABLED_MaxOffscreenTabs #else #define MAYBE_MaxOffscreenTabs MaxOffscreenTabs @@ -431,10 +432,6 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiTest, MAYBE_TabIndicator) { browser_->tab_strip_model()->AddObserver(this); } - ~IndicatorChangeObserver() override { - browser_->tab_strip_model()->RemoveObserver(this); - } - TabAlertState last_alert_state() const { return last_alert_state_; } void TabChangedAt(content::WebContents* contents, diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc index 7433a5793f0..874af5d556c 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -16,6 +16,7 @@ #include "base/location.h" #include "base/logging.h" #include "base/memory/ref_counted_memory.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" @@ -148,7 +149,7 @@ bool GetBrowserFromWindowID(const ChromeExtensionFunctionDetails& details, return true; } -bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, +bool GetBrowserFromWindowID(ExtensionFunction* function, int window_id, Browser** browser, std::string* error) { @@ -182,10 +183,9 @@ bool GetTabById(int tab_id, // Gets the WebContents for |tab_id| if it is specified. Otherwise get the // WebContents for the active tab in the |function|'s current window. // Returns nullptr and fills |error| if failed. -content::WebContents* GetTabsAPIDefaultWebContents( - UIThreadExtensionFunction* function, - int tab_id, - std::string* error) { +content::WebContents* GetTabsAPIDefaultWebContents(ExtensionFunction* function, + int tab_id, + std::string* error) { content::WebContents* web_contents = nullptr; if (tab_id != -1) { // We assume this call leaves web_contents unchanged if it is unsuccessful. @@ -267,6 +267,18 @@ bool ExtensionHasLockedFullscreenPermission(const Extension* extension) { APIPermission::kLockWindowFullscreenPrivate); } +std::unique_ptr<api::tabs::Tab> CreateTabObjectHelper( + WebContents* contents, + const Extension* extension, + Feature::Context context, + TabStripModel* tab_strip, + int tab_index) { + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, context, contents); + return ExtensionTabUtil::CreateTabObject(contents, scrub_tab_behavior, + extension, tab_strip, tab_index); +} + } // namespace void ZoomModeToZoomSettings(ZoomController::ZoomMode zoom_mode, @@ -312,8 +324,8 @@ ExtensionFunction::ResponseAction WindowsGetFunction::Run() { extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), - populate_tab_behavior); + ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), populate_tab_behavior, source_context_type()); return RespondNow(OneArgument(std::move(windows))); } @@ -335,8 +347,8 @@ ExtensionFunction::ResponseAction WindowsGetCurrentFunction::Run() { extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), - populate_tab_behavior); + ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), populate_tab_behavior, source_context_type()); return RespondNow(OneArgument(std::move(windows))); } @@ -369,8 +381,8 @@ ExtensionFunction::ResponseAction WindowsGetLastFocusedFunction::Run() { extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), - populate_tab_behavior); + ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), populate_tab_behavior, source_context_type()); return RespondNow(OneArgument(std::move(windows))); } @@ -391,7 +403,8 @@ ExtensionFunction::ResponseAction WindowsGetAllFunction::Run() { continue; } window_list->Append(ExtensionTabUtil::CreateWindowValueForExtension( - *controller->GetBrowser(), extension(), populate_tab_behavior)); + *controller->GetBrowser(), extension(), populate_tab_behavior, + source_context_type())); } return RespondNow(OneArgument(std::move(window_list))); @@ -508,7 +521,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { if (!IsValidStateForWindowsCreateFunction(create_data)) return RespondNow(Error(tabs_constants::kInvalidWindowStateError)); - Browser::Type window_type = Browser::TYPE_TABBED; + Browser::Type window_type = Browser::TYPE_NORMAL; gfx::Rect window_bounds; bool focused = true; @@ -532,13 +545,10 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { } // Initialize default window bounds according to window type. - if (window_type == Browser::TYPE_TABBED || - window_type == Browser::TYPE_POPUP) { - ui::WindowShowState ignored_show_state = ui::SHOW_STATE_DEFAULT; - WindowSizer::GetBrowserWindowBoundsAndShowState( - std::string(), gfx::Rect(), nullptr, &window_bounds, - &ignored_show_state); - } + ui::WindowShowState ignored_show_state = ui::SHOW_STATE_DEFAULT; + WindowSizer::GetBrowserWindowBoundsAndShowState(std::string(), gfx::Rect(), + nullptr, &window_bounds, + &ignored_show_state); // Any part of the bounds can optionally be set by the caller. if (create_data->left) @@ -592,9 +602,19 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { // https://crbug.com/713888. bool set_self_as_opener = create_data->set_self_as_opener && // present? *create_data->set_self_as_opener; // set to true? - navigate_params.opener = set_self_as_opener ? render_frame_host() : nullptr; - navigate_params.source_site_instance = - render_frame_host()->GetSiteInstance(); + if (set_self_as_opener) { + if (is_from_service_worker()) { + // TODO(crbug.com/984350): Add test for this. + return RespondNow( + Error("Cannot specify setSelfAsOpener Service Worker extension.")); + } + // TODO(crbug.com/984350): Add tests for checking opener SiteInstance + // behavior from a SW based extension's extension frame (e.g. from popup). + // See ExtensionApiTest.WindowsCreate* tests for details. + navigate_params.opener = render_frame_host(); + navigate_params.source_site_instance = + render_frame_host()->GetSiteInstance(); + } Navigate(&navigate_params); } @@ -602,8 +622,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { WebContents* contents = NULL; // Move the tab into the created window only if it's an empty popup or it's // a tabbed window. - if ((window_type == Browser::TYPE_POPUP && urls.empty()) || - window_type == Browser::TYPE_TABBED) { + if (window_type == Browser::TYPE_NORMAL || urls.empty()) { if (source_tab_strip) { std::unique_ptr<content::WebContents> detached_tab = source_tab_strip->DetachWebContentsAt(tab_index); @@ -615,7 +634,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { } // Create a new tab if the created window is still empty. Don't create a new // tab when it is intended to create an empty popup. - if (!contents && urls.empty() && window_type != Browser::TYPE_POPUP) { + if (!contents && urls.empty() && window_type == Browser::TYPE_NORMAL) { chrome::NewTab(new_window); } chrome::SelectNumberedTab(new_window, 0, {TabStripModel::GestureType::kNone}); @@ -642,7 +661,8 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { result = std::make_unique<base::Value>(); } else { result = ExtensionTabUtil::CreateWindowValueForExtension( - *new_window, extension(), ExtensionTabUtil::kPopulateTabs); + *new_window, extension(), ExtensionTabUtil::kPopulateTabs, + source_context_type()); } return RespondNow(OneArgument(std::move(result))); @@ -772,7 +792,8 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { browser->window()->FlashFrame(*params->update_info.draw_attention); return RespondNow(OneArgument(ExtensionTabUtil::CreateWindowValueForExtension( - *browser, extension(), ExtensionTabUtil::kDontPopulateTabs))); + *browser, extension(), ExtensionTabUtil::kDontPopulateTabs, + source_context_type()))); } ExtensionFunction::ResponseAction WindowsRemoveFunction::Run() { @@ -826,10 +847,9 @@ ExtensionFunction::ResponseAction TabsGetSelectedFunction::Run() { WebContents* contents = tab_strip->GetActiveWebContents(); if (!contents) return RespondNow(Error(tabs_constants::kNoSelectedTabError)); - return RespondNow(ArgumentList( - tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension(), tab_strip, - tab_strip->active_index())))); + return RespondNow(ArgumentList(tabs::Get::Results::Create( + *CreateTabObjectHelper(contents, extension(), source_context_type(), + tab_strip, tab_strip->active_index())))); } ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { @@ -846,8 +866,8 @@ ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { if (!GetBrowserFromWindowID(this, window_id, &browser, &error)) return RespondNow(Error(error)); - return RespondNow( - OneArgument(ExtensionTabUtil::CreateTabList(browser, extension()))); + return RespondNow(OneArgument(ExtensionTabUtil::CreateTabList( + browser, extension(), source_context_type()))); } ExtensionFunction::ResponseAction TabsQueryFunction::Run() { @@ -1016,9 +1036,8 @@ ExtensionFunction::ResponseAction TabsQueryFunction::Run() { if (loading_status_set && loading != web_contents->IsLoading()) continue; - result->Append(ExtensionTabUtil::CreateTabObject( - web_contents, ExtensionTabUtil::kScrubTab, extension(), - tab_strip, i) + result->Append(CreateTabObjectHelper(web_contents, extension(), + source_context_type(), tab_strip, i) ->ToValue()); } } @@ -1083,10 +1102,9 @@ ExtensionFunction::ResponseAction TabsDuplicateFunction::Run() { return RespondNow(Error(kUnknownErrorDoNotUse)); } - return RespondNow(ArgumentList( - tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - new_contents, ExtensionTabUtil::kScrubTab, extension(), new_tab_strip, - new_tab_index)))); + return RespondNow(ArgumentList(tabs::Get::Results::Create( + *CreateTabObjectHelper(new_contents, extension(), source_context_type(), + new_tab_strip, new_tab_index)))); } ExtensionFunction::ResponseAction TabsGetFunction::Run() { @@ -1104,8 +1122,8 @@ ExtensionFunction::ResponseAction TabsGetFunction::Run() { } return RespondNow(ArgumentList(tabs::Get::Results::Create( - *ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, - extension(), tab_strip, tab_index)))); + *CreateTabObjectHelper(contents, extension(), source_context_type(), + tab_strip, tab_index)))); } ExtensionFunction::ResponseAction TabsGetCurrentFunction::Run() { @@ -1116,8 +1134,8 @@ ExtensionFunction::ResponseAction TabsGetCurrentFunction::Run() { WebContents* caller_contents = GetSenderWebContents(); std::unique_ptr<base::ListValue> results; if (caller_contents && ExtensionTabUtil::GetTabId(caller_contents) >= 0) { - results = tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - caller_contents, ExtensionTabUtil::kScrubTab, extension())); + results = tabs::Get::Results::Create(*CreateTabObjectHelper( + caller_contents, extension(), source_context_type(), nullptr, -1)); } return RespondNow(results ? ArgumentList(std::move(results)) : NoArguments()); } @@ -1165,7 +1183,8 @@ ExtensionFunction::ResponseAction TabsHighlightFunction::Run() { selection.set_active(active_index); browser->tab_strip_model()->SetSelectionFromModel(std::move(selection)); return RespondNow(OneArgument(ExtensionTabUtil::CreateWindowValueForExtension( - *browser, extension(), ExtensionTabUtil::kPopulateTabs))); + *browser, extension(), ExtensionTabUtil::kPopulateTabs, + source_context_type()))); } bool TabsHighlightFunction::HighlightTab(TabStripModel* tabstrip, @@ -1359,9 +1378,8 @@ ExtensionFunction::ResponseValue TabsUpdateFunction::GetResult() { if (!has_callback()) return NoArguments(); - return ArgumentList( - tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - web_contents_, ExtensionTabUtil::kScrubTab, extension()))); + return ArgumentList(tabs::Get::Results::Create(*CreateTabObjectHelper( + web_contents_, extension(), source_context_type(), nullptr, -1))); } void TabsUpdateFunction::OnExecuteCodeFinished( @@ -1458,7 +1476,9 @@ bool TabsMoveFunction::MoveTab(int tab_id, return false; } - if (!target_browser->is_type_tabbed()) { + // TODO(crbug.com/990158): Rather than calling is_type_normal(), should + // this call SupportsWindowFeature(Browser::FEATURE_TABSTRIP)? + if (!target_browser->is_type_normal()) { *error = tabs_constants::kCanOnlyMoveTabsWithinNormalWindowsError; return false; } @@ -1492,9 +1512,9 @@ bool TabsMoveFunction::MoveTab(int tab_id, *new_index, std::move(web_contents), TabStripModel::ADD_NONE); if (has_callback()) { - tab_values->Append(ExtensionTabUtil::CreateTabObject( - web_contents_raw, ExtensionTabUtil::kScrubTab, - extension(), target_tab_strip, *new_index) + tab_values->Append(CreateTabObjectHelper(web_contents_raw, extension(), + source_context_type(), + target_tab_strip, *new_index) ->ToValue()); } @@ -1514,9 +1534,9 @@ bool TabsMoveFunction::MoveTab(int tab_id, source_tab_strip->MoveWebContentsAt(tab_index, *new_index, false); if (has_callback()) { - tab_values->Append(ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension(), - source_tab_strip, *new_index) + tab_values->Append(CreateTabObjectHelper(contents, extension(), + source_context_type(), + source_tab_strip, *new_index) ->ToValue()); } @@ -1790,7 +1810,7 @@ ExtensionFunction::ResponseAction TabsDetectLanguageFunction::Run() { // Observe the WebContents' lifetime and navigations. Observe(contents); // Wait until the language is determined. - chrome_translate_client->translate_driver().AddObserver(this); + chrome_translate_client->translate_driver()->AddObserver(this); is_observing_ = true; return RespondLater(); @@ -1820,7 +1840,7 @@ void TabsDetectLanguageFunction::RespondWithLanguage( if (is_observing_) { ChromeTranslateClient::FromWebContents(web_contents()) ->translate_driver() - .RemoveObserver(this); + ->RemoveObserver(this); Observe(nullptr); } @@ -1983,8 +2003,7 @@ ExtensionFunction::ResponseAction TabsSetZoomFunction::Run() { ? content::ZoomFactorToZoomLevel(params->zoom_factor) : zoom_controller->GetDefaultZoomLevel(); - scoped_refptr<ExtensionZoomRequestClient> client( - new ExtensionZoomRequestClient(extension())); + auto client = base::MakeRefCounted<ExtensionZoomRequestClient>(extension()); if (!zoom_controller->SetZoomLevelByClient(zoom_level, client)) { // Tried to zoom a tab in disabled mode. return RespondNow(Error(tabs_constants::kCannotZoomDisabledTabError)); @@ -2111,9 +2130,9 @@ ExtensionFunction::ResponseAction TabsDiscardFunction::Run() { // Create the Tab object and return it in case of success. if (contents) { - return RespondNow(ArgumentList( - tabs::Discard::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, ExtensionTabUtil::kScrubTab, extension())))); + return RespondNow( + ArgumentList(tabs::Discard::Results::Create(*CreateTabObjectHelper( + contents, extension(), source_context_type(), nullptr, -1)))); } // Return appropriate error message otherwise. diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h index 37c2da5cf71..ed3aa5336d5 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h @@ -44,27 +44,27 @@ void ZoomModeToZoomSettings(zoom::ZoomController::ZoomMode zoom_mode, api::tabs::ZoomSettings* zoom_settings); // Windows -class WindowsGetFunction : public UIThreadExtensionFunction { +class WindowsGetFunction : public ExtensionFunction { ~WindowsGetFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.get", WINDOWS_GET) }; -class WindowsGetCurrentFunction : public UIThreadExtensionFunction { +class WindowsGetCurrentFunction : public ExtensionFunction { ~WindowsGetCurrentFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getCurrent", WINDOWS_GETCURRENT) }; -class WindowsGetLastFocusedFunction : public UIThreadExtensionFunction { +class WindowsGetLastFocusedFunction : public ExtensionFunction { ~WindowsGetLastFocusedFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getLastFocused", WINDOWS_GETLASTFOCUSED) }; -class WindowsGetAllFunction : public UIThreadExtensionFunction { +class WindowsGetAllFunction : public ExtensionFunction { ~WindowsGetAllFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.getAll", WINDOWS_GETALL) }; -class WindowsCreateFunction : public UIThreadExtensionFunction { +class WindowsCreateFunction : public ExtensionFunction { ~WindowsCreateFunction() override {} ResponseAction Run() override; // Returns whether the window should be created in incognito mode. @@ -80,54 +80,54 @@ class WindowsCreateFunction : public UIThreadExtensionFunction { std::string* error); DECLARE_EXTENSION_FUNCTION("windows.create", WINDOWS_CREATE) }; -class WindowsUpdateFunction : public UIThreadExtensionFunction { +class WindowsUpdateFunction : public ExtensionFunction { ~WindowsUpdateFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.update", WINDOWS_UPDATE) }; -class WindowsRemoveFunction : public UIThreadExtensionFunction { +class WindowsRemoveFunction : public ExtensionFunction { ~WindowsRemoveFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("windows.remove", WINDOWS_REMOVE) }; // Tabs -class TabsGetFunction : public UIThreadExtensionFunction { +class TabsGetFunction : public ExtensionFunction { ~TabsGetFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.get", TABS_GET) }; -class TabsGetCurrentFunction : public UIThreadExtensionFunction { +class TabsGetCurrentFunction : public ExtensionFunction { ~TabsGetCurrentFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getCurrent", TABS_GETCURRENT) }; -class TabsGetSelectedFunction : public UIThreadExtensionFunction { +class TabsGetSelectedFunction : public ExtensionFunction { ~TabsGetSelectedFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getSelected", TABS_GETSELECTED) }; -class TabsGetAllInWindowFunction : public UIThreadExtensionFunction { +class TabsGetAllInWindowFunction : public ExtensionFunction { ~TabsGetAllInWindowFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.getAllInWindow", TABS_GETALLINWINDOW) }; -class TabsQueryFunction : public UIThreadExtensionFunction { +class TabsQueryFunction : public ExtensionFunction { ~TabsQueryFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.query", TABS_QUERY) }; -class TabsCreateFunction : public UIThreadExtensionFunction { +class TabsCreateFunction : public ExtensionFunction { ~TabsCreateFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.create", TABS_CREATE) }; -class TabsDuplicateFunction : public UIThreadExtensionFunction { +class TabsDuplicateFunction : public ExtensionFunction { ~TabsDuplicateFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.duplicate", TABS_DUPLICATE) }; -class TabsHighlightFunction : public UIThreadExtensionFunction { +class TabsHighlightFunction : public ExtensionFunction { ~TabsHighlightFunction() override {} ResponseAction Run() override; bool HighlightTab(TabStripModel* tabstrip, @@ -137,7 +137,7 @@ class TabsHighlightFunction : public UIThreadExtensionFunction { std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.highlight", TABS_HIGHLIGHT) }; -class TabsUpdateFunction : public UIThreadExtensionFunction { +class TabsUpdateFunction : public ExtensionFunction { public: TabsUpdateFunction(); @@ -158,7 +158,7 @@ class TabsUpdateFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.update", TABS_UPDATE) }; -class TabsMoveFunction : public UIThreadExtensionFunction { +class TabsMoveFunction : public ExtensionFunction { ~TabsMoveFunction() override {} ResponseAction Run() override; bool MoveTab(int tab_id, @@ -169,19 +169,19 @@ class TabsMoveFunction : public UIThreadExtensionFunction { std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.move", TABS_MOVE) }; -class TabsReloadFunction : public UIThreadExtensionFunction { +class TabsReloadFunction : public ExtensionFunction { ~TabsReloadFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("tabs.reload", TABS_RELOAD) }; -class TabsRemoveFunction : public UIThreadExtensionFunction { +class TabsRemoveFunction : public ExtensionFunction { ~TabsRemoveFunction() override {} ResponseAction Run() override; bool RemoveTab(int tab_id, std::string* error); DECLARE_EXTENSION_FUNCTION("tabs.remove", TABS_REMOVE) }; class TabsDetectLanguageFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public content::WebContentsObserver, public translate::ContentTranslateDriver::Observer { private: @@ -209,7 +209,7 @@ class TabsDetectLanguageFunction class TabsCaptureVisibleTabFunction : public extensions::WebContentsCaptureClient, - public UIThreadExtensionFunction { + public ExtensionFunction { public: TabsCaptureVisibleTabFunction(); static void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry); @@ -280,7 +280,7 @@ class TabsInsertCSSFunction : public ExecuteCodeInTabFunction { DECLARE_EXTENSION_FUNCTION("tabs.insertCSS", TABS_INSERTCSS) }; -class TabsSetZoomFunction : public UIThreadExtensionFunction { +class TabsSetZoomFunction : public ExtensionFunction { private: ~TabsSetZoomFunction() override {} @@ -289,7 +289,7 @@ class TabsSetZoomFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.setZoom", TABS_SETZOOM) }; -class TabsGetZoomFunction : public UIThreadExtensionFunction { +class TabsGetZoomFunction : public ExtensionFunction { private: ~TabsGetZoomFunction() override {} @@ -298,7 +298,7 @@ class TabsGetZoomFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.getZoom", TABS_GETZOOM) }; -class TabsSetZoomSettingsFunction : public UIThreadExtensionFunction { +class TabsSetZoomSettingsFunction : public ExtensionFunction { private: ~TabsSetZoomSettingsFunction() override {} @@ -307,7 +307,7 @@ class TabsSetZoomSettingsFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.setZoomSettings", TABS_SETZOOMSETTINGS) }; -class TabsGetZoomSettingsFunction : public UIThreadExtensionFunction { +class TabsGetZoomSettingsFunction : public ExtensionFunction { private: ~TabsGetZoomSettingsFunction() override {} @@ -316,7 +316,7 @@ class TabsGetZoomSettingsFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("tabs.getZoomSettings", TABS_GETZOOMSETTINGS) }; -class TabsDiscardFunction : public UIThreadExtensionFunction { +class TabsDiscardFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabs.discard", TABS_DISCARD) @@ -331,7 +331,7 @@ class TabsDiscardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(TabsDiscardFunction); }; -class TabsGoForwardFunction : public UIThreadExtensionFunction { +class TabsGoForwardFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabs.goForward", TABS_GOFORWARD) @@ -346,7 +346,7 @@ class TabsGoForwardFunction : public UIThreadExtensionFunction { DISALLOW_COPY_AND_ASSIGN(TabsGoForwardFunction); }; -class TabsGoBackFunction : public UIThreadExtensionFunction { +class TabsGoBackFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("tabs.goBack", TABS_GOBACK) 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 60915b4d639..8b1853957cd 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc @@ -106,7 +106,7 @@ void TabsApiUnitTest::SetUp() { browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); - params.type = Browser::TYPE_TABBED; + params.type = Browser::TYPE_NORMAL; params.window = browser_window_.get(); browser_.reset(new Browser(params)); scoped_screen_override_ = 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 ead6f0a7144..f86ebb9b063 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc @@ -27,6 +27,7 @@ #include "content/public/browser/favicon_status.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" +#include "extensions/common/features/feature.h" using base::DictionaryValue; using base::ListValue; @@ -41,12 +42,16 @@ namespace { bool WillDispatchTabUpdatedEvent( WebContents* contents, const std::set<std::string> changed_property_names, - content::BrowserContext* context, + content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, target_context, + contents); std::unique_ptr<api::tabs::Tab> tab_object = - ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, + ExtensionTabUtil::CreateTabObject(contents, scrub_tab_behavior, extension); std::unique_ptr<base::DictionaryValue> tab_value = tab_object->ToValue(); @@ -66,14 +71,17 @@ bool WillDispatchTabUpdatedEvent( bool WillDispatchTabCreatedEvent(WebContents* contents, bool active, - content::BrowserContext* context, + content::BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { event->event_args->Clear(); + ExtensionTabUtil::ScrubTabBehavior scrub_tab_behavior = + ExtensionTabUtil::GetScrubTabBehavior(extension, target_context, + contents); std::unique_ptr<base::DictionaryValue> tab_value = - ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, - extension) + ExtensionTabUtil::CreateTabObject(contents, scrub_tab_behavior, extension) ->ToValue(); tab_value->SetBoolean(tabs_constants::kSelectedKey, active); tab_value->SetBoolean(tabs_constants::kActiveKey, active); 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 9d43155a027..77050a952f3 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_interactive_test.cc @@ -21,6 +21,7 @@ namespace extensions { namespace keys = tabs_constants; namespace utils = extension_function_test_utils; +using ContextType = ExtensionBrowserTest::ContextType; using ExtensionTabsTest = InProcessBrowserTest; IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetLastFocusedWindow) { @@ -117,8 +118,35 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, QueryLastFocusedWindowTabs) { } } -IN_PROC_BROWSER_TEST_F(ExtensionApiTest, TabCurrentWindow) { - ASSERT_TRUE(RunExtensionTest("tabs/current_window")) << message_; +class NonPersistentExtensionTabsTest + : public ExtensionApiTest, + public testing::WithParamInterface<ContextType> { + protected: + const Extension* LoadNonPersistentExtension(const char* relative_path) { + return LoadExtensionWithFlags(test_data_dir_.AppendASCII(relative_path), + GetParam() == ContextType::kEventPage + ? kFlagNone + : kFlagRunAsServiceWorkerBasedExtension); + } +}; + +// Tests chrome.windows.create. +// 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, TabCurrentWindow) { + ASSERT_TRUE(RunExtensionTestWithFlags( + "tabs/current_window", GetParam() == ContextType::kServiceWorker + ? kFlagRunAsServiceWorkerBasedExtension + : kFlagNone)) + << message_; } +INSTANTIATE_TEST_SUITE_P(EventPage, + NonPersistentExtensionTabsTest, + ::testing::Values(ContextType::kEventPage)); + +INSTANTIATE_TEST_SUITE_P(ServiceWorker, + NonPersistentExtensionTabsTest, + ::testing::Values(ContextType::kServiceWorker)); + } // 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 748dc56a796..f5fb14246df 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc @@ -795,7 +795,7 @@ class ExtensionWindowLastFocusedTest : public ExtensionTabsTest { int GetTabId(const base::DictionaryValue* value) const; - base::Value* RunFunction(UIThreadExtensionFunction* function, + base::Value* RunFunction(ExtensionFunction* function, const std::string& params); const Extension* extension() { return extension_.get(); } @@ -880,7 +880,7 @@ int ExtensionWindowLastFocusedTest::GetTabId( } base::Value* ExtensionWindowLastFocusedTest::RunFunction( - UIThreadExtensionFunction* function, + ExtensionFunction* function, const std::string& params) { function->set_extension(extension_.get()); return utils::RunFunctionAndReturnSingleResult(function, params, browser()); @@ -2238,4 +2238,87 @@ IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowsCreate_NoOpener) { // (we hope this can be limited to background pages / contents). } +// Tests the origin of tabs created through chrome.windows.create(). +IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WindowsCreate_OpenerAndOrigin) { + const extensions::Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("../simple_with_file")); + ASSERT_TRUE(extension); + + // Navigate a tab to an extension page. + GURL extension_url = extension->GetResourceURL("file.html"); + ui_test_utils::NavigateToURL(browser(), extension_url); + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + + const std::string extension_origin_str = + url::Origin::Create(extension->url()).Serialize(); + constexpr char kDataURL[] = "data:text/html,<html>test</html>"; + std::string extension_url_str = extension_url.spec(); + struct TestCase { + // The url to use in chrome.windows.create(). + std::string url; + // If set, its value will be used to specify |setSelfAsOpener|. + base::Optional<bool> set_self_as_opener; + // The origin we expect the new tab to be in, opaque origins will be "null". + std::string expected_origin_str; + } test_cases[] = { + // about:blank URLs. + // With opener relationship, about:blank urls will get the extension's + // origin, without opener relationship, they will get opaque/"null" + // origin. + {url::kAboutBlankURL, true, extension_origin_str}, + {url::kAboutBlankURL, false, "null"}, + {url::kAboutBlankURL, base::nullopt, "null"}, + + // data:... URLs. + // With opener relationship or not, "data:..." URLs always gets unique + // origin, so origin will always be "null" in these cases. + {kDataURL, true, "null"}, + {kDataURL, false, "null"}, + {kDataURL, base::nullopt, "null"}, + + // chrome-extension:// URLs. + // These always get extension origin. + {extension_url_str, true, extension_origin_str}, + {extension_url_str, false, extension_origin_str}, + {extension_url_str, base::nullopt, extension_origin_str}, + }; + + auto run_test_case = [&web_contents](const TestCase& test_case) { + std::string maybe_specify_set_self_as_opener = ""; + if (test_case.set_self_as_opener) { + maybe_specify_set_self_as_opener = + base::StringPrintf(", setSelfAsOpener: %s", + *test_case.set_self_as_opener ? "true" : "false"); + } + std::string script = base::StringPrintf( + R"( chrome.windows.create({url: '%s'%s}); )", test_case.url.c_str(), + maybe_specify_set_self_as_opener.c_str()); + + content::WebContents* new_contents = nullptr; + { + content::WebContentsAddedObserver observer; + ASSERT_TRUE(content::ExecuteScript(web_contents, script)); + new_contents = observer.GetWebContents(); + } + ASSERT_TRUE(new_contents); + ASSERT_TRUE(content::WaitForLoadStop(new_contents)); + + std::string actual_origin_str; + EXPECT_TRUE(ExecuteScriptAndExtractString( + new_contents, "window.domAutomationController.send(origin);", + &actual_origin_str)); + EXPECT_EQ(test_case.expected_origin_str, actual_origin_str); + const bool is_opaque_origin = + new_contents->GetMainFrame()->GetLastCommittedOrigin().opaque(); + EXPECT_EQ(test_case.expected_origin_str == "null", is_opaque_origin); + }; + for (size_t i = 0; i < base::size(test_cases); ++i) { + const auto& test_case = test_cases[i]; + SCOPED_TRACE( + base::StringPrintf("#%" PRIuS " %s", i, test_case.url.c_str())); + run_test_case(test_case); + } +} + } // namespace extensions 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 0a076f31c73..6a0c9a2833f 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_util_chromeos.cc @@ -19,7 +19,7 @@ #include "content/public/browser/devtools_agent_host.h" #include "ui/aura/window.h" #include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/clipboard_types.h" +#include "ui/base/clipboard/clipboard_buffer.h" namespace extensions { namespace tabs_util { @@ -27,14 +27,6 @@ namespace tabs_util { void SetLockedFullscreenState(Browser* browser, bool locked) { UMA_HISTOGRAM_BOOLEAN("Extensions.LockedFullscreenStateRequest", locked); - // Disable ChromeVox before entering locked fullscreen. Quickfix for - // crbug.com/957950. - auto* const accessibility_manager = chromeos::AccessibilityManager::Get(); - if (locked && accessibility_manager && - accessibility_manager->IsSpokenFeedbackEnabled()) { - accessibility_manager->EnableSpokenFeedback(false); - } - 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). @@ -50,7 +42,7 @@ void SetLockedFullscreenState(Browser* browser, bool locked) { // Reset the clipboard and kill dev tools when entering or exiting locked // fullscreen (security concerns). - ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardType::kCopyPaste); + ui::Clipboard::GetForCurrentThread()->Clear(ui::ClipboardBuffer::kCopyPaste); content::DevToolsAgentHost::DetachAllClients(); // Disable ARC while in the locked fullscreen mode. 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 b27e4bca86e..c890c88293c 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc @@ -60,7 +60,8 @@ bool ControllerVisibleToListener(WindowController* window_controller, } bool WillDispatchWindowEvent(WindowController* window_controller, - BrowserContext* context, + BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { @@ -88,7 +89,8 @@ bool WillDispatchWindowEvent(WindowController* window_controller, bool WillDispatchWindowFocusedEvent( WindowController* window_controller, - BrowserContext* context, + BrowserContext* browser_context, + Feature::Context target_context, const Extension* extension, Event* event, const base::DictionaryValue* listener_filter) { @@ -123,9 +125,9 @@ bool WillDispatchWindowFocusedEvent( // dispatch WINDOW_ID_NONE to extensions whose profile lost focus that // can't see the new focused window across the incognito boundary. // See crbug.com/46610. - bool cant_cross_incognito = new_active_context && - new_active_context != context && - !util::CanCrossIncognito(extension, context); + bool cant_cross_incognito = + new_active_context && new_active_context != browser_context && + !util::CanCrossIncognito(extension, browser_context); // If the window is not visible by the listener, we also need to // clear out the window id from the event. bool visible_to_listener = ControllerVisibleToListener( @@ -214,9 +216,13 @@ void WindowsEventRouter::OnWindowControllerAdded( return; std::unique_ptr<base::ListValue> args(new base::ListValue()); + // Since we don't populate tab info here, the context type doesn't matter. + constexpr ExtensionTabUtil::PopulateTabBehavior populate_behavior = + ExtensionTabUtil::kDontPopulateTabs; + constexpr Feature::Context context_type = Feature::UNSPECIFIED_CONTEXT; args->Append(ExtensionTabUtil::CreateWindowValueForExtension( - *window_controller->GetBrowser(), nullptr, - ExtensionTabUtil::kDontPopulateTabs)); + *window_controller->GetBrowser(), nullptr, populate_behavior, + context_type)); DispatchEvent(events::WINDOWS_ON_CREATED, windows::OnCreated::kEventName, window_controller, std::move(args)); } diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc index 684183d770a..ae70d408258 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc @@ -23,7 +23,7 @@ namespace windows_util { -bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, +bool GetBrowserFromWindowID(ExtensionFunction* function, int window_id, extensions::WindowController::TypeFilter filter, Browser** browser, @@ -68,7 +68,7 @@ bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, return true; } -bool CanOperateOnWindow(const UIThreadExtensionFunction* function, +bool CanOperateOnWindow(const ExtensionFunction* function, const extensions::WindowController* controller, extensions::WindowController::TypeFilter filter) { if (filter && !controller->MatchesFilter(filter)) diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.h b/chromium/chrome/browser/extensions/api/tabs/windows_util.h index f080d068c72..551e1bbbb89 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.h +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.h @@ -9,7 +9,7 @@ #include "chrome/browser/extensions/window_controller_list.h" -class UIThreadExtensionFunction; +class ExtensionFunction; namespace extensions { class WindowController; @@ -19,7 +19,7 @@ namespace windows_util { // Populates |browser| for given |window_id|. If the window is not found, // returns false and sets |error|. -bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, +bool GetBrowserFromWindowID(ExtensionFunction* function, int window_id, extensions::WindowController::TypeFilter filter, Browser** browser, @@ -31,7 +31,7 @@ bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, // kind of window (including app and devtools), otherwise it will // return true only for normal browser windows as well as windows // created by the extension. -bool CanOperateOnWindow(const UIThreadExtensionFunction* function, +bool CanOperateOnWindow(const ExtensionFunction* function, const extensions::WindowController* controller, extensions::WindowController::TypeFilter filter); 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 1dc03aa89af..a84c77ebbe5 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc @@ -5,6 +5,7 @@ #include "chrome/browser/extensions/api/terminal/terminal_private_api.h" #include <memory> +#include <string> #include <utility> #include <vector> @@ -14,9 +15,13 @@ #include "base/system/sys_info.h" #include "base/task/post_task.h" #include "base/values.h" +#include "chrome/browser/chromeos/crostini/crostini_manager.h" +#include "chrome/browser/chromeos/crostini/crostini_simple_types.h" +#include "chrome/browser/chromeos/crostini/crostini_util.h" #include "chrome/browser/extensions/api/terminal/terminal_extension_helper.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_tab_util.h" +#include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/api/terminal_private.h" #include "chromeos/process_proxy/process_proxy_registry.h" @@ -49,33 +54,29 @@ const char kStubbedCroshCommand[] = "cat"; const char kVmShellName[] = "vmshell"; const char kVmShellCommand[] = "/usr/bin/vsh"; -std::string GetCroshPath() { - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kCroshCommand)) - return command_line->GetSwitchValueASCII(switches::kCroshCommand); - - if (base::SysInfo::IsRunningOnChromeOS()) - return std::string(kCroshCommand); - - return std::string(kStubbedCroshCommand); -} - -// Get the program to run based on the openTerminalProcess JS request. -std::string GetProcessCommandForName(const std::string& name) { - if (name == kCroshName) - return GetCroshPath(); - else if (name == kVmShellName) - return kVmShellCommand; - else - return std::string(); +const char kSwitchOwnerId[] = "owner_id"; +const char kSwitchVmName[] = "vm_name"; +const char kSwitchTargetContainer[] = "target_container"; + +// Returns the value of the specified |switch_name| if present. If not present, +// sets that switch to and returns |default_value|. +std::string GetSwitch(base::CommandLine* command_line, + const std::string& switch_name, + const std::string& default_value) { + if (command_line->HasSwitch(switch_name)) { + return command_line->GetSwitchValueASCII(switch_name); + } + command_line->AppendSwitchASCII(switch_name, default_value); + return default_value; } -// Whether the program accepts arbitrary command line arguments. -bool CommandSupportsArguments(const std::string& name) { - if (name == kVmShellName) - return true; - - return false; +void OnCrostiniRestarted(base::OnceClosure callback, + crostini::CrostiniResult result) { + if (result != crostini::CrostiniResult::SUCCESS) { + LOG(ERROR) << "Error restarting crostini for terminal: " + << static_cast<int>(result); + } + std::move(callback).Run(); } void NotifyProcessOutput(content::BrowserContext* browser_context, @@ -84,10 +85,9 @@ void NotifyProcessOutput(content::BrowserContext* browser_context, const std::string& output_type, const std::string& output) { if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { - base::PostTaskWithTraits( - FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(&NotifyProcessOutput, browser_context, tab_id, - terminal_id, output_type, output)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(&NotifyProcessOutput, browser_context, tab_id, + terminal_id, output_type, output)); return; } @@ -135,27 +135,62 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { OpenTerminalProcess::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - const std::string command = GetProcessCommandForName(params->process_name); - if (command.empty()) - return RespondNow(Error("Invalid process name.")); - - const std::string user_id_hash = - ExtensionsBrowserClient::Get()->GetUserIdHashFromContext( - browser_context()); - - std::vector<std::string> arguments; - arguments.push_back(command); - if (params->args) { - for (const std::string& arg : *params->args) - arguments.push_back(arg); + // Passing --crosh-command overrides any JS process name. + base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); + if (command_line->HasSwitch(switches::kCroshCommand)) { + OpenProcess({command_line->GetSwitchValueASCII(switches::kCroshCommand)}); + + } else if (params->process_name == kCroshName) { + // command=crosh: use '/usr/bin/crosh' on a device, 'cat' otherwise. + if (base::SysInfo::IsRunningOnChromeOS()) { + OpenProcess({kCroshCommand}); + } else { + OpenProcess({kStubbedCroshCommand}); + } + + } else if (params->process_name == kVmShellName) { + // command=vmshell: ensure --owner_id, --vm_name, --target_container are set + // and the specified vm/container is running. + std::vector<std::string> args = {kVmShellCommand}; + if (params->args) + args.insert(args.end(), params->args->begin(), params->args->end()); + base::CommandLine vmshell_cmd(args); + std::string owner_id = + GetSwitch(&vmshell_cmd, kSwitchOwnerId, UserIdHash()); + std::string vm_name = GetSwitch(&vmshell_cmd, kSwitchVmName, + crostini::kCrostiniDefaultVmName); + std::string container_name = + GetSwitch(&vmshell_cmd, kSwitchTargetContainer, + crostini::kCrostiniDefaultContainerName); + + auto open_process = + base::BindOnce(&TerminalPrivateOpenTerminalProcessFunction::OpenProcess, + this, vmshell_cmd.argv()); + crostini::CrostiniManager::GetForProfile( + Profile::FromBrowserContext(browser_context())) + ->RestartCrostini( + vm_name, container_name, + base::BindOnce(&OnCrostiniRestarted, std::move(open_process))); + + } else { + // command=[unrecognized]. + return RespondNow(Error("Invalid process name: " + params->process_name)); } + return RespondLater(); +} - if (arguments.size() > 1 && !CommandSupportsArguments(params->process_name)) - return RespondNow(Error("Specified command does not support arguments.")); +std::string TerminalPrivateOpenTerminalProcessFunction::UserIdHash() { + return extensions::ExtensionsBrowserClient::Get()->GetUserIdHashFromContext( + browser_context()); +} + +void TerminalPrivateOpenTerminalProcessFunction::OpenProcess( + const std::vector<std::string> arguments) { + DCHECK(!arguments.empty()); content::WebContents* caller_contents = GetSenderWebContents(); if (!caller_contents) - return RespondNow(Error("No web contents.")); + return Respond(Error("No web contents.")); // Passed to terminalPrivate.ackOutput, which is called from the API's custom // bindings after terminalPrivate.onProcessOutput is dispatched. It is used to @@ -169,7 +204,7 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { // needed to fix crbug.com/210295. int tab_id = GetTabOrWindowSessionId(browser_context(), caller_contents); if (tab_id < 0) - return RespondNow(Error("Not called from a tab or app window")); + return Respond(Error("Not called from a tab or app window")); // Registry lives on its own task runner. chromeos::ProcessProxyRegistry::GetTaskRunner()->PostTask( @@ -180,8 +215,7 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { base::Bind( &TerminalPrivateOpenTerminalProcessFunction::RespondOnUIThread, this), - arguments, user_id_hash)); - return RespondLater(); + arguments, UserIdHash())); } void TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner( @@ -197,8 +231,8 @@ void TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner( bool success = registry->OpenProcess(cmdline, user_id_hash, output_callback, &terminal_id); - base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI}, - base::BindOnce(callback, success, terminal_id)); + base::PostTask(FROM_HERE, {content::BrowserThread::UI}, + base::BindOnce(callback, success, terminal_id)); } TerminalPrivateSendInputFunction::~TerminalPrivateSendInputFunction() {} @@ -232,7 +266,7 @@ void TerminalPrivateSendInputFunction::SendInputOnRegistryTaskRunner( bool success = chromeos::ProcessProxyRegistry::Get()->SendInput(terminal_id, text); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce(&TerminalPrivateSendInputFunction::RespondOnUIThread, this, success)); @@ -265,7 +299,7 @@ void TerminalPrivateCloseTerminalProcessFunction::CloseOnRegistryTaskRunner( bool success = chromeos::ProcessProxyRegistry::Get()->CloseProcess(terminal_id); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &TerminalPrivateCloseTerminalProcessFunction::RespondOnUIThread, this, @@ -303,7 +337,7 @@ void TerminalPrivateOnTerminalResizeFunction::OnResizeOnRegistryTaskRunner( bool success = chromeos::ProcessProxyRegistry::Get()->OnTerminalResize( terminal_id, width, height); - base::PostTaskWithTraits( + base::PostTask( FROM_HERE, {content::BrowserThread::UI}, base::BindOnce( &TerminalPrivateOnTerminalResizeFunction::RespondOnUIThread, this, 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 601c34eb004..802d2f7c445 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h @@ -13,8 +13,7 @@ namespace extensions { // Opens new terminal process. Returns the new terminal id. -class TerminalPrivateOpenTerminalProcessFunction - : public UIThreadExtensionFunction { +class TerminalPrivateOpenTerminalProcessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.openTerminalProcess", TERMINALPRIVATE_OPENTERMINALPROCESS) @@ -34,6 +33,8 @@ class TerminalPrivateOpenTerminalProcessFunction using OpenProcessCallback = base::Callback<void(bool success, const std::string& terminal_id)>; + std::string UserIdHash(); + void OpenProcess(const std::vector<std::string> arguments); void OpenOnRegistryTaskRunner(const ProcessOutputCallback& output_callback, const OpenProcessCallback& callback, const std::vector<std::string>& arguments, @@ -43,7 +44,7 @@ class TerminalPrivateOpenTerminalProcessFunction // Send input to the terminal process specified by the terminal ID, which is set // as an argument. -class TerminalPrivateSendInputFunction : public UIThreadExtensionFunction { +class TerminalPrivateSendInputFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.sendInput", TERMINALPRIVATE_SENDINPUT) @@ -60,8 +61,7 @@ class TerminalPrivateSendInputFunction : public UIThreadExtensionFunction { }; // Closes terminal process. -class TerminalPrivateCloseTerminalProcessFunction - : public UIThreadExtensionFunction { +class TerminalPrivateCloseTerminalProcessFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.closeTerminalProcess", TERMINALPRIVATE_CLOSETERMINALPROCESS) @@ -77,8 +77,7 @@ class TerminalPrivateCloseTerminalProcessFunction }; // Called by extension when terminal size changes. -class TerminalPrivateOnTerminalResizeFunction - : public UIThreadExtensionFunction { +class TerminalPrivateOnTerminalResizeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.onTerminalResize", TERMINALPRIVATE_ONTERMINALRESIZE) @@ -95,7 +94,7 @@ class TerminalPrivateOnTerminalResizeFunction void RespondOnUIThread(bool success); }; -class TerminalPrivateAckOutputFunction : public UIThreadExtensionFunction { +class TerminalPrivateAckOutputFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("terminalPrivate.ackOutput", TERMINALPRIVATE_ACKOUTPUT) diff --git a/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h b/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h index 1b8689303ef..0bcfa273d1a 100644 --- a/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h +++ b/chromium/chrome/browser/extensions/api/top_sites/top_sites_api.h @@ -10,7 +10,7 @@ namespace extensions { -class TopSitesGetFunction : public UIThreadExtensionFunction { +class TopSitesGetFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("topSites.get", TOPSITES_GET) 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 7f27757fb74..2a0832b667a 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 @@ -163,7 +163,7 @@ namespace extensions { ChromeVirtualKeyboardDelegate::ChromeVirtualKeyboardDelegate( content::BrowserContext* browser_context) - : browser_context_(browser_context), weak_factory_(this) { + : browser_context_(browser_context) { weak_this_ = weak_factory_.GetWeakPtr(); } @@ -361,7 +361,6 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices( features->AppendString(GenerateFeatureFlag("gestureediting", false)); features->AppendString(GenerateFeatureFlag("fullscreenhandwriting", false)); features->AppendString(GenerateFeatureFlag("virtualkeyboardmdui", true)); - features->AppendString(GenerateFeatureFlag("imeservice", true)); keyboard::KeyboardConfig config = keyboard_client->GetKeyboardConfig(); // TODO(oka): Change this to use config.voice_input. @@ -378,8 +377,14 @@ void ChromeVirtualKeyboardDelegate::OnHasInputDevices( "handwritinggesture", base::FeatureList::IsEnabled(features::kHandwritingGesture))); features->AppendString(GenerateFeatureFlag( + "hmminputlogic", + base::FeatureList::IsEnabled(chromeos::features::kImeInputLogicHmm))); + features->AppendString(GenerateFeatureFlag( "fstinputlogic", base::FeatureList::IsEnabled(chromeos::features::kImeInputLogicFst))); + features->AppendString(GenerateFeatureFlag( + "fstnonenglish", base::FeatureList::IsEnabled( + chromeos::features::kImeInputLogicFstNonEnglish))); results->Set("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 cb2cc995a7f..96a8b6d3194 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 @@ -65,7 +65,7 @@ class ChromeVirtualKeyboardDelegate : public VirtualKeyboardDelegate { content::BrowserContext* browser_context_; std::unique_ptr<media::AudioSystem> audio_system_; base::WeakPtr<ChromeVirtualKeyboardDelegate> weak_this_; - base::WeakPtrFactory<ChromeVirtualKeyboardDelegate> weak_factory_; + base::WeakPtrFactory<ChromeVirtualKeyboardDelegate> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ChromeVirtualKeyboardDelegate); }; 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 7677465aa8f..98483bc6950 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 @@ -9,7 +9,6 @@ #include <memory> #include "base/no_destructor.h" -#include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api_constants.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h" #include "chrome/browser/extensions/extension_tab_util.h" @@ -19,8 +18,6 @@ #include "chrome/common/extensions/api/web_navigation.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_handle.h" -#include "content/public/browser/notification_service.h" -#include "content/public/browser/notification_types.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" @@ -51,41 +48,36 @@ TabObserverMap& GetTabObserverMap() { // WebNavigtionEventRouter ------------------------------------------- -WebNavigationEventRouter::PendingWebContents::PendingWebContents() - : source_web_contents(NULL), - source_frame_host(NULL), - target_web_contents(NULL), - target_url() { -} +WebNavigationEventRouter::PendingWebContents::PendingWebContents() = default; +WebNavigationEventRouter::PendingWebContents::~PendingWebContents() {} -WebNavigationEventRouter::PendingWebContents::PendingWebContents( - content::WebContents* source_web_contents, - content::RenderFrameHost* source_frame_host, +void WebNavigationEventRouter::PendingWebContents::Set( + int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, content::WebContents* target_web_contents, - const GURL& target_url) - : source_web_contents(source_web_contents), - source_frame_host(source_frame_host), - target_web_contents(target_web_contents), - target_url(target_url) { + const GURL& target_url, + base::OnceCallback<void(content::WebContents*)> on_destroy) { + Observe(target_web_contents); + source_tab_id_ = source_tab_id; + source_render_process_id_ = source_render_process_id; + source_extension_frame_id_ = source_extension_frame_id; + target_web_contents_ = target_web_contents; + target_url_ = target_url; + on_destroy_ = std::move(on_destroy); } -WebNavigationEventRouter::PendingWebContents::~PendingWebContents() {} +void WebNavigationEventRouter::PendingWebContents::WebContentsDestroyed() { + std::move(on_destroy_).Run(target_web_contents_); + // |this| is deleted! +} WebNavigationEventRouter::WebNavigationEventRouter(Profile* profile) : profile_(profile), browser_tab_strip_tracker_(this, this, nullptr) { - CHECK(registrar_.IsEmpty()); - registrar_.Add(this, - chrome::NOTIFICATION_TAB_ADDED, - content::NotificationService::AllSources()); - registrar_.Add(this, - content::NOTIFICATION_WEB_CONTENTS_DESTROYED, - content::NotificationService::AllSources()); - browser_tab_strip_tracker_.Init(); } -WebNavigationEventRouter::~WebNavigationEventRouter() { -} +WebNavigationEventRouter::~WebNavigationEventRouter() = default; bool WebNavigationEventRouter::ShouldTrackBrowser(Browser* browser) { return profile_->IsSameProfile(browser->profile()); @@ -95,42 +87,26 @@ void WebNavigationEventRouter::OnTabStripModelChanged( TabStripModel* tab_strip_model, const TabStripModelChange& change, const TabStripSelectionChange& selection) { - if (change.type() != TabStripModelChange::kReplaced) - return; - - auto* replace = change.GetReplace(); - WebNavigationTabObserver* tab_observer = - WebNavigationTabObserver::Get(replace->old_contents); - - if (!tab_observer) { - // If you hit this DCHECK(), please add reproduction steps to - // http://crbug.com/109464. - DCHECK(GetViewType(replace->old_contents) != VIEW_TYPE_TAB_CONTENTS); - return; - } - if (!FrameNavigationState::IsValidUrl(replace->old_contents->GetURL()) || - !FrameNavigationState::IsValidUrl(replace->new_contents->GetURL())) - return; - - web_navigation_api_helpers::DispatchOnTabReplaced( - replace->old_contents, profile_, replace->new_contents); -} - -void WebNavigationEventRouter::Observe( - int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) { - switch (type) { - case chrome::NOTIFICATION_TAB_ADDED: - TabAdded(content::Details<content::WebContents>(details).ptr()); - break; - - case content::NOTIFICATION_WEB_CONTENTS_DESTROYED: - TabDestroyed(content::Source<content::WebContents>(source).ptr()); - break; - - default: - NOTREACHED(); + if (change.type() == TabStripModelChange::kReplaced) { + auto* replace = change.GetReplace(); + WebNavigationTabObserver* tab_observer = + WebNavigationTabObserver::Get(replace->old_contents); + + if (!tab_observer) { + // If you hit this DCHECK(), please add reproduction steps to + // http://crbug.com/109464. + DCHECK(GetViewType(replace->old_contents) != VIEW_TYPE_TAB_CONTENTS); + return; + } + if (!FrameNavigationState::IsValidUrl(replace->old_contents->GetURL()) || + !FrameNavigationState::IsValidUrl(replace->new_contents->GetURL())) + return; + + web_navigation_api_helpers::DispatchOnTabReplaced( + replace->old_contents, profile_, replace->new_contents); + } else if (change.type() == TabStripModelChange::kInserted) { + for (auto& tab : change.GetInsert()->contents) + TabAdded(tab.contents); } } @@ -159,15 +135,23 @@ void WebNavigationEventRouter::RecordNewWebContents( if (!frame_navigation_state.CanSendEvents(frame_host)) return; + int source_extension_frame_id = + ExtensionApiFrameIdMap::GetFrameId(frame_host); + int source_tab_id = ExtensionTabUtil::GetTabId(source_web_contents); + // If the WebContents isn't yet inserted into a tab strip, we need to delay // the extension event until the WebContents is fully initialized. if (not_yet_in_tabstrip) { - pending_web_contents_[target_web_contents] = PendingWebContents( - source_web_contents, frame_host, target_web_contents, target_url); + pending_web_contents_[target_web_contents].Set( + source_tab_id, source_render_process_id, source_extension_frame_id, + target_web_contents, target_url, + base::BindOnce(&WebNavigationEventRouter::PendingWebContentsDestroyed, + base::Unretained(this))); } else { web_navigation_api_helpers::DispatchOnCreatedNavigationTarget( - source_web_contents, target_web_contents->GetBrowserContext(), - frame_host, target_web_contents, target_url); + source_tab_id, source_render_process_id, source_extension_frame_id, + target_web_contents->GetBrowserContext(), target_web_contents, + target_url); } } @@ -176,34 +160,18 @@ void WebNavigationEventRouter::TabAdded(content::WebContents* tab) { if (iter == pending_web_contents_.end()) return; - WebNavigationTabObserver* tab_observer = - WebNavigationTabObserver::Get(iter->second.source_web_contents); - if (!tab_observer) { - NOTREACHED(); - return; - } - const FrameNavigationState& frame_navigation_state = - tab_observer->frame_navigation_state(); - - if (frame_navigation_state.CanSendEvents(iter->second.source_frame_host)) { - web_navigation_api_helpers::DispatchOnCreatedNavigationTarget( - iter->second.source_web_contents, - iter->second.target_web_contents->GetBrowserContext(), - iter->second.source_frame_host, iter->second.target_web_contents, - iter->second.target_url); - } + const PendingWebContents& pending_tab = iter->second; + web_navigation_api_helpers::DispatchOnCreatedNavigationTarget( + pending_tab.source_tab_id(), pending_tab.source_render_process_id(), + pending_tab.source_extension_frame_id(), + pending_tab.target_web_contents()->GetBrowserContext(), + pending_tab.target_web_contents(), pending_tab.target_url()); pending_web_contents_.erase(iter); } -void WebNavigationEventRouter::TabDestroyed(content::WebContents* tab) { +void WebNavigationEventRouter::PendingWebContentsDestroyed( + content::WebContents* tab) { pending_web_contents_.erase(tab); - for (auto i = pending_web_contents_.begin(); - i != pending_web_contents_.end();) { - if (i->second.source_web_contents == tab) - pending_web_contents_.erase(i++); - else - ++i; - } } // WebNavigationTabObserver ------------------------------------------ @@ -264,14 +232,14 @@ void WebNavigationTabObserver::DidStartNavigation( // and sent after the addition, to preserve the ordering of events. // // TODO(nasko|devlin): This check is necessary because chrome::Navigate() - // begins the navigation before the sending the TAB_ADDED notification, and it + // begins the navigation before adding the tab to the TabStripModel, and it // is used an indication of that. It would be best if instead it was known // when the tab was created and immediately sent the created event instead of - // waiting for the later TAB_ADDED notification, but this appears to work for - // now. + // waiting for the later TabStripModel kInserted change, but this appears to + // work for now. if (ExtensionTabUtil::GetTabById(ExtensionTabUtil::GetTabId(web_contents()), web_contents()->GetBrowserContext(), false, - nullptr, nullptr, nullptr, nullptr)) { + nullptr)) { DispatchCachedOnBeforeNavigate(); } } @@ -400,7 +368,6 @@ void WebNavigationTabObserver::DidOpenRequestedURL( void WebNavigationTabObserver::WebContentsDestroyed() { GetTabObserverMap().erase(web_contents()); - registrar_.RemoveAll(); } void WebNavigationTabObserver::DispatchCachedOnBeforeNavigate() { @@ -500,8 +467,8 @@ ExtensionFunction::ResponseAction WebNavigationGetFrameFunction::Run() { content::WebContents* web_contents; if (!ExtensionTabUtil::GetTabById(tab_id, browser_context(), - include_incognito_information(), nullptr, - nullptr, &web_contents, nullptr) || + include_incognito_information(), + &web_contents) || !web_contents) { return RespondNow(OneArgument(std::make_unique<base::Value>())); } @@ -540,8 +507,8 @@ ExtensionFunction::ResponseAction WebNavigationGetAllFramesFunction::Run() { content::WebContents* web_contents; if (!ExtensionTabUtil::GetTabById(tab_id, browser_context(), - include_incognito_information(), nullptr, - nullptr, &web_contents, nullptr) || + include_incognito_information(), + &web_contents) || !web_contents) { return RespondNow(OneArgument(std::make_unique<base::Value>())); } 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 d76a63e1fcb..d5169edb107 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 @@ -11,6 +11,7 @@ #include <map> #include <set> +#include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "chrome/browser/extensions/api/web_navigation/frame_navigation_state.h" @@ -19,8 +20,6 @@ #include "chrome/browser/ui/browser_tab_strip_tracker.h" #include "chrome/browser/ui/browser_tab_strip_tracker_delegate.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "content/public/browser/notification_observer.h" -#include "content/public/browser/notification_registrar.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" #include "extensions/browser/browser_context_keyed_api_factory.h" @@ -97,19 +96,14 @@ class WebNavigationTabObserver // the tab strip and is ready to dispatch events. std::unique_ptr<Event> pending_on_before_navigate_event_; - // Used for tracking registrations to redirect notifications. - content::NotificationRegistrar registrar_; - WEB_CONTENTS_USER_DATA_KEY_DECL(); DISALLOW_COPY_AND_ASSIGN(WebNavigationTabObserver); }; -// Observes navigation notifications and routes them as events to the extension -// system. +// Tracks new tab navigations and routes them as events to the extension system. class WebNavigationEventRouter : public TabStripModelObserver, - public BrowserTabStripTrackerDelegate, - public content::NotificationObserver { + public BrowserTabStripTrackerDelegate { public: explicit WebNavigationEventRouter(Profile* profile); ~WebNavigationEventRouter() override; @@ -117,7 +111,7 @@ class WebNavigationEventRouter : public TabStripModelObserver, // Router level handler for the creation of WebContents. Stores information // about the newly created WebContents. This information is later used when // the WebContents for the tab is added to the tabstrip and we receive the - // TAB_ADDED notification. + // TabStripModelChanged insertion. void RecordNewWebContents(content::WebContents* source_web_contents, int source_render_process_id, int source_render_frame_id, @@ -127,18 +121,42 @@ class WebNavigationEventRouter : public TabStripModelObserver, private: // Used to cache the information about newly created WebContents objects. - struct PendingWebContents{ + // Will run |on_destroy_| if/when the target WebContents is destroyed. + class PendingWebContents : public content::WebContentsObserver { + public: PendingWebContents(); - PendingWebContents(content::WebContents* source_web_contents, - content::RenderFrameHost* source_frame_host, - content::WebContents* target_web_contents, - const GURL& target_url); - ~PendingWebContents(); - - content::WebContents* source_web_contents; - content::RenderFrameHost* source_frame_host; - content::WebContents* target_web_contents; - GURL target_url; + ~PendingWebContents() override; + + void Set(int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, + content::WebContents* target_web_contents, + const GURL& target_url, + base::OnceCallback<void(content::WebContents*)> on_destroy); + + // content::WebContentsObserver: + void WebContentsDestroyed() override; + + int source_tab_id() const { return source_tab_id_; } + int source_render_process_id() const { return source_render_process_id_; } + int source_extension_frame_id() const { return source_extension_frame_id_; } + content::WebContents* target_web_contents() const { + return target_web_contents_; + } + GURL target_url() const { return target_url_; } + + private: + // The Extensions API ID for the source tab. + int source_tab_id_ = -1; + // The source frame's RenderProcessHost ID. + int source_render_process_id_ = -1; + // The Extensions API ID for the source frame. + int source_extension_frame_id_ = -1; + content::WebContents* target_web_contents_ = nullptr; + GURL target_url_; + base::OnceCallback<void(content::WebContents*)> on_destroy_; + + DISALLOW_COPY_AND_ASSIGN(PendingWebContents); }; // BrowserTabStripTrackerDelegate implementation. @@ -150,26 +168,17 @@ class WebNavigationEventRouter : public TabStripModelObserver, const TabStripModelChange& change, const TabStripSelectionChange& selection) override; - // content::NotificationObserver implementation. - void Observe(int type, - const content::NotificationSource& source, - const content::NotificationDetails& details) override; - - // Handler for the NOTIFICATION_TAB_ADDED event. The method takes the details - // of such an event and creates a JSON formated extension event from it. + // The method takes the details of such an event and creates a JSON formatted + // extension event from it. void TabAdded(content::WebContents* tab); - // Handler for NOTIFICATION_WEB_CONTENTS_DESTROYED. If |tab| is in - // |pending_web_contents_|, it is removed. - void TabDestroyed(content::WebContents* tab); + // Removes |tab| from |pending_web_contents_| if it is there. + void PendingWebContentsDestroyed(content::WebContents* tab); // Mapping pointers to WebContents objects to information about how they got // created. std::map<content::WebContents*, PendingWebContents> pending_web_contents_; - // Used for tracking registrations to navigation notifications. - content::NotificationRegistrar registrar_; - // The profile that owns us via ExtensionService. Profile* profile_; @@ -179,14 +188,14 @@ class WebNavigationEventRouter : public TabStripModelObserver, }; // API function that returns the state of a given frame. -class WebNavigationGetFrameFunction : public UIThreadExtensionFunction { +class WebNavigationGetFrameFunction : public ExtensionFunction { ~WebNavigationGetFrameFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("webNavigation.getFrame", WEBNAVIGATION_GETFRAME) }; // API function that returns the states of all frames in a given tab. -class WebNavigationGetAllFramesFunction : public UIThreadExtensionFunction { +class WebNavigationGetAllFramesFunction : public ExtensionFunction { ~WebNavigationGetAllFramesFunction() override {} ResponseAction Run() override; DECLARE_EXTENSION_FUNCTION("webNavigation.getAllFrames", diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc index ce5b7603702..2f27a224fd5 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.cc @@ -192,9 +192,10 @@ void DispatchOnCompleted(content::WebContents* web_contents, // Constructs and dispatches an onCreatedNavigationTarget event. void DispatchOnCreatedNavigationTarget( - content::WebContents* web_contents, + int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, content::BrowserContext* browser_context, - content::RenderFrameHost* source_frame_host, content::WebContents* target_web_contents, const GURL& target_url) { // Check that the tab is already inserted into a tab strip model. This code @@ -202,13 +203,12 @@ void DispatchOnCreatedNavigationTarget( DCHECK(ExtensionTabUtil::GetTabById( ExtensionTabUtil::GetTabId(target_web_contents), Profile::FromBrowserContext(target_web_contents->GetBrowserContext()), - false, NULL, NULL, NULL, NULL)); + false, nullptr)); web_navigation::OnCreatedNavigationTarget::Details details; - details.source_tab_id = ExtensionTabUtil::GetTabId(web_contents); - details.source_process_id = source_frame_host->GetProcess()->GetID(); - details.source_frame_id = - ExtensionApiFrameIdMap::GetFrameId(source_frame_host); + details.source_tab_id = source_tab_id; + details.source_process_id = source_render_process_id; + details.source_frame_id = source_extension_frame_id; details.url = target_url.possibly_invalid_spec(); details.tab_id = ExtensionTabUtil::GetTabId(target_web_contents); details.time_stamp = MilliSecondsFromTime(base::Time::Now()); diff --git a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h index 5a447c9285a..10d3658c2a6 100644 --- a/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h +++ b/chromium/chrome/browser/extensions/api/web_navigation/web_navigation_api_helpers.h @@ -48,9 +48,10 @@ void DispatchOnCompleted(content::WebContents* web_contents, const GURL& url); void DispatchOnCreatedNavigationTarget( - content::WebContents* web_contents, + int source_tab_id, + int source_render_process_id, + int source_extension_frame_id, content::BrowserContext* browser_context, - content::RenderFrameHost* source_frame_host, content::WebContents* target_web_contents, const GURL& target_url); 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 b06f9750014..2110bfc8a4e 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 @@ -23,7 +23,6 @@ #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/extensions/api/web_navigation/web_navigation_api.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h" #include "chrome/browser/ui/browser.h" @@ -44,7 +43,7 @@ #include "content/public/test/download_test_observer.h" #include "content/public/test/no_renderer_crashes_assertion.h" #include "content/public/test/test_utils.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" #include "extensions/common/switches.h" #include "extensions/test/result_catcher.h" #include "net/dns/mock_host_resolver.h" @@ -77,7 +76,7 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, delay_url_(delay_url), until_url_suffix_(until_url_suffix), script_(script) { - tab_strip_observer_.Add(browser->tab_strip_model()); + browser->tab_strip_model()->AddObserver(this); } ~DelayLoadStartAndExecuteJavascript() override {} @@ -92,7 +91,7 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, content::WebContentsObserver::Observe( change.GetInsert()->contents[0].contents); - tab_strip_observer_.RemoveAll(); + tab_strip_model->RemoveObserver(this); } // WebContentsObserver: @@ -166,8 +165,6 @@ class DelayLoadStartAndExecuteJavascript : public TabStripModelObserver, base::WeakPtr<WillStartRequestObserverThrottle> throttle_; - ScopedObserver<TabStripModel, TabStripModelObserver> tab_strip_observer_{ - this}; GURL delay_url_; std::string until_url_suffix_; std::string script_; @@ -360,10 +357,9 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, MAYBE_UserAction) { ResultCatcher catcher; - ExtensionService* service = extensions::ExtensionSystem::Get( - browser()->profile())->extension_service(); const extensions::Extension* extension = - service->GetExtensionById(last_loaded_extension_id(), false); + extension_registry()->GetExtensionById(last_loaded_extension_id(), + ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL( "a.html?" + base::NumberToString(embedded_test_server()->port())); @@ -400,10 +396,9 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, RequestOpenTab) { ResultCatcher catcher; - ExtensionService* service = extensions::ExtensionSystem::Get( - browser()->profile())->extension_service(); const extensions::Extension* extension = - service->GetExtensionById(last_loaded_extension_id(), false); + extension_registry()->GetExtensionById(last_loaded_extension_id(), + ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL("a.html"); ui_test_utils::NavigateToURL(browser(), url); 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 e0dbdfd790e..2e416ee7641 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 @@ -39,7 +39,7 @@ #include "components/prefs/pref_member.h" #include "components/sync_preferences/testing_pref_service_syncable.h" #include "content/public/common/url_constants.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/web_request/upload_data_presenter.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/api/web_request/web_request_api_constants.h" @@ -154,7 +154,7 @@ class TestIPCSender : public IPC::Sender { class ExtensionWebRequestTest : public testing::Test { public: ExtensionWebRequestTest() - : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP), + : task_environment_(content::BrowserTaskEnvironment::IO_MAINLOOP), profile_manager_(TestingBrowserProcess::GetGlobal()) {} protected: @@ -162,7 +162,7 @@ class ExtensionWebRequestTest : public testing::Test { ASSERT_TRUE(profile_manager_.SetUp()); } - content::TestBrowserThreadBundle thread_bundle_; + content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; TestingProfileManager profile_manager_; }; 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 1398d76db6b..622cdec21a1 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 @@ -78,7 +78,8 @@ #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/blocked_action_type.h" #include "extensions/browser/extension_prefs.h" -#include "extensions/browser/extension_system.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/process_manager.h" #include "extensions/common/extension_builder.h" #include "extensions/common/extension_features.h" #include "extensions/common/features/feature.h" @@ -93,6 +94,7 @@ #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 "net/test/embedded_test_server/request_handler_util.h" #include "net/test/test_data_directory.h" #include "net/test/url_request/url_request_mock_http_job.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" @@ -242,41 +244,6 @@ class ExtensionWebRequestApiTest : public ExtensionApiTest { const char* expected_content_regular_window, const char* exptected_content_incognito_window); - void InstallRequestHeaderModifyingExtension() { - TestExtensionDir test_dir; - test_dir.WriteManifest(R"({ - "name": "Web Request Header Modifying Extension", - "manifest_version": 2, - "version": "0.1", - "background": { "scripts": ["background.js"] }, - "permissions": ["<all_urls>", "webRequest", "webRequestBlocking"] - })"); - test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"( - chrome.webRequest.onBeforeSendHeaders.addListener(function(details) { - details.requestHeaders.push({name: 'foo', value: 'bar'}); - details.requestHeaders.push({ - name: 'frameId', - value: details.frameId.toString() - }); - details.requestHeaders.push({ - name: 'resourceType', - value: details.type - }); - return {requestHeaders: details.requestHeaders}; - }, {urls: ['*://*/echoheader*']}, ['blocking', 'requestHeaders']); - - chrome.test.sendMessage('ready'); - )"); - - ExtensionTestMessageListener listener("ready", false); - ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath())); - EXPECT_TRUE(listener.WaitUntilSatisfied()); - } - - // Ensures requests made by the |worker_script_name| service worker can be - // intercepted by extensions. - void RunServiceWorkerFetchTest(const std::string& worker_script_name); - network::mojom::URLLoaderFactoryPtr CreateURLLoaderFactory() { network::mojom::URLLoaderFactoryParamsPtr params = network::mojom::URLLoaderFactoryParams::New(); @@ -305,18 +272,6 @@ class ExtensionWebRequestApiTest : public ExtensionApiTest { test_dirs_.push_back(std::move(dir)); } - void RegisterServiceWorker(const std::string& worker_path, - const base::Optional<std::string>& scope) { - GURL url = embedded_test_server()->GetURL( - "/service_worker/create_service_worker.html"); - EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); - std::string script = content::JsReplace("register($1, $2);", worker_path, - scope ? *scope : std::string()); - EXPECT_EQ( - "DONE", - EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), script)); - } - private: std::vector<std::unique_ptr<TestExtensionDir>> test_dirs_; }; @@ -534,8 +489,15 @@ IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTest, << message_; } +// TODO(crbug.com/998369): Flaky on Win ASAN. +#if defined(OS_WIN) && defined(ADDRESS_SANITIZER) +#define MAYBE_WebRequestAuthRequiredParallel \ + DISABLED_WebRequestAuthRequiredParallel +#else +#define MAYBE_WebRequestAuthRequiredParallel WebRequestAuthRequiredParallel +#endif IN_PROC_BROWSER_TEST_P(ExtensionWebRequestApiAuthRequiredTest, - WebRequestAuthRequiredParallel) { + MAYBE_WebRequestAuthRequiredParallel) { CancelLoginDialog login_dialog_helper; ASSERT_TRUE(StartEmbeddedTestServer()); @@ -581,6 +543,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestExtraHeaders) { << message_; } +IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, + WebRequestCORSWithExtraHeaders) { + ASSERT_TRUE(StartEmbeddedTestServer()); + ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_cors.html")) << message_; +} + IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestRedirects) { ASSERT_TRUE(StartEmbeddedTestServer()); ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_redirects.html")) @@ -652,10 +620,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestNewTab) { ResultCatcher catcher; - ExtensionService* service = - ExtensionSystem::Get(browser()->profile())->extension_service(); - const Extension* extension = - service->GetExtensionById(last_loaded_extension_id(), false); + ExtensionRegistry* registry = ExtensionRegistry::Get(browser()->profile()); + const Extension* extension = registry->GetExtensionById( + last_loaded_extension_id(), extensions::ExtensionRegistry::ENABLED); GURL url = extension->GetResourceURL("newTab/a.html"); ui_test_utils::NavigateToURL(browser(), url); @@ -758,30 +725,6 @@ void ExtensionWebRequestApiTest::RunPermissionTest( EXPECT_EQ(exptected_content_incognito_window, body); } -void ExtensionWebRequestApiTest::RunServiceWorkerFetchTest( - const std::string& worker_script_name) { - embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); - ASSERT_TRUE(embedded_test_server()->Start()); - - // Install the test extension. - InstallRequestHeaderModifyingExtension(); - - // Register a service worker and navigate to a page it controls. - RegisterServiceWorker(worker_script_name, base::nullopt); - EXPECT_TRUE(ui_test_utils::NavigateToURL( - browser(), - embedded_test_server()->GetURL("/service_worker/fetch_from_page.html"))); - - // Make a fetch from the controlled page. Depending on the worker script, the - // fetch might go to the service worker and be re-issued, or might fallback to - // network, or skip the worker, etc. In any case, this function expects a - // network request to happen, and that the extension modify the headers of the - // request before it goes to network. Verify that it was able to inject a - // header of "foo=bar". - EXPECT_EQ("bar", EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), - "fetch_from_page('/echoheader?foo');")); -} - IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestDeclarativePermissionSpanning1) { // Test spanning with incognito permission. @@ -949,9 +892,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, HostedAppRequest) { .Build()) .Build()) .Build(); - ExtensionSystem::Get(browser()->profile()) - ->extension_service() - ->AddExtension(hosted_app.get()); + extension_service()->AddExtension(hosted_app.get()); ExtensionTestMessageListener listener1("main_frame", false); ExtensionTestMessageListener listener2("xmlhttprequest", false); @@ -1778,7 +1719,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, content::RenderFrameHost* frame = temp_web_contents->GetMainFrame(); EXPECT_TRUE(api->MaybeProxyURLLoaderFactory( frame->GetProcess()->GetBrowserContext(), frame, - frame->GetProcess()->GetID(), false, false, &pending_receiver, nullptr)); + frame->GetProcess()->GetID(), + content::ContentBrowserClient::URLLoaderFactoryType::kDocumentSubResource, + &pending_receiver, nullptr)); temp_web_contents.reset(); auto params = network::mojom::URLLoaderFactoryParams::New(); params->process_id = 0; @@ -2498,22 +2441,177 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, RemoveHeaderUMAs) { ResponseHeaderType::kNone, 1); } -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ServiceWorkerFetch) { +// The parameter is for opt_extraInfoSpec passed to addEventListener. +// 'blocking' and 'requestHeaders' if it's false, and 'extraHeaders' in addition +// to them if it's true. +class ServiceWorkerWebRequestApiTest : public testing::WithParamInterface<bool>, + public ExtensionApiTest { + public: + // The options passed as opt_extraInfoSpec to addEventListener. + enum class ExtraInfoSpec { + // 'blocking', 'requestHeaders' + kDefault, + // kDefault + 'extraHeaders' + kExtraHeaders + }; + + static ExtraInfoSpec GetExtraInfoSpec() { + return GetParam() ? ExtraInfoSpec::kExtraHeaders : ExtraInfoSpec::kDefault; + } + + void InstallRequestHeaderModifyingExtension() { + TestExtensionDir test_dir; + test_dir.WriteManifest(R"({ + "name": "Web Request Header Modifying Extension", + "manifest_version": 2, + "version": "0.1", + "background": { "scripts": ["background.js"] }, + "permissions": ["<all_urls>", "webRequest", "webRequestBlocking"] + })"); + + const char kBackgroundScript[] = R"( + chrome.webRequest.onBeforeSendHeaders.addListener(function(details) { + details.requestHeaders.push({name: 'foo', value: 'bar'}); + details.requestHeaders.push({ + name: 'frameId', + value: details.frameId.toString() + }); + details.requestHeaders.push({ + name: 'resourceType', + value: details.type + }); + return {requestHeaders: details.requestHeaders}; + }, + {urls: ['*://*/echoheader*']}, + [%s]); + + chrome.test.sendMessage('ready'); + )"; + std::string opt_extra_info_spec = "'blocking', 'requestHeaders'"; + if (GetExtraInfoSpec() == ExtraInfoSpec::kExtraHeaders) + opt_extra_info_spec += ", 'extraHeaders'"; + test_dir.WriteFile( + FILE_PATH_LITERAL("background.js"), + base::StringPrintf(kBackgroundScript, opt_extra_info_spec.c_str())); + + ExtensionTestMessageListener listener("ready", false); + ASSERT_TRUE(LoadExtension(test_dir.UnpackedPath())); + EXPECT_TRUE(listener.WaitUntilSatisfied()); + } + + void RegisterServiceWorker(const std::string& worker_path, + const base::Optional<std::string>& scope) { + GURL url = embedded_test_server()->GetURL( + "/service_worker/create_service_worker.html"); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + std::string script = content::JsReplace("register($1, $2);", worker_path, + scope ? *scope : std::string()); + EXPECT_EQ( + "DONE", + EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), script)); + } + + // Ensures requests made by the |worker_script_name| service worker can be + // intercepted by extensions. + void RunServiceWorkerFetchTest(const std::string& worker_script_name) { + embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data"); + ASSERT_TRUE(embedded_test_server()->Start()); + + // Install the test extension. + InstallRequestHeaderModifyingExtension(); + + // Register a service worker and navigate to a page it controls. + RegisterServiceWorker(worker_script_name, base::nullopt); + EXPECT_TRUE(ui_test_utils::NavigateToURL( + browser(), embedded_test_server()->GetURL( + "/service_worker/fetch_from_page.html"))); + + // Make a fetch from the controlled page. Depending on the worker script, + // the fetch might go to the service worker and be re-issued, or might + // fallback to network, or skip the worker, etc. In any case, this function + // expects a network request to happen, and that the extension modify the + // headers of the request before it goes to network. Verify that it was able + // to inject a header of "foo=bar". + EXPECT_EQ("bar", + EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), + "fetch_from_page('/echoheader?foo');")); + } +}; + +INSTANTIATE_TEST_SUITE_P(/* No prefix */, + ServiceWorkerWebRequestApiTest, + ::testing::Bool()); + +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerFetch) { RunServiceWorkerFetchTest("fetch_event_respond_with_fetch.js"); } -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, ServiceWorkerFallback) { +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerFallback) { RunServiceWorkerFetchTest("fetch_event_pass_through.js"); } -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerNoFetchHandler) { RunServiceWorkerFetchTest("empty.js"); } +// An extension should be able to modify the request header for service worker +// script by using WebRequest API. +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerScript) { + // The extension to be used in this test adds foo=bar request header. + const char kScriptPath[] = "/echoheader_service_worker.js"; + int served_service_worker_count = 0; + std::string foo_header_value; + + // Capture the value of a request header foo, which should be added if + // extension modifies the request header. + embedded_test_server()->RegisterRequestHandler(base::BindLambdaForTesting( + [&](const net::test_server::HttpRequest& request) + -> std::unique_ptr<net::test_server::HttpResponse> { + if (request.relative_url != kScriptPath) + return nullptr; + + ++served_service_worker_count; + foo_header_value.clear(); + if (request.headers.find("foo") != request.headers.end()) + foo_header_value = request.headers.at("foo"); + + auto response = std::make_unique<net::test_server::BasicHttpResponse>(); + response->set_code(net::HTTP_OK); + response->set_content_type("text/javascript"); + response->AddCustomHeader("Cache-Control", "no-cache"); + response->set_content("// empty"); + return response; + })); + ASSERT_TRUE(embedded_test_server()->Start()); + + InstallRequestHeaderModifyingExtension(); + + content::WebContents* web_contents = + browser()->tab_strip_model()->GetActiveWebContents(); + GURL url = embedded_test_server()->GetURL( + "/service_worker/create_service_worker.html"); + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + + // Register a service worker. The worker script should have "foo: bar" request + // header added by the extension. + std::string script = + content::JsReplace("register($1, './in-scope');", kScriptPath); + EXPECT_EQ("DONE", EvalJs(web_contents, script)); + EXPECT_EQ(1, served_service_worker_count); + EXPECT_EQ("bar", foo_header_value); + + // Update the worker. The worker should have "foo: bar" request header in the + // request for update checking. + EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url)); + EXPECT_EQ("DONE", EvalJs(web_contents, "update('./in-scope');")); + EXPECT_EQ(2, served_service_worker_count); + EXPECT_EQ("bar", foo_header_value); +} + // Ensure that extensions can intercept service worker navigation preload // requests. -IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, +IN_PROC_BROWSER_TEST_P(ServiceWorkerWebRequestApiTest, ServiceWorkerNavigationPreload) { ASSERT_TRUE(embedded_test_server()->Start()); diff --git a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc index c73e3247c93..d58a7afb20d 100644 --- a/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc +++ b/chromium/chrome/browser/extensions/api/web_request/web_request_permissions_unittest.cc @@ -11,7 +11,7 @@ #include "chrome/common/extensions/extension_test_util.h" #include "chrome/common/url_constants.h" #include "chromeos/login/login_state/scoped_test_public_session_login_state.h" -#include "content/public/test/test_browser_thread_bundle.h" +#include "content/public/test/browser_task_environment.h" #include "extensions/browser/api/web_request/permission_helper.h" #include "extensions/browser/api/web_request/web_request_info.h" #include "extensions/browser/api/web_request/web_request_permissions.h" 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 9ca71edf5f6..b9f63549d5a 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 @@ -17,7 +17,7 @@ namespace extensions { class ChromeWebViewInternalContextMenusCreateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusCreate", WEBVIEWINTERNAL_CONTEXTMENUSCREATE) @@ -26,7 +26,7 @@ class ChromeWebViewInternalContextMenusCreateFunction protected: ~ChromeWebViewInternalContextMenusCreateFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: @@ -34,7 +34,7 @@ class ChromeWebViewInternalContextMenusCreateFunction }; class ChromeWebViewInternalContextMenusUpdateFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusUpdate", WEBVIEWINTERNAL_CONTEXTMENUSUPDATE) @@ -43,7 +43,7 @@ class ChromeWebViewInternalContextMenusUpdateFunction protected: ~ChromeWebViewInternalContextMenusUpdateFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: @@ -51,7 +51,7 @@ class ChromeWebViewInternalContextMenusUpdateFunction }; class ChromeWebViewInternalContextMenusRemoveFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusRemove", WEBVIEWINTERNAL_CONTEXTMENUSREMOVE) @@ -60,7 +60,7 @@ class ChromeWebViewInternalContextMenusRemoveFunction protected: ~ChromeWebViewInternalContextMenusRemoveFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: @@ -68,7 +68,7 @@ class ChromeWebViewInternalContextMenusRemoveFunction }; class ChromeWebViewInternalContextMenusRemoveAllFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("chromeWebViewInternal.contextMenusRemoveAll", WEBVIEWINTERNAL_CONTEXTMENUSREMOVEALL) @@ -77,7 +77,7 @@ class ChromeWebViewInternalContextMenusRemoveAllFunction protected: ~ChromeWebViewInternalContextMenusRemoveAllFunction() override {} - // UIThreadExtensionFunction implementation. + // ExtensionFunction implementation. ResponseAction Run() override; private: 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 3896f0b9e8f..bb110a5ba9b 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 @@ -150,8 +150,7 @@ content::RenderProcessHost* WebrtcLoggingPrivateFunction::RphFromRequest( int tab_id = *request.tab_id; content::WebContents* contents = nullptr; - if (!ExtensionTabUtil::GetTabById(tab_id, GetProfile(), true, nullptr, - nullptr, &contents, nullptr)) { + if (!ExtensionTabUtil::GetTabById(tab_id, GetProfile(), true, &contents)) { SetError(extensions::ErrorUtils::FormatErrorMessage( extensions::tabs_constants::kTabNotFoundError, base::NumberToString(tab_id))); @@ -176,8 +175,8 @@ content::RenderProcessHost* WebrtcLoggingPrivateFunction::RphFromRequest( return rph; } -WebRtcLoggingHandlerHost* -WebrtcLoggingPrivateFunction::LoggingHandlerFromRequest( +WebRtcLoggingController* +WebrtcLoggingPrivateFunction::LoggingControllerFromRequest( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin) { content::RenderProcessHost* host = RphFromRequest(request, security_origin); @@ -185,17 +184,17 @@ WebrtcLoggingPrivateFunction::LoggingHandlerFromRequest( // SetError() will have been called by RphFromRequest(). return nullptr; } - return WebRtcLoggingHandlerHost::FromRenderProcessHost(host); + return WebRtcLoggingController::FromRenderProcessHost(host); } -WebRtcLoggingHandlerHost* +WebRtcLoggingController* WebrtcLoggingPrivateFunctionWithGenericCallback::PrepareTask( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin, - WebRtcLoggingHandlerHost::GenericDoneCallback* callback) { + WebRtcLoggingController::GenericDoneCallback* callback) { *callback = base::Bind( &WebrtcLoggingPrivateFunctionWithGenericCallback::FireCallback, this); - return LoggingHandlerFromRequest(request, security_origin); + return LoggingControllerFromRequest(request, security_origin); } void WebrtcLoggingPrivateFunctionWithGenericCallback::FireCallback( @@ -245,17 +244,17 @@ bool WebrtcLoggingPrivateSetMetaDataFunction::RunAsync() { SetMetaData::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - std::unique_ptr<MetaDataMap> meta_data(new MetaDataMap()); + std::unique_ptr<WebRtcLogMetaDataMap> meta_data(new WebRtcLogMetaDataMap()); for (const MetaDataEntry& entry : params->meta_data) (*meta_data)[entry.key] = entry.value; - webrtc_logging_handler_host->SetMetaData(std::move(meta_data), callback); + webrtc_logging_controller->SetMetaData(std::move(meta_data), callback); return true; } @@ -263,13 +262,13 @@ bool WebrtcLoggingPrivateStartFunction::RunAsync() { std::unique_ptr<Start::Params> params(Start::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->StartLogging(callback); + webrtc_logging_controller->StartLogging(callback); return true; } @@ -278,18 +277,18 @@ bool WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::RunAsync() { SetUploadOnRenderClose::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost* webrtc_logging_handler_host( - LoggingHandlerFromRequest(params->request, params->security_origin)); - if (!webrtc_logging_handler_host) + WebRtcLoggingController* webrtc_logging_controller( + LoggingControllerFromRequest(params->request, params->security_origin)); + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->set_upload_log_on_render_close( + webrtc_logging_controller->set_upload_log_on_render_close( params->should_upload); // Post a task since this is an asynchronous extension function. // TODO(devlin): This is unneccessary; this should just be a - // UIThreadExtensionFunction. Fix this. - base::PostTaskWithTraits( + // ExtensionFunction. Fix this. + base::PostTask( FROM_HERE, {BrowserThread::UI}, base::BindOnce( &WebrtcLoggingPrivateSetUploadOnRenderCloseFunction::SendResponse, @@ -301,13 +300,13 @@ bool WebrtcLoggingPrivateStopFunction::RunAsync() { std::unique_ptr<Stop::Params> params(Stop::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->StopLogging(callback); + webrtc_logging_controller->StopLogging(callback); return true; } @@ -315,16 +314,16 @@ bool WebrtcLoggingPrivateStoreFunction::RunAsync() { std::unique_ptr<Store::Params> params(Store::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; const std::string local_log_id(HashIdWithOrigin(params->security_origin, params->log_id)); - webrtc_logging_handler_host->StoreLog(local_log_id, callback); + webrtc_logging_controller->StoreLog(local_log_id, callback); return true; } @@ -333,18 +332,18 @@ bool WebrtcLoggingPrivateUploadStoredFunction::RunAsync() { UploadStored::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost* logging_handler = - LoggingHandlerFromRequest(params->request, params->security_origin); - if (!logging_handler) + WebRtcLoggingController* logging_controller = + LoggingControllerFromRequest(params->request, params->security_origin); + if (!logging_controller) return false; - WebRtcLoggingHandlerHost::UploadDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateUploadStoredFunction::FireCallback, this); + WebRtcLoggingController::UploadDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateUploadStoredFunction::FireCallback, this); const std::string local_log_id(HashIdWithOrigin(params->security_origin, params->log_id)); - logging_handler->UploadStoredLog(local_log_id, callback); + logging_controller->UploadStoredLog(local_log_id, callback); return true; } @@ -352,15 +351,15 @@ bool WebrtcLoggingPrivateUploadFunction::RunAsync() { std::unique_ptr<Upload::Params> params(Upload::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost* logging_handler = - LoggingHandlerFromRequest(params->request, params->security_origin); - if (!logging_handler) + WebRtcLoggingController* logging_controller = + LoggingControllerFromRequest(params->request, params->security_origin); + if (!logging_controller) return false; - WebRtcLoggingHandlerHost::UploadDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateUploadFunction::FireCallback, this); + WebRtcLoggingController::UploadDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateUploadFunction::FireCallback, this); - logging_handler->UploadLog(callback); + logging_controller->UploadLog(callback); return true; } @@ -368,13 +367,13 @@ bool WebrtcLoggingPrivateDiscardFunction::RunAsync() { std::unique_ptr<Discard::Params> params(Discard::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - WebRtcLoggingHandlerHost::GenericDoneCallback callback; - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = + WebRtcLoggingController::GenericDoneCallback callback; + WebRtcLoggingController* webrtc_logging_controller = PrepareTask(params->request, params->security_origin, &callback); - if (!webrtc_logging_handler_host) + if (!webrtc_logging_controller) return false; - webrtc_logging_handler_host->DiscardLog(callback); + webrtc_logging_controller->DiscardLog(callback); return true; } @@ -400,19 +399,13 @@ bool WebrtcLoggingPrivateStartRtpDumpFunction::RunAsync() { return false; } - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); - WebRtcLoggingHandlerHost::GenericDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateStartRtpDumpFunction::FireCallback, this); + WebRtcLoggingController::GenericDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateStartRtpDumpFunction::FireCallback, this); - // This call cannot fail. - content::RenderProcessHost::WebRtcStopRtpDumpCallback stop_callback = - host->StartRtpDump(params->incoming, params->outgoing, - base::Bind(&WebRtcLoggingHandlerHost::OnRtpPacket, - webrtc_logging_handler_host->GetWeakPtr())); - - webrtc_logging_handler_host->StartRtpDump(type, callback, stop_callback); + webrtc_logging_controller->StartRtpDump(type, callback); return true; } @@ -438,13 +431,13 @@ bool WebrtcLoggingPrivateStopRtpDumpFunction::RunAsync() { return false; } - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); - WebRtcLoggingHandlerHost::GenericDoneCallback callback = base::Bind( - &WebrtcLoggingPrivateStopRtpDumpFunction::FireCallback, this); + WebRtcLoggingController::GenericDoneCallback callback = + base::Bind(&WebrtcLoggingPrivateStopRtpDumpFunction::FireCallback, this); - webrtc_logging_handler_host->StopRtpDump(type, callback); + webrtc_logging_controller->StopRtpDump(type, callback); return true; } @@ -527,18 +520,18 @@ bool WebrtcLoggingPrivateStartEventLoggingFunction::RunAsync() { return false; } - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); - if (!webrtc_logging_handler_host) { - SetError("WebRTC logging handler not found."); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); + if (!webrtc_logging_controller) { + SetError("WebRTC logging controller not found."); return false; } - WebRtcLoggingHandlerHost::StartEventLoggingCallback callback = + WebRtcLoggingController::StartEventLoggingCallback callback = base::BindRepeating( &WebrtcLoggingPrivateStartEventLoggingFunction::FireCallback, this); - webrtc_logging_handler_host->StartEventLogging( + webrtc_logging_controller->StartEventLogging( params->session_id, params->max_log_size_bytes, params->output_period_ms, params->web_app_id, callback); return true; @@ -573,14 +566,14 @@ bool WebrtcLoggingPrivateGetLogsDirectoryFunction::RunAsync() { // that should be granted access to the logs directory. content::RenderProcessHost* host = render_frame_host()->GetProcess(); - WebRtcLoggingHandlerHost* webrtc_logging_handler_host = - WebRtcLoggingHandlerHost::FromRenderProcessHost(host); - if (!webrtc_logging_handler_host) { - FireErrorCallback("WebRTC logging handler not found."); + WebRtcLoggingController* webrtc_logging_controller = + WebRtcLoggingController::FromRenderProcessHost(host); + if (!webrtc_logging_controller) { + FireErrorCallback("WebRTC logging controller not found."); return true; } - webrtc_logging_handler_host->GetLogsDirectory( + webrtc_logging_controller->GetLogsDirectory( base::Bind(&WebrtcLoggingPrivateGetLogsDirectoryFunction::FireCallback, this), base::Bind( diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h index 34b1124f71e..3ded513b39b 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_api.h @@ -9,7 +9,7 @@ #include "chrome/browser/extensions/chrome_extension_function.h" #include "chrome/browser/media/webrtc/audio_debug_recordings_handler.h" -#include "chrome/browser/media/webrtc/webrtc_logging_handler_host.h" +#include "chrome/browser/media/webrtc/webrtc_logging_controller.h" #include "chrome/common/extensions/api/webrtc_logging_private.h" #include "media/media_buildflags.h" @@ -32,7 +32,7 @@ class WebrtcLoggingPrivateFunction : public ChromeAsyncExtensionFunction { const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin); - WebRtcLoggingHandlerHost* LoggingHandlerFromRequest( + WebRtcLoggingController* LoggingControllerFromRequest( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin); }; @@ -42,14 +42,14 @@ class WebrtcLoggingPrivateFunctionWithGenericCallback protected: ~WebrtcLoggingPrivateFunctionWithGenericCallback() override {} - // Finds the appropriate logging handler for performing the task and prepares - // a generic callback object for when the task is completed. - // If the logging handler can't be found for the given request+origin, the + // Finds the appropriate logging controller for performing the task and + // prepares a generic callback object for when the task is completed. If the + // logging controller can't be found for the given request+origin, the // returned ptr will be null. - WebRtcLoggingHandlerHost* PrepareTask( + WebRtcLoggingController* PrepareTask( const api::webrtc_logging_private::RequestInfo& request, const std::string& security_origin, - WebRtcLoggingHandlerHost::GenericDoneCallback* callback); + WebRtcLoggingController::GenericDoneCallback* callback); // Must be called on UI thread. void FireCallback(bool success, const std::string& error_message); 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 ce5a5c00e6e..dcff38d5276 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 @@ -12,6 +12,7 @@ #include "base/bind.h" #include "base/lazy_instance.h" #include "base/macros.h" +#include "base/memory/scoped_refptr.h" #include "base/metrics/histogram_macros.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" @@ -234,7 +235,7 @@ WebstorePrivateBeginInstallWithManifest3Function::Run() { .get(); } - scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper( + auto helper = base::MakeRefCounted<WebstoreInstallHelper>( this, details().id, details().manifest, icon_url); // The helper will call us back via OnWebstoreParseSuccess or 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 0e74942a8fd..72f65444b0c 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 @@ -42,7 +42,7 @@ class WebstorePrivateApi { }; class WebstorePrivateBeginInstallWithManifest3Function - : public UIThreadExtensionFunction, + : public ExtensionFunction, public WebstoreInstallHelper::Delegate { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.beginInstallWithManifest3", @@ -97,7 +97,7 @@ class WebstorePrivateBeginInstallWithManifest3Function }; class WebstorePrivateCompleteInstallFunction - : public UIThreadExtensionFunction, + : public ExtensionFunction, public WebstoreInstaller::Delegate { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.completeInstall", @@ -126,8 +126,7 @@ class WebstorePrivateCompleteInstallFunction std::unique_ptr<ScopedActiveInstall> scoped_active_install_; }; -class WebstorePrivateEnableAppLauncherFunction - : public UIThreadExtensionFunction { +class WebstorePrivateEnableAppLauncherFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.enableAppLauncher", WEBSTOREPRIVATE_ENABLEAPPLAUNCHER) @@ -143,8 +142,7 @@ class WebstorePrivateEnableAppLauncherFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetBrowserLoginFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetBrowserLoginFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getBrowserLogin", WEBSTOREPRIVATE_GETBROWSERLOGIN) @@ -160,8 +158,7 @@ class WebstorePrivateGetBrowserLoginFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetStoreLoginFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetStoreLoginFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getStoreLogin", WEBSTOREPRIVATE_GETSTORELOGIN) @@ -177,8 +174,7 @@ class WebstorePrivateGetStoreLoginFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateSetStoreLoginFunction - : public UIThreadExtensionFunction { +class WebstorePrivateSetStoreLoginFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.setStoreLogin", WEBSTOREPRIVATE_SETSTORELOGIN) @@ -194,8 +190,7 @@ class WebstorePrivateSetStoreLoginFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetWebGLStatusFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetWebGLStatusFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getWebGLStatus", WEBSTOREPRIVATE_GETWEBGLSTATUS) @@ -213,8 +208,7 @@ class WebstorePrivateGetWebGLStatusFunction scoped_refptr<content::GpuFeatureChecker> feature_checker_; }; -class WebstorePrivateGetIsLauncherEnabledFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetIsLauncherEnabledFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getIsLauncherEnabled", WEBSTOREPRIVATE_GETISLAUNCHERENABLED) @@ -230,8 +224,7 @@ class WebstorePrivateGetIsLauncherEnabledFunction void OnIsLauncherCheckCompleted(bool is_enabled); }; -class WebstorePrivateIsInIncognitoModeFunction - : public UIThreadExtensionFunction { +class WebstorePrivateIsInIncognitoModeFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.isInIncognitoMode", WEBSTOREPRIVATE_ISININCOGNITOMODEFUNCTION) @@ -247,8 +240,7 @@ class WebstorePrivateIsInIncognitoModeFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateLaunchEphemeralAppFunction - : public UIThreadExtensionFunction { +class WebstorePrivateLaunchEphemeralAppFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.launchEphemeralApp", WEBSTOREPRIVATE_LAUNCHEPHEMERALAPP) @@ -272,7 +264,7 @@ class WebstorePrivateLaunchEphemeralAppFunction }; class WebstorePrivateGetEphemeralAppsEnabledFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getEphemeralAppsEnabled", WEBSTOREPRIVATE_GETEPHEMERALAPPSENABLED) @@ -287,7 +279,7 @@ class WebstorePrivateGetEphemeralAppsEnabledFunction }; class WebstorePrivateIsPendingCustodianApprovalFunction - : public UIThreadExtensionFunction { + : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.isPendingCustodianApproval", WEBSTOREPRIVATE_ISPENDINGCUSTODIANAPPROVAL) @@ -305,8 +297,7 @@ class WebstorePrivateIsPendingCustodianApprovalFunction ChromeExtensionFunctionDetails chrome_details_; }; -class WebstorePrivateGetReferrerChainFunction - : public UIThreadExtensionFunction { +class WebstorePrivateGetReferrerChainFunction : public ExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("webstorePrivate.getReferrerChain", WEBSTOREPRIVATE_GETREFERRERCHAIN) 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 b544f0de6ee..e88e6e1865d 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 @@ -42,6 +42,7 @@ #include "ui/gl/gl_switches.h" #if BUILDFLAG(ENABLE_SUPERVISED_USERS) +#include "chrome/browser/supervised_user/logged_in_user_mixin.h" #include "chrome/browser/supervised_user/supervised_user_constants.h" #if defined(OS_CHROMEOS) @@ -375,23 +376,89 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, EmptyCrx) { class ExtensionWebstorePrivateApiTestChild : public ExtensionWebstorePrivateApiTest { public: + ExtensionWebstorePrivateApiTestChild() + : embedded_test_server_(std::make_unique<net::EmbeddedTestServer>()), + logged_in_user_mixin_(&mixin_host_, + chromeos::LoggedInUserMixin::LogInType::kChild, + embedded_test_server_.get()) { + // Suppress regular user login to enable child user login. + set_chromeos_user_ = false; + } + + void SetUp() override { + mixin_host_.SetUp(); + ExtensionWebstorePrivateApiTest::SetUp(); + } + void SetUpCommandLine(base::CommandLine* command_line) override { + mixin_host_.SetUpCommandLine(command_line); ExtensionWebstorePrivateApiTest::SetUpCommandLine(command_line); - command_line->AppendSwitchASCII(switches::kSupervisedUserId, - supervised_users::kChildAccountSUID); -#if defined(OS_CHROMEOS) - command_line->AppendSwitchASCII( - chromeos::switches::kLoginUser, - "supervised_user@locally-managed.localhost"); - command_line->AppendSwitchASCII(chromeos::switches::kLoginProfile, "hash"); -#endif + // Shortens the merge session timeout from 20 to 1 seconds to speed up the + // test by about 19 seconds. + // TODO (crbug.com/995575): figure out why this switch speeds up the test, + // and fix the test setup so this is not required. + command_line->AppendSwitch(switches::kShortMergeSessionTimeoutForTest); + } + + void SetUpDefaultCommandLine(base::CommandLine* command_line) override { + mixin_host_.SetUpDefaultCommandLine(command_line); + ExtensionWebstorePrivateApiTest::SetUpDefaultCommandLine(command_line); + } + + bool SetUpUserDataDirectory() override { + return mixin_host_.SetUpUserDataDirectory() && + ExtensionWebstorePrivateApiTest::SetUpUserDataDirectory(); + } + + void SetUpInProcessBrowserTestFixture() override { + mixin_host_.SetUpInProcessBrowserTestFixture(); + ExtensionWebstorePrivateApiTest::SetUpInProcessBrowserTestFixture(); + } + + void CreatedBrowserMainParts( + content::BrowserMainParts* browser_main_parts) override { + mixin_host_.CreatedBrowserMainParts(browser_main_parts); + ExtensionWebstorePrivateApiTest::CreatedBrowserMainParts( + browser_main_parts); + } + + void SetUpOnMainThread() override { + mixin_host_.SetUpOnMainThread(); + ExtensionWebstorePrivateApiTest::SetUpOnMainThread(); + logged_in_user_mixin_.SetUpOnMainThreadHelper( + host_resolver(), this, true /* issue_any_scope_token */); + } + + void TearDownOnMainThread() override { + mixin_host_.TearDownOnMainThread(); + ExtensionWebstorePrivateApiTest::TearDownOnMainThread(); } + + void TearDownInProcessBrowserTestFixture() override { + mixin_host_.TearDownInProcessBrowserTestFixture(); + ExtensionWebstorePrivateApiTest::TearDownInProcessBrowserTestFixture(); + } + + void TearDown() override { + mixin_host_.TearDown(); + ExtensionWebstorePrivateApiTest::TearDown(); + } + + private: + // Replicate what MixinBasedInProcessBrowserTest does since inheriting from + // that class is inconvenient here. + InProcessBrowserTestMixinHost mixin_host_; + // 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_; }; // Tests that extension installation is blocked for child accounts, and // attempting to do so produces a special error code. // Note: This will have to be updated when we enable child-initiated installs. IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTestChild, InstallBlocked) { + ASSERT_TRUE(browser()); ASSERT_TRUE(RunInstallTest("begin_install_fail_child.html", "extension.crx")); } |