diff options
author | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-05-03 13:42:47 +0200 |
---|---|---|
committer | Allan Sandfeld Jensen <allan.jensen@qt.io> | 2018-05-15 10:27:51 +0000 |
commit | 8c5c43c7b138c9b4b0bf56d946e61d3bbc111bec (patch) | |
tree | d29d987c4d7b173cf853279b79a51598f104b403 /chromium/chrome/browser/extensions/api | |
parent | 830c9e163d31a9180fadca926b3e1d7dfffb5021 (diff) | |
download | qtwebengine-chromium-8c5c43c7b138c9b4b0bf56d946e61d3bbc111bec.tar.gz |
BASELINE: Update Chromium to 66.0.3359.156
Change-Id: I0c9831ad39911a086b6377b16f995ad75a51e441
Reviewed-by: Michal Klocek <michal.klocek@qt.io>
Diffstat (limited to 'chromium/chrome/browser/extensions/api')
158 files changed, 2266 insertions, 1672 deletions
diff --git a/chromium/chrome/browser/extensions/api/DEPS b/chromium/chrome/browser/extensions/api/DEPS index fea8d34597f..e6dcb249500 100644 --- a/chromium/chrome/browser/extensions/api/DEPS +++ b/chromium/chrome/browser/extensions/api/DEPS @@ -8,7 +8,7 @@ include_rules = [ # Enable remote assistance on Chrome OS "+remoting/base", "+remoting/host", - "+services/network/public/interfaces", + "+services/network", ] specific_include_rules = { diff --git a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc index 81b27277daa..12183657a08 100644 --- a/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc +++ b/chromium/chrome/browser/extensions/api/automation/automation_apitest.cc @@ -120,7 +120,13 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, Actions) { << message_; } -IN_PROC_BROWSER_TEST_F(AutomationApiTest, Location) { +// TODO(https://crbug.com/622387): Disabled due to flakiness. +#if defined(OS_CHROMEOS) && defined(NDEBUG) +#define MAYBE_Location DISABLED_Location +#else +#define MAYBE_Location Location +#endif +IN_PROC_BROWSER_TEST_F(AutomationApiTest, MAYBE_Location) { StartEmbeddedTestServer(); ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", "location.html")) << message_; @@ -174,14 +180,14 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, TabsAutomationHostsPermissions) { } #if defined(USE_AURA) -// Flaky, see http://crbug.com/637525 +// TODO(https://crbug.com/754870): Disabled due to flakiness. IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_Desktop) { ASSERT_TRUE(RunExtensionSubtest("automation/tests/desktop", "desktop.html")) << message_; } #if defined(OS_CHROMEOS) -// TODO(crbug.com/615908): Flaky on CrOS sanitizers. +// TODO(https://crbug.com/754870): Flaky on CrOS sanitizers. IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_DesktopInitialFocus) { ASSERT_TRUE( RunExtensionSubtest("automation/tests/desktop", "initial_focus.html")) @@ -194,8 +200,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopFocusWeb) { << message_; } -// Flaky, see https://crbug.com/724923. -IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_DesktopFocusIframe) { +IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopFocusIframe) { StartEmbeddedTestServer(); ASSERT_TRUE( RunExtensionSubtest("automation/tests/desktop", "focus_iframe.html")) @@ -247,7 +252,7 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, DesktopHitTest) { << message_; } -// Flaky, see http://crbug.com/435449 +// TODO(https://crbug.com/754870): flaky. IN_PROC_BROWSER_TEST_F(AutomationApiTest, DISABLED_DesktopLoadTabs) { ASSERT_TRUE(RunExtensionSubtest("automation/tests/desktop", "load_tabs.html")) << message_; @@ -280,13 +285,19 @@ IN_PROC_BROWSER_TEST_F(AutomationApiTest, Find) { << message_; } -// TODO(crbug.com/725420) Flaky IN_PROC_BROWSER_TEST_F(AutomationApiTest, Attributes) { StartEmbeddedTestServer(); ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", "attributes.html")) << message_; } +IN_PROC_BROWSER_TEST_F(AutomationApiTest, ReverseRelations) { + StartEmbeddedTestServer(); + ASSERT_TRUE( + RunExtensionSubtest("automation/tests/tabs", "reverse_relations.html")) + << message_; +} + IN_PROC_BROWSER_TEST_F(AutomationApiTest, TreeChange) { StartEmbeddedTestServer(); ASSERT_TRUE(RunExtensionSubtest("automation/tests/tabs", "tree_change.html")) diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc index b54484f9b58..b87d67a8227 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_event_router.cc @@ -23,7 +23,7 @@ #include "extensions/browser/event_router.h" #include "extensions/common/extension.h" #include "ui/accessibility/ax_action_data.h" -#include "ui/accessibility/ax_enums.h" +#include "ui/accessibility/ax_enums.mojom.h" #include "ui/accessibility/ax_node_data.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc index c468f587436..e8309a03a77 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.cc @@ -15,6 +15,7 @@ #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/api/automation_internal/automation_event_router.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" +#include "chrome/browser/extensions/chrome_extension_function_details.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" @@ -37,6 +38,7 @@ #include "extensions/common/extension_messages.h" #include "extensions/common/permissions/permissions_data.h" #include "ui/accessibility/ax_action_data.h" +#include "ui/accessibility/ax_enum_util.h" #include "ui/accessibility/ax_host_delegate.h" #include "ui/accessibility/ax_tree_id_registry.h" @@ -208,7 +210,7 @@ class AutomationWebContentsObserver std::vector<content::AXEventNotificationDetails> details; content::AXEventNotificationDetails detail; detail.ax_tree_id = id.first->GetAXTreeID(); - detail.event_type = ui::AX_EVENT_MEDIA_STARTED_PLAYING; + detail.event_type = ax::mojom::Event::kMediaStartedPlaying; details.push_back(detail); AccessibilityEventReceived(details); } @@ -220,7 +222,7 @@ class AutomationWebContentsObserver std::vector<content::AXEventNotificationDetails> details; content::AXEventNotificationDetails detail; detail.ax_tree_id = id.first->GetAXTreeID(); - detail.event_type = ui::AX_EVENT_MEDIA_STOPPED_PLAYING; + detail.event_type = ax::mojom::Event::kMediaStoppedPlaying; details.push_back(detail); AccessibilityEventReceived(details); } @@ -239,7 +241,7 @@ class AutomationWebContentsObserver content::AXEventNotificationDetails detail; detail.ax_tree_id = rfh->GetAXTreeID(); - detail.event_type = ui::AX_EVENT_MEDIA_STARTED_PLAYING; + detail.event_type = ax::mojom::Event::kMediaStartedPlaying; details.push_back(detail); AccessibilityEventReceived(details); } @@ -261,18 +263,19 @@ AutomationInternalEnableTabFunction::Run() { content::WebContents* contents = NULL; if (params->args.tab_id.get()) { int tab_id = *params->args.tab_id; - if (!ExtensionTabUtil::GetTabById(tab_id, - GetProfile(), - include_incognito(), - NULL, /* browser out param*/ - NULL, /* tab_strip out param */ - &contents, - NULL /* tab_index out param */)) { + if (!ExtensionTabUtil::GetTabById( + tab_id, browser_context(), include_incognito(), + NULL, /* browser out param*/ + NULL, /* tab_strip out param */ + &contents, NULL /* tab_index out param */)) { return RespondNow( Error(tabs_constants::kTabNotFoundError, base::IntToString(tab_id))); } } else { - contents = GetCurrentBrowser()->tab_strip_model()->GetActiveWebContents(); + contents = ChromeExtensionFunctionDetails(this) + .GetCurrentBrowser() + ->tab_strip_model() + ->GetActiveWebContents(); if (!contents) return RespondNow(Error("No active tab")); } @@ -336,17 +339,17 @@ AutomationInternalPerformActionFunction::ConvertToAXActionData( action->request_id = request_id ? *request_id : -1; switch (params->args.action_type) { case api::automation_internal::ACTION_TYPE_DODEFAULT: - action->action = ui::AX_ACTION_DO_DEFAULT; + action->action = ax::mojom::Action::kDoDefault; break; case api::automation_internal::ACTION_TYPE_FOCUS: - action->action = ui::AX_ACTION_FOCUS; + action->action = ax::mojom::Action::kFocus; break; case api::automation_internal::ACTION_TYPE_GETIMAGEDATA: { api::automation_internal::GetImageDataParams get_image_data_params; EXTENSION_FUNCTION_VALIDATE( api::automation_internal::GetImageDataParams::Populate( params->opt_args.additional_properties, &get_image_data_params)); - action->action = ui::AX_ACTION_GET_IMAGE_DATA; + action->action = ax::mojom::Action::kGetImageData; action->target_rect = gfx::Rect(0, 0, get_image_data_params.max_width, get_image_data_params.max_height); break; @@ -356,34 +359,34 @@ AutomationInternalPerformActionFunction::ConvertToAXActionData( EXTENSION_FUNCTION_VALIDATE( api::automation_internal::HitTestParams::Populate( params->opt_args.additional_properties, &hit_test_params)); - action->action = ui::AX_ACTION_HIT_TEST; + action->action = ax::mojom::Action::kHitTest; action->target_point = gfx::Point(hit_test_params.x, hit_test_params.y); action->hit_test_event_to_fire = - ui::ParseAXEvent(hit_test_params.event_to_fire); - if (action->hit_test_event_to_fire == ui::AX_EVENT_NONE) + ui::ParseEvent(hit_test_params.event_to_fire.c_str()); + if (action->hit_test_event_to_fire == ax::mojom::Event::kNone) return RespondNow(NoArguments()); break; } case api::automation_internal::ACTION_TYPE_MAKEVISIBLE: - action->action = ui::AX_ACTION_SCROLL_TO_MAKE_VISIBLE; + action->action = ax::mojom::Action::kScrollToMakeVisible; break; case api::automation_internal::ACTION_TYPE_SCROLLBACKWARD: - action->action = ui::AX_ACTION_SCROLL_BACKWARD; + action->action = ax::mojom::Action::kScrollBackward; break; case api::automation_internal::ACTION_TYPE_SCROLLFORWARD: - action->action = ui::AX_ACTION_SCROLL_FORWARD; + action->action = ax::mojom::Action::kScrollForward; break; case api::automation_internal::ACTION_TYPE_SCROLLUP: - action->action = ui::AX_ACTION_SCROLL_UP; + action->action = ax::mojom::Action::kScrollUp; break; case api::automation_internal::ACTION_TYPE_SCROLLDOWN: - action->action = ui::AX_ACTION_SCROLL_DOWN; + action->action = ax::mojom::Action::kScrollDown; break; case api::automation_internal::ACTION_TYPE_SCROLLLEFT: - action->action = ui::AX_ACTION_SCROLL_LEFT; + action->action = ax::mojom::Action::kScrollLeft; break; case api::automation_internal::ACTION_TYPE_SCROLLRIGHT: - action->action = ui::AX_ACTION_SCROLL_RIGHT; + action->action = ax::mojom::Action::kScrollRight; break; case api::automation_internal::ACTION_TYPE_SETSELECTION: { api::automation_internal::SetSelectionParams selection_params; @@ -394,17 +397,17 @@ AutomationInternalPerformActionFunction::ConvertToAXActionData( action->anchor_offset = selection_params.anchor_offset; action->focus_node_id = selection_params.focus_node_id; action->focus_offset = selection_params.focus_offset; - action->action = ui::AX_ACTION_SET_SELECTION; + action->action = ax::mojom::Action::kSetSelection; break; } case api::automation_internal::ACTION_TYPE_SHOWCONTEXTMENU: { - action->action = ui::AX_ACTION_SHOW_CONTEXT_MENU; + action->action = ax::mojom::Action::kShowContextMenu; break; } case api::automation_internal:: ACTION_TYPE_SETSEQUENTIALFOCUSNAVIGATIONSTARTINGPOINT: { action->action = - ui::AX_ACTION_SET_SEQUENTIAL_FOCUS_NAVIGATION_STARTING_POINT; + ax::mojom::Action::kSetSequentialFocusNavigationStartingPoint; break; } case api::automation_internal::ACTION_TYPE_CUSTOMACTION: { @@ -414,7 +417,7 @@ AutomationInternalPerformActionFunction::ConvertToAXActionData( api::automation_internal::PerformCustomActionParams::Populate( params->opt_args.additional_properties, &perform_custom_action_params)); - action->action = ui::AX_ACTION_CUSTOM_ACTION; + action->action = ax::mojom::Action::kCustomAction; action->custom_action_id = perform_custom_action_params.custom_action_id; break; } diff --git a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h index ffce688fc36..2971910dca3 100644 --- a/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h +++ b/chromium/chrome/browser/extensions/api/automation_internal/automation_internal_api.h @@ -7,9 +7,9 @@ #include <string> -#include "chrome/browser/extensions/chrome_extension_function.h" #include "content/public/browser/web_contents_observer.h" #include "content/public/browser/web_contents_user_data.h" +#include "extensions/browser/extension_function.h" namespace extensions { @@ -29,8 +29,7 @@ struct AXActionData; namespace extensions { // Implementation of the chrome.automation API. -class AutomationInternalEnableTabFunction - : public ChromeUIThreadExtensionFunction { +class AutomationInternalEnableTabFunction : public UIThreadExtensionFunction { DECLARE_EXTENSION_FUNCTION("automationInternal.enableTab", AUTOMATIONINTERNAL_ENABLETAB) protected: diff --git a/chromium/chrome/browser/extensions/api/autotest_private/DEPS b/chromium/chrome/browser/extensions/api/autotest_private/DEPS new file mode 100644 index 00000000000..b21e182ab37 --- /dev/null +++ b/chromium/chrome/browser/extensions/api/autotest_private/DEPS @@ -0,0 +1,3 @@ +include_rules = [ + "+ui/message_center", +] diff --git a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc index 7a2179a278f..8bdc5a72567 100644 --- a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc +++ b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.cc @@ -37,7 +37,7 @@ #include "chromeos/printing/printer_configuration.h" #include "components/user_manager/user_manager.h" #include "ui/message_center/message_center.h" -#include "ui/message_center/notification.h" +#include "ui/message_center/public/cpp/notification.h" #endif namespace extensions { @@ -396,6 +396,10 @@ AutotestPrivateGetVisibleNotificationsFunction::Run() { DVLOG(1) << "AutotestPrivateGetVisibleNotificationsFunction"; std::unique_ptr<base::ListValue> values(new base::ListValue); #if defined(OS_CHROMEOS) + // TODO(estade): we can't rely on the message center being available in the + // browser process (in mash). Make autotests that use it fail loudly. See + // crbug.com/804570 + CHECK(message_center::MessageCenter::Get()); for (auto* notification : message_center::MessageCenter::Get()->GetVisibleNotifications()) { auto result = std::make_unique<base::DictionaryValue>(); diff --git a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h index 7f55a387113..7eb44055070 100644 --- a/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h +++ b/chromium/chrome/browser/extensions/api/autotest_private/autotest_private_api.h @@ -10,7 +10,7 @@ #include "base/compiler_specific.h" #include "chrome/browser/extensions/chrome_extension_function.h" #include "extensions/browser/browser_context_keyed_api_factory.h" -#include "ui/message_center/notification_types.h" +#include "ui/message_center/public/cpp/notification_types.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/printing/cups_printers_manager.h" diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc index 8717bf94ac3..c4cdaf3aa3b 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmark_apitest.cc @@ -21,13 +21,7 @@ using bookmarks::BookmarkModel; -// Flaky on Windows and Linux. http://crbug.com/383452 -#if defined(OS_WIN) || defined(OS_LINUX) -#define MAYBE_Bookmarks DISABLED_Bookmarks -#else -#define MAYBE_Bookmarks Bookmarks -#endif -IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Bookmarks) { +IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Bookmarks) { // Add test managed bookmarks to verify that the bookmarks API can read them // and can't modify them. Profile* profile = browser()->profile(); diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc index 397e6f924bf..1e93c03bfd7 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.cc @@ -555,7 +555,7 @@ bool BookmarksSearchFunction::RunOnReady() { return true; } -bool BookmarksRemoveFunction::RunOnReady() { +bool BookmarksRemoveFunctionBase::RunOnReady() { if (!EditBookmarksEnabled()) return false; @@ -567,15 +567,21 @@ bool BookmarksRemoveFunction::RunOnReady() { if (!GetBookmarkIdAsInt64(params->id, &id)) return false; - bool recursive = false; - if (name() == BookmarksRemoveTreeFunction::function_name()) - recursive = true; - BookmarkModel* model = GetBookmarkModel(); ManagedBookmarkService* managed = GetManagedBookmarkService(); - if (!bookmark_api_helpers::RemoveNode(model, managed, id, recursive, &error_)) + if (!bookmark_api_helpers::RemoveNode(model, managed, id, is_recursive(), + &error_)) { return false; + } + + return true; +} + +bool BookmarksRemoveFunction::is_recursive() const { + return false; +} +bool BookmarksRemoveTreeFunction::is_recursive() const { return true; } diff --git a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h index f67548f71c8..610c6410c80 100644 --- a/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h +++ b/chromium/chrome/browser/extensions/api/bookmarks/bookmarks_api.h @@ -244,23 +244,36 @@ class BookmarksSearchFunction : public BookmarksFunction { bool RunOnReady() override; }; -class BookmarksRemoveFunction : public BookmarksFunction { +class BookmarksRemoveFunctionBase : public BookmarksFunction { + protected: + ~BookmarksRemoveFunctionBase() override {} + + virtual bool is_recursive() const = 0; + + // BookmarksFunction: + bool RunOnReady() override; +}; + +class BookmarksRemoveFunction : public BookmarksRemoveFunctionBase { public: - DECLARE_EXTENSION_FUNCTION("bookmarks.remove", BOOKMARKS_REMOVE) + DECLARE_EXTENSION_FUNCTION("bookmarks.remove", BOOKMARKS_REMOVE); protected: ~BookmarksRemoveFunction() override {} - // BookmarksFunction: - bool RunOnReady() override; + // BookmarksRemoveFunctionBase: + bool is_recursive() const override; }; -class BookmarksRemoveTreeFunction : public BookmarksRemoveFunction { +class BookmarksRemoveTreeFunction : public BookmarksRemoveFunctionBase { public: DECLARE_EXTENSION_FUNCTION("bookmarks.removeTree", BOOKMARKS_REMOVETREE) protected: ~BookmarksRemoveTreeFunction() override {} + + // BookmarksRemoveFunctionBase: + bool is_recursive() const override; }; class BookmarksCreateFunction : public BookmarksFunction { 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 c16ed76a1da..244be025170 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 @@ -136,11 +136,8 @@ bool BrowsingDataSettingsFunction::isDataTypeSelected( ExtensionFunction::ResponseAction BrowsingDataSettingsFunction::Run() { prefs_ = Profile::FromBrowserContext(browser_context())->GetPrefs(); - ClearBrowsingDataTab tab = - base::FeatureList::IsEnabled(features::kTabsInCbd) - ? static_cast<ClearBrowsingDataTab>(prefs_->GetInteger( - browsing_data::prefs::kLastClearBrowsingDataTab)) - : ClearBrowsingDataTab::ADVANCED; + ClearBrowsingDataTab tab = static_cast<ClearBrowsingDataTab>( + prefs_->GetInteger(browsing_data::prefs::kLastClearBrowsingDataTab)); // Fill origin types. // The "cookies" and "hosted apps" UI checkboxes both map to 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 d777b98d233..f0e724e64a3 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 @@ -9,7 +9,6 @@ #include "base/memory/ref_counted.h" #include "base/strings/pattern.h" #include "base/strings/string_util.h" -#include "base/test/scoped_feature_list.h" #include "base/values.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/chrome_browsing_data_remover_delegate.h" @@ -17,7 +16,6 @@ #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" -#include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/browsing_data/core/browsing_data_utils.h" @@ -62,7 +60,6 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { protected: void SetUp() override { - feature_list_.InitAndEnableFeature(features::kTabsInCbd); InProcessBrowserTest::SetUp(); } @@ -297,7 +294,6 @@ class ExtensionBrowsingDataTest : public InProcessBrowserTest { } private: - base::test::ScopedFeatureList feature_list_; // Cached pointer to BrowsingDataRemover for access to testing methods. content::BrowsingDataRemover* remover_; }; diff --git a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc index 8a53d8a19aa..3a6d2f4f736 100644 --- a/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc +++ b/chromium/chrome/browser/extensions/api/cast_streaming/performance_test.cc @@ -68,13 +68,9 @@ constexpr size_t kTrimEvents = 24; // 1 sec at 24fps, or 0.4 sec at 60 fps. constexpr size_t kMinDataPoints = 100; // 1 sec of audio, or ~5 sec at 24fps. enum TestFlags { - // TODO(miu): Remove kUseGpu (since the GPU is required), and maybe - // kDisableVsync. http://crbug.com/567848 kUseGpu = 1 << 0, // Only execute test if --enable-gpu was given // on the command line. This is required for // tests that run on GPU. - kDisableVsync = 1 << 1, // Do not limit framerate to vertical refresh. - // when on GPU, nor to 60hz when not on GPU. kSmallWindow = 1 << 2, // Window size: 1 = 800x600, 0 = 2000x1000 k24fps = 1 << 3, // Use 24 fps video. k30fps = 1 << 4, // Use 30 fps video. @@ -368,8 +364,6 @@ class CastV2PerformanceTest std::string suffix; if (HasFlag(kUseGpu)) suffix += "_gpu"; - if (HasFlag(kDisableVsync)) - suffix += "_novsync"; if (HasFlag(kSmallWindow)) suffix += "_small"; if (HasFlag(k24fps)) @@ -406,6 +400,8 @@ class CastV2PerformanceTest void SetUp() override { EnablePixelOutput(); + if (!HasFlag(kUseGpu)) + UseSoftwareCompositing(); ExtensionApiTest::SetUp(); } @@ -425,12 +421,10 @@ class CastV2PerformanceTest if (!HasFlag(kUseGpu)) command_line->AppendSwitch(switches::kDisableGpu); - if (HasFlag(kDisableVsync)) - command_line->AppendSwitch(switches::kDisableGpuVsync); - command_line->AppendSwitchASCII( extensions::switches::kWhitelistedExtensionID, kExtensionId); + ExtensionApiTest::SetUpCommandLine(command_line); } @@ -721,7 +715,6 @@ INSTANTIATE_TEST_CASE_P( testing::Values(kUseGpu | k24fps, kUseGpu | k30fps, kUseGpu | k60fps, - kUseGpu | k24fps | kDisableVsync, kUseGpu | k30fps | kProxyWifi, kUseGpu | k30fps | kProxyBad, kUseGpu | k30fps | kSlowClock, diff --git a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc index 90c1889cb5e..17dbddd0d73 100644 --- a/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc +++ b/chromium/chrome/browser/extensions/api/cloud_print_private/cloud_print_private_api.cc @@ -7,7 +7,6 @@ #include <memory> #include <string> -#include "base/threading/sequenced_worker_pool.h" #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h" #include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h" #include "chrome/common/extensions/api/cloud_print_private.h" diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.cc b/chromium/chrome/browser/extensions/api/commands/command_service.cc index 3f3661f362e..362c8e4bf5a 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.cc +++ b/chromium/chrome/browser/extensions/api/commands/command_service.cc @@ -133,8 +133,8 @@ void CommandService::RegisterProfilePrefs( CommandService::CommandService(content::BrowserContext* context) : profile_(Profile::FromBrowserContext(context)), extension_registry_observer_(this) { - ExtensionFunctionRegistry::GetInstance()-> - RegisterFunction<GetAllCommandsFunction>(); + ExtensionFunctionRegistry::GetInstance() + .RegisterFunction<GetAllCommandsFunction>(); extension_registry_observer_.Add(ExtensionRegistry::Get(profile_)); } @@ -177,16 +177,16 @@ bool CommandService::GetBrowserActionCommand(const std::string& extension_id, QueryType type, Command* command, bool* active) const { - return GetExtensionActionCommand( - extension_id, type, command, active, BROWSER_ACTION); + return GetExtensionActionCommand(extension_id, type, command, active, + Command::Type::kBrowserAction); } bool CommandService::GetPageActionCommand(const std::string& extension_id, QueryType type, Command* command, bool* active) const { - return GetExtensionActionCommand( - extension_id, type, command, active, PAGE_ACTION); + return GetExtensionActionCommand(extension_id, type, command, active, + Command::Type::kPageAction); } bool CommandService::GetNamedCommands(const std::string& extension_id, @@ -403,8 +403,7 @@ Command CommandService::FindCommandByName(const std::string& extension_id, bool CommandService::GetSuggestedExtensionCommand( const std::string& extension_id, const ui::Accelerator& accelerator, - Command* command, - ExtensionCommandType* command_type) const { + Command* command) const { const Extension* extension = ExtensionRegistry::Get(profile_) ->GetExtensionById(extension_id, ExtensionRegistry::ENABLED); @@ -419,8 +418,6 @@ bool CommandService::GetSuggestedExtensionCommand( accelerator == prospective_command.accelerator()) { if (command) *command = prospective_command; - if (command_type) - *command_type = BROWSER_ACTION; return true; } else if (GetPageActionCommand(extension_id, CommandService::SUGGESTED, @@ -429,8 +426,6 @@ bool CommandService::GetSuggestedExtensionCommand( accelerator == prospective_command.accelerator()) { if (command) *command = prospective_command; - if (command_type) - *command_type = PAGE_ACTION; return true; } else if (GetNamedCommands(extension_id, CommandService::SUGGESTED, @@ -442,8 +437,6 @@ bool CommandService::GetSuggestedExtensionCommand( if (accelerator == it->second.accelerator()) { if (command) *command = it->second; - if (command_type) - *command_type = NAMED; return true; } } @@ -454,11 +447,10 @@ bool CommandService::GetSuggestedExtensionCommand( bool CommandService::RequestsBookmarkShortcutOverride( const Extension* extension) const { return RemovesBookmarkShortcut(extension) && - GetSuggestedExtensionCommand( - extension->id(), - chrome::GetPrimaryChromeAcceleratorForCommandId(IDC_BOOKMARK_PAGE), - NULL, - NULL); + GetSuggestedExtensionCommand( + extension->id(), + chrome::GetPrimaryChromeAcceleratorForCommandId(IDC_BOOKMARK_PAGE), + nullptr); } void CommandService::AddObserver(Observer* observer) { @@ -858,7 +850,7 @@ bool CommandService::GetExtensionActionCommand( QueryType query_type, Command* command, bool* active, - ExtensionCommandType action_type) const { + Command::Type action_type) const { const ExtensionSet& extensions = ExtensionRegistry::Get(profile_)->enabled_extensions(); const Extension* extension = extensions.GetByID(extension_id); @@ -869,13 +861,13 @@ bool CommandService::GetExtensionActionCommand( const Command* requested_command = NULL; switch (action_type) { - case BROWSER_ACTION: + case Command::Type::kBrowserAction: requested_command = CommandsInfo::GetBrowserActionCommand(extension); break; - case PAGE_ACTION: + case Command::Type::kPageAction: requested_command = CommandsInfo::GetPageActionCommand(extension); break; - case NAMED: + case Command::Type::kNamed: NOTREACHED(); return false; } diff --git a/chromium/chrome/browser/extensions/api/commands/command_service.h b/chromium/chrome/browser/extensions/api/commands/command_service.h index ebff2853236..378922ae5fe 100644 --- a/chromium/chrome/browser/extensions/api/commands/command_service.h +++ b/chromium/chrome/browser/extensions/api/commands/command_service.h @@ -68,13 +68,6 @@ class CommandService : public BrowserContextKeyedAPI, ANY_SCOPE, // All commands, regardless of scope (used when querying). }; - // An enum specifying the types of commands that can be used by an extension. - enum ExtensionCommandType { - NAMED, - BROWSER_ACTION, - PAGE_ACTION - }; - class Observer { public: // Called when an extension command is added. @@ -186,8 +179,7 @@ class CommandService : public BrowserContextKeyedAPI, // assigns the type to *|command_type| if non-null. bool GetSuggestedExtensionCommand(const std::string& extension_id, const ui::Accelerator& accelerator, - Command* command, - ExtensionCommandType* command_type) const; + Command* command) const; // Returns true if |extension| requests to override the bookmark shortcut key // and should be allowed to do so. @@ -265,7 +257,7 @@ class CommandService : public BrowserContextKeyedAPI, QueryType query_type, Command* command, bool* active, - ExtensionCommandType action_type) const; + Command::Type type) const; // A weak pointer to the profile we are associated with. Not owned by us. Profile* profile_; diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc index f77080331df..13790f2f9eb 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.cc @@ -33,7 +33,7 @@ #include "extensions/common/permissions/permissions_data.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_constants.h" -#include "services/network/public/interfaces/network_service.mojom.h" +#include "services/network/public/mojom/network_service.mojom.h" using content::BrowserThread; @@ -87,7 +87,8 @@ network::mojom::CookieManager* ParseStoreCookieManager( // GetCurrentBrowser() already takes into account incognito settings. // TODO(rdevlin.cronin): Relying on the current execution context is // almost never the right answer; clean this up. - Browser* current_browser = function->GetCurrentBrowser(); + Browser* current_browser = + ChromeExtensionFunctionDetails(function).GetCurrentBrowser(); if (!current_browser) { function->SetError(keys::kNoCookieStoreFoundError); return nullptr; diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h index b5a5ad044f1..991fb466e53 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_api.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_api.h @@ -22,7 +22,7 @@ #include "extensions/browser/browser_context_keyed_api_factory.h" #include "extensions/browser/event_router.h" #include "net/cookies/canonical_cookie.h" -#include "services/network/public/interfaces/cookie_manager.mojom.h" +#include "services/network/public/mojom/cookie_manager.mojom.h" #include "url/gurl.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h index ec287ffbce9..0b21eb056db 100644 --- a/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h +++ b/chromium/chrome/browser/extensions/api/cookies/cookies_helpers.h @@ -18,7 +18,7 @@ #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_options.h" -#include "services/network/public/interfaces/cookie_manager.mojom.h" +#include "services/network/public/mojom/cookie_manager.mojom.h" class Browser; class Profile; 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 6e99d232a39..6b95797c994 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 @@ -10,20 +10,18 @@ #include "base/memory/ptr_util.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" -#include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/permissions/permission_request.h" +#include "chrome/browser/permissions/attestation_permission_request.h" #include "chrome/browser/permissions/permission_request_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" -#include "chrome/grit/generated_resources.h" #include "components/pref_registry/pref_registry_syncable.h" #include "components/prefs/pref_service.h" #include "crypto/sha2.h" #include "extensions/common/error_utils.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" -#include "ui/base/l10n/l10n_util.h" +#include "url/origin.h" namespace { @@ -57,52 +55,6 @@ bool ContainsAppIdByHash(const base::ListValue& list, return false; } -// AttestationPermissionRequest is a delegate class that provides information -// and callbacks to the PermissionRequestManager. -// -// PermissionRequestManager has a reference to this object and so this object -// must outlive it. Since attestation requests are never canceled, -// PermissionRequestManager guarentees that |RequestFinished| will always, -// eventually, be called. This object uses that fact to delete itself during -// |RequestFinished| and thus owns itself. -class AttestationPermissionRequest : public PermissionRequest { - public: - AttestationPermissionRequest(const GURL& app_id, - base::OnceCallback<void(bool)> callback) - : app_id_(app_id), callback_(std::move(callback)) {} - - PermissionRequest::IconId GetIconId() const override { - return kUsbSecurityKeyIcon; - } - - base::string16 GetMessageTextFragment() const override { - return l10n_util::GetStringUTF16( - IDS_SECURITY_KEY_ATTESTATION_PERMISSION_FRAGMENT); - } - GURL GetOrigin() const override { return app_id_; } - void PermissionGranted() override { std::move(callback_).Run(true); } - void PermissionDenied() override { std::move(callback_).Run(false); } - void Cancelled() override { std::move(callback_).Run(false); } - - void RequestFinished() override { - if (callback_) - std::move(callback_).Run(false); - delete this; - } - - PermissionRequestType GetPermissionRequestType() const override { - return PermissionRequestType::PERMISSION_SECURITY_KEY_ATTESTATION; - } - - private: - ~AttestationPermissionRequest() override = default; - - const GURL app_id_; - base::OnceCallback<void(bool)> callback_; - - DISALLOW_COPY_AND_ASSIGN(AttestationPermissionRequest); -}; - } // namespace namespace extensions { @@ -241,8 +193,9 @@ CryptotokenPrivateCanAppIdGetAttestationFunction::Run() { } // The created AttestationPermissionRequest deletes itself once complete. - permission_request_manager->AddRequest(new AttestationPermissionRequest( - app_id_url, + const url::Origin origin(url::Origin::Create(app_id_url)); + permission_request_manager->AddRequest(NewAttestationPermissionRequest( + origin, base::BindOnce( &CryptotokenPrivateCanAppIdGetAttestationFunction::Complete, this))); return RespondLater(); 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 a88874bd102..3c912638980 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 @@ -69,8 +69,7 @@ class CryptoTokenPrivateApiTest : public extensions::ExtensionApiUnittest { args->AppendString(app_id); if (!extension_function_test_utils::RunFunction( - function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)) { + function.get(), std::move(args), browser(), api_test_utils::NONE)) { return false; } @@ -89,7 +88,7 @@ class CryptoTokenPrivateApiTest : public extensions::ExtensionApiUnittest { if (!extension_function_test_utils::RunFunction( function.get(), base::ListValue::From(std::move(args)), browser(), - extension_function_test_utils::NONE)) { + api_test_utils::NONE)) { return false; } @@ -214,8 +213,7 @@ class CryptoTokenPermissionTest : public ExtensionApiUnittest { auto args_list = base::ListValue::From(std::move(args)); extension_function_test_utils::RunFunction( - function.get(), std::move(args_list), browser(), - extension_function_test_utils::NONE); + function.get(), std::move(args_list), browser(), api_test_utils::NONE); return GetSingleBooleanResult(function.get(), out_result); } 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 c7d8abdb460..c2bb77b851e 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 @@ -78,7 +78,8 @@ DashboardPrivateShowPermissionPromptForDelegatedInstallFunction::Run() { if (!icon_url.is_empty()) { loader_factory = content::BrowserContext::GetDefaultStoragePartition(browser_context()) - ->GetURLLoaderFactoryForBrowserProcess(); + ->GetURLLoaderFactoryForBrowserProcess() + .get(); } scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper( diff --git a/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc b/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc index 615ee3a7276..92fae3336a0 100644 --- a/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc +++ b/chromium/chrome/browser/extensions/api/debugger/debugger_apitest.cc @@ -126,20 +126,20 @@ testing::AssertionResult DebuggerApiTest::RunAttachFunctionOnTarget( attach_function->set_extension(extension_.get()); std::string actual_error; - if (!RunFunction(attach_function.get(), - base::StringPrintf("[%s, \"1.1\"]", debuggee_target.c_str()), - browser(), - extension_function_test_utils::NONE)) { + if (!extension_function_test_utils::RunFunction( + attach_function.get(), + base::StringPrintf("[%s, \"1.1\"]", debuggee_target.c_str()), + browser(), api_test_utils::NONE)) { actual_error = attach_function->GetError(); } else { // Clean up and detach. scoped_refptr<DebuggerDetachFunction> detach_function = new DebuggerDetachFunction(); detach_function->set_extension(extension_.get()); - if (!RunFunction(detach_function.get(), - base::StringPrintf("[%s]", debuggee_target.c_str()), - browser(), - extension_function_test_utils::NONE)) { + if (!extension_function_test_utils::RunFunction( + detach_function.get(), + base::StringPrintf("[%s]", debuggee_target.c_str()), browser(), + api_test_utils::NONE)) { return testing::AssertionFailure() << "Could not detach from " << debuggee_target << " : " << detach_function->GetError(); } @@ -212,10 +212,10 @@ IN_PROC_BROWSER_TEST_F(DebuggerApiTest, InfoBar) { // Attach should create infobars in both browsers. attach_function = new DebuggerAttachFunction(); attach_function->set_extension(extension()); - ASSERT_TRUE( - RunFunction(attach_function.get(), - base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id), - browser(), extension_function_test_utils::NONE)); + ASSERT_TRUE(extension_function_test_utils::RunFunction( + attach_function.get(), + base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id), browser(), + api_test_utils::NONE)); EXPECT_EQ(1u, service1->infobar_count()); EXPECT_EQ(1u, service2->infobar_count()); EXPECT_EQ(1u, service3->infobar_count()); @@ -223,10 +223,10 @@ IN_PROC_BROWSER_TEST_F(DebuggerApiTest, InfoBar) { // Second attach should not create infobars. attach_function = new DebuggerAttachFunction(); attach_function->set_extension(extension()); - ASSERT_TRUE( - RunFunction(attach_function.get(), - base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id2), - browser(), extension_function_test_utils::NONE)); + ASSERT_TRUE(extension_function_test_utils::RunFunction( + attach_function.get(), + base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id2), browser(), + api_test_utils::NONE)); EXPECT_EQ(1u, service1->infobar_count()); EXPECT_EQ(1u, service2->infobar_count()); EXPECT_EQ(1u, service3->infobar_count()); @@ -234,9 +234,9 @@ IN_PROC_BROWSER_TEST_F(DebuggerApiTest, InfoBar) { // Detach from one of the tabs should not remove infobars. detach_function = new DebuggerDetachFunction(); detach_function->set_extension(extension()); - ASSERT_TRUE(RunFunction(detach_function.get(), - base::StringPrintf("[{\"tabId\": %d}]", tab_id2), - browser(), extension_function_test_utils::NONE)); + ASSERT_TRUE(extension_function_test_utils::RunFunction( + detach_function.get(), base::StringPrintf("[{\"tabId\": %d}]", tab_id2), + browser(), api_test_utils::NONE)); EXPECT_EQ(1u, service1->infobar_count()); EXPECT_EQ(1u, service2->infobar_count()); EXPECT_EQ(1u, service3->infobar_count()); @@ -244,9 +244,9 @@ IN_PROC_BROWSER_TEST_F(DebuggerApiTest, InfoBar) { // Detach should remove all infobars. detach_function = new DebuggerDetachFunction(); detach_function->set_extension(extension()); - ASSERT_TRUE(RunFunction(detach_function.get(), - base::StringPrintf("[{\"tabId\": %d}]", tab_id), - browser(), extension_function_test_utils::NONE)); + ASSERT_TRUE(extension_function_test_utils::RunFunction( + detach_function.get(), base::StringPrintf("[{\"tabId\": %d}]", tab_id), + browser(), api_test_utils::NONE)); EXPECT_EQ(0u, service1->infobar_count()); EXPECT_EQ(0u, service2->infobar_count()); EXPECT_EQ(0u, service3->infobar_count()); @@ -254,10 +254,10 @@ IN_PROC_BROWSER_TEST_F(DebuggerApiTest, InfoBar) { // Attach again. attach_function = new DebuggerAttachFunction(); attach_function->set_extension(extension()); - ASSERT_TRUE( - RunFunction(attach_function.get(), - base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id), - browser(), extension_function_test_utils::NONE)); + ASSERT_TRUE(extension_function_test_utils::RunFunction( + attach_function.get(), + base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id), browser(), + api_test_utils::NONE)); EXPECT_EQ(1u, service1->infobar_count()); EXPECT_EQ(1u, service2->infobar_count()); EXPECT_EQ(1u, service3->infobar_count()); @@ -275,17 +275,17 @@ IN_PROC_BROWSER_TEST_F(DebuggerApiTest, InfoBar) { detach_function = new DebuggerDetachFunction(); detach_function->set_extension(extension()); // Cannot detach again. - ASSERT_FALSE(RunFunction(detach_function.get(), - base::StringPrintf("[{\"tabId\": %d}]", tab_id), - browser(), extension_function_test_utils::NONE)); + ASSERT_FALSE(extension_function_test_utils::RunFunction( + detach_function.get(), base::StringPrintf("[{\"tabId\": %d}]", tab_id), + browser(), api_test_utils::NONE)); // And again... attach_function = new DebuggerAttachFunction(); attach_function->set_extension(extension()); - ASSERT_TRUE( - RunFunction(attach_function.get(), - base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id), - browser(), extension_function_test_utils::NONE)); + ASSERT_TRUE(extension_function_test_utils::RunFunction( + attach_function.get(), + base::StringPrintf("[{\"tabId\": %d}, \"1.1\"]", tab_id), browser(), + api_test_utils::NONE)); EXPECT_EQ(1u, service1->infobar_count()); EXPECT_EQ(1u, service2->infobar_count()); EXPECT_EQ(1u, service3->infobar_count()); @@ -305,9 +305,9 @@ IN_PROC_BROWSER_TEST_F(DebuggerApiTest, InfoBar) { // Detach should remove the remaining infobar. detach_function = new DebuggerDetachFunction(); detach_function->set_extension(extension()); - ASSERT_TRUE(RunFunction(detach_function.get(), - base::StringPrintf("[{\"tabId\": %d}]", tab_id), - browser(), extension_function_test_utils::NONE)); + ASSERT_TRUE(extension_function_test_utils::RunFunction( + detach_function.get(), base::StringPrintf("[{\"tabId\": %d}]", tab_id), + browser(), api_test_utils::NONE)); EXPECT_EQ(0u, service1->infobar_count()); } diff --git a/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar.cc b/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar.cc index 6b187e3a93c..41b8582f234 100644 --- a/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar.cc +++ b/chromium/chrome/browser/extensions/api/debugger/extension_dev_tools_infobar.cc @@ -26,7 +26,6 @@ class ExtensionDevToolsInfoBarDelegate : public ConfirmInfoBarDelegate { ~ExtensionDevToolsInfoBarDelegate() override; // ConfirmInfoBarDelegate: - Type GetInfoBarType() const override; infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; bool ShouldExpire(const NavigationDetails& details) const override; void InfoBarDismissed() override; @@ -50,11 +49,6 @@ ExtensionDevToolsInfoBarDelegate::ExtensionDevToolsInfoBarDelegate( ExtensionDevToolsInfoBarDelegate::~ExtensionDevToolsInfoBarDelegate() {} -infobars::InfoBarDelegate::Type -ExtensionDevToolsInfoBarDelegate::GetInfoBarType() const { - return WARNING_TYPE; -} - infobars::InfoBarDelegate::InfoBarIdentifier ExtensionDevToolsInfoBarDelegate::GetIdentifier() const { return EXTENSION_DEV_TOOLS_INFOBAR_DELEGATE; diff --git a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc index 21fe2a8754a..24f23e44620 100644 --- a/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative/declarative_apitest.cc @@ -13,7 +13,6 @@ #include "base/strings/utf_string_conversions.h" #include "base/test/thread_test_helper.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" @@ -24,6 +23,7 @@ #include "extensions/browser/extension_prefs.h" #include "extensions/common/extension.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_extension_dir.h" using content::BrowserThread; 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 d9059dbe147..53906599f6b 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 @@ -44,7 +44,8 @@ const int kRulesRegistryID = RulesRegistryService::kDefaultRulesRegistryID; class RulesRegistryWithCacheTest : public testing::Test { public: RulesRegistryWithCacheTest() - : cache_delegate_(/*log_storage_init_delay=*/false), + : cache_delegate_(RulesCacheDelegate::Type::kPersistent, + /*log_storage_init_delay=*/false), registry_(new TestRulesRegistry(profile(), /*event_name=*/"", content::BrowserThread::UI, @@ -233,8 +234,8 @@ TEST_F(RulesRegistryWithCacheTest, DeclarativeRulesStored) { const std::string rules_stored_key( RulesCacheDelegate::GetRulesStoredKey( event_name, profile()->IsOffTheRecord())); - std::unique_ptr<RulesCacheDelegate> cache_delegate( - new RulesCacheDelegate(false)); + auto cache_delegate = std::make_unique<RulesCacheDelegate>( + RulesCacheDelegate::Type::kPersistent, false); scoped_refptr<RulesRegistry> registry( new TestRulesRegistry(profile(), event_name, content::BrowserThread::UI, cache_delegate.get(), kRulesRegistryID)); @@ -252,9 +253,11 @@ TEST_F(RulesRegistryWithCacheTest, DeclarativeRulesStored) { EXPECT_TRUE(cache_delegate->GetDeclarativeRulesStored(extension1_->id())); // 2. Test writing behavior. - std::unique_ptr<base::ListValue> value(new base::ListValue); - value->AppendBoolean(true); - cache_delegate->WriteToStorage(extension1_->id(), std::move(value)); + { + base::Value value(base::Value::Type::LIST); + value.GetList().push_back(base::Value(true)); + cache_delegate->UpdateRules(extension1_->id(), std::move(value)); + } EXPECT_TRUE(cache_delegate->GetDeclarativeRulesStored(extension1_->id())); content::RunAllTasksUntilIdle(); TestingValueStore* store = env_.GetExtensionSystem()->value_store(); @@ -262,17 +265,21 @@ TEST_F(RulesRegistryWithCacheTest, DeclarativeRulesStored) { EXPECT_EQ(1, store->write_count()); int write_count = store->write_count(); - value.reset(new base::ListValue); - cache_delegate->WriteToStorage(extension1_->id(), std::move(value)); - EXPECT_FALSE(cache_delegate->GetDeclarativeRulesStored(extension1_->id())); + { + base::Value value = base::Value(base::Value::Type::LIST); + cache_delegate->UpdateRules(extension1_->id(), std::move(value)); + EXPECT_FALSE(cache_delegate->GetDeclarativeRulesStored(extension1_->id())); + } content::RunAllTasksUntilIdle(); // No rules currently, but previously there were, so we expect a write. EXPECT_EQ(write_count + 1, store->write_count()); write_count = store->write_count(); - value.reset(new base::ListValue); - cache_delegate->WriteToStorage(extension1_->id(), std::move(value)); - EXPECT_FALSE(cache_delegate->GetDeclarativeRulesStored(extension1_->id())); + { + base::Value value = base::Value(base::Value::Type::LIST); + cache_delegate->UpdateRules(extension1_->id(), std::move(value)); + EXPECT_FALSE(cache_delegate->GetDeclarativeRulesStored(extension1_->id())); + } content::RunAllTasksUntilIdle(); EXPECT_EQ(write_count, store->write_count()); @@ -291,6 +298,18 @@ TEST_F(RulesRegistryWithCacheTest, DeclarativeRulesStored) { EXPECT_EQ(read_count + 1, store->read_count()); } +TEST_F(RulesRegistryWithCacheTest, EphemeralCacheIsEphemeral) { + auto cache_delegate = std::make_unique<RulesCacheDelegate>( + RulesCacheDelegate::Type::kEphemeral, false); + base::Value value(base::Value::Type::LIST); + value.GetList().push_back(base::Value(true)); + cache_delegate->UpdateRules(extension1_->id(), std::move(value)); + content::RunAllTasksUntilIdle(); + TestingValueStore* store = env_.GetExtensionSystem()->value_store(); + ASSERT_TRUE(store); + EXPECT_EQ(0, store->write_count()); +} + // Test that each registry has its own "are some rules stored" flag. TEST_F(RulesRegistryWithCacheTest, RulesStoredFlagMultipleRegistries) { ExtensionPrefs* extension_prefs = env_.GetExtensionPrefs(); @@ -303,14 +322,14 @@ TEST_F(RulesRegistryWithCacheTest, RulesStoredFlagMultipleRegistries) { const std::string rules_stored_key2( RulesCacheDelegate::GetRulesStoredKey( event_name2, profile()->IsOffTheRecord())); - std::unique_ptr<RulesCacheDelegate> cache_delegate1( - new RulesCacheDelegate(false)); + auto cache_delegate1 = std::make_unique<RulesCacheDelegate>( + RulesCacheDelegate::Type::kPersistent, false); scoped_refptr<RulesRegistry> registry1( new TestRulesRegistry(profile(), event_name1, content::BrowserThread::UI, cache_delegate1.get(), kRulesRegistryID)); - std::unique_ptr<RulesCacheDelegate> cache_delegate2( - new RulesCacheDelegate(false)); + auto cache_delegate2 = std::make_unique<RulesCacheDelegate>( + RulesCacheDelegate::Type::kPersistent, false); scoped_refptr<RulesRegistry> registry2( new TestRulesRegistry(profile(), event_name2, content::BrowserThread::UI, cache_delegate2.get(), kRulesRegistryID)); @@ -351,8 +370,8 @@ TEST_F(RulesRegistryWithCacheTest, RulesPreservedAcrossRestart) { env_.GetExtensionSystem()->SetReady(); // 2. First run, adding a rule for the extension. - std::unique_ptr<RulesCacheDelegate> cache_delegate( - new RulesCacheDelegate(false)); + auto cache_delegate = std::make_unique<RulesCacheDelegate>( + RulesCacheDelegate::Type::kPersistent, false); scoped_refptr<TestRulesRegistry> registry( new TestRulesRegistry(profile(), "testEvent", content::BrowserThread::UI, cache_delegate.get(), kRulesRegistryID)); @@ -364,7 +383,8 @@ TEST_F(RulesRegistryWithCacheTest, RulesPreservedAcrossRestart) { EXPECT_EQ(1, GetNumberOfRules(extension1_->id(), registry.get())); // 3. Restart the TestRulesRegistry and see the rule still there. - cache_delegate.reset(new RulesCacheDelegate(false)); + cache_delegate = std::make_unique<RulesCacheDelegate>( + RulesCacheDelegate::Type::kPersistent, false); registry = new TestRulesRegistry(profile(), "testEvent", content::BrowserThread::UI, cache_delegate.get(), kRulesRegistryID); diff --git a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc index 88a0d6da572..4f2b43e14fd 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/declarative_content_apitest.cc @@ -16,7 +16,6 @@ #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" @@ -26,6 +25,7 @@ #include "extensions/browser/extension_system.h" #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_extension_dir.h" #include "testing/gmock/include/gmock/gmock.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc index ffa680bbcd2..42c42b760ce 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/request_content_script_apitest.cc @@ -6,12 +6,12 @@ #include "base/macros.h" #include "base/strings/stringprintf.h" #include "chrome/browser/extensions/extension_browsertest.h" -#include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_extension_dir.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc b/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc index 5a91c7c006c..72a79c3313d 100644 --- a/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_content/set_icon_apitest.cc @@ -5,11 +5,11 @@ #include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_tab_util.h" -#include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "components/version_info/version_info.h" #include "extensions/common/features/feature_channel.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_extension_dir.h" #include "ui/gfx/image/image.h" namespace extensions { 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 3ae612a992c..7efb7086919 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 @@ -41,10 +41,13 @@ #include "extensions/browser/extension_util.h" #include "extensions/common/api/declarative_net_request/constants.h" #include "extensions/common/api/declarative_net_request/test_utils.h" +#include "extensions/common/constants.h" #include "extensions/common/extension_id.h" +#include "extensions/common/url_pattern.h" #include "net/dns/mock_host_resolver.h" #include "net/test/spawned_test_server/spawned_test_server.h" #include "net/test/test_data_directory.h" +#include "services/network/public/cpp/features.h" namespace extensions { namespace declarative_net_request { @@ -154,8 +157,11 @@ class DeclarativeNetRequestBrowserTest // Loads an extension with the given declarative |rules| in the given // |directory|. Generates a fatal failure if the extension failed to load. + // |hosts| specifies the host permissions, the extensions should + // have. void LoadExtensionWithRules(const std::vector<TestRule>& rules, - const std::string& directory) { + const std::string& directory, + const std::vector<std::string>& hosts) { base::ScopedAllowBlockingForTesting scoped_allow_blocking; base::HistogramTester tester; @@ -163,12 +169,13 @@ class DeclarativeNetRequestBrowserTest EXPECT_TRUE(base::CreateDirectory(extension_dir)); WriteManifestAndRuleset(extension_dir, kJSONRulesetFilepath, - kJSONRulesFilename, rules); + kJSONRulesFilename, rules, hosts); const Extension* extension = nullptr; switch (GetParam()) { case ExtensionLoadType::PACKED: - extension = InstallExtension(extension_dir, 1 /* expected_change */); + extension = InstallExtensionWithPermissionsGranted( + extension_dir, 1 /* expected_change */); break; case ExtensionLoadType::UNPACKED: extension = LoadExtension(extension_dir); @@ -196,7 +203,8 @@ class DeclarativeNetRequestBrowserTest } void LoadExtensionWithRules(const std::vector<TestRule>& rules) { - LoadExtensionWithRules(rules, "test_extension"); + LoadExtensionWithRules(rules, "test_extension", + {URLPattern::kAllUrlsPattern}); } private: @@ -635,8 +643,10 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, rules_2.push_back(rule); } - ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules_1, "extension_1")); - ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules(rules_2, "extension_2")); + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules_1, "extension_1", {URLPattern::kAllUrlsPattern})); + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules_2, "extension_2", {URLPattern::kAllUrlsPattern})); struct { std::string host; @@ -688,7 +698,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, // url. for (size_t i = 1; i <= kNumExtensions; ++i) { rule.action->redirect_url = redirect_url_for_extension_number(i); - ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules({rule}, std::to_string(i))); + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + {rule}, std::to_string(i), {URLPattern::kAllUrlsPattern})); // Verify that the install time of this extension is greater than the last // extension. @@ -906,7 +917,8 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, } } -// Ensure extensions can't intercept chrome:// urls. +// Ensure extensions can't intercept chrome:// urls, even after explicitly +// requesting access to <all_urls>. IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, ChromeURLS) { // Have the extension block all chrome:// urls. TestRule rule = CreateGenericRule(); @@ -976,7 +988,12 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); - EXPECT_TRUE(script_monitor.GetAndResetRequestSeen(false)); + + // NOTE: When the Network Service is enabled, the RulesetMatcher will not see + // network requests if no rulesets are active. + EXPECT_TRUE( + base::FeatureList::IsEnabled(network::features::kNetworkService) || + script_monitor.GetAndResetRequestSeen(false)); // Another request to |url| should not cause a network request for // script.js since it will be served by the renderer's in-memory @@ -1010,7 +1027,9 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, RendererCacheCleared) { ui_test_utils::NavigateToURL(browser(), url); EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); EXPECT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); - EXPECT_TRUE(script_monitor.GetAndResetRequestSeen(false)); + EXPECT_TRUE( + base::FeatureList::IsEnabled(network::features::kNetworkService) || + script_monitor.GetAndResetRequestSeen(false)); // Clear RulesetManager's observer. content::BrowserThread::PostTask( @@ -1049,6 +1068,164 @@ IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); } +// Ensure that an extension can intercept its own resources, but not those of +// other extensions. +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestBrowserTest, + InterceptExtensionScheme) { + // Load two extensions. One blocks all urls, and the other blocks urls with + // "google.com" as a substring. + std::vector<TestRule> rules_1; + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = std::string("*"); + rules_1.push_back(rule); + + std::vector<TestRule> rules_2; + rule = CreateGenericRule(); + rule.condition->url_filter = std::string("google.com"); + rules_2.push_back(rule); + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules_1, "extension_1", {URLPattern::kAllUrlsPattern})); + const std::string extension_id_1 = last_loaded_extension_id(); + + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithRules( + rules_2, "extension_2", {URLPattern::kAllUrlsPattern})); + const std::string extension_id_2 = last_loaded_extension_id(); + + auto get_manifest_url = [](const std::string& extension_id) { + return GURL(base::StringPrintf("%s://%s/manifest.json", + extensions::kExtensionScheme, + extension_id.c_str())); + }; + + // Extension 1 should be able to block the request to its own + // manifest.json. + ui_test_utils::NavigateToURL(browser(), get_manifest_url(extension_id_1)); + GURL final_url = web_contents()->GetLastCommittedURL(); + EXPECT_EQ(content::PAGE_TYPE_ERROR, GetPageType()); + + // But it should not be able to intercept requests to the second extensions's + // resources, even with "<all_urls>" host permissions. + ui_test_utils::NavigateToURL(browser(), get_manifest_url(extension_id_2)); + EXPECT_EQ(content::PAGE_TYPE_NORMAL, GetPageType()); +} + +// Test fixture to verify that host permissions for the request url and the +// request initiator are properly checked. Loads an example.com url with four +// sub-frames named frame_[1..4] from hosts frame_[1..4].com. The initiator for +// these frames will be example.com. Loads an extension set to block all sub- +// frames. Verifies that the correct frames are blocked depending on the host +// permissions for the extension. +class DeclarativeNetRequestHostPermissionsBrowserTest + : public DeclarativeNetRequestBrowserTest { + public: + DeclarativeNetRequestHostPermissionsBrowserTest() {} + + protected: + struct FrameLoadResult { + std::string child_frame_name; + bool expect_frame_loaded; + }; + + void LoadExtensionWithHostPermissions(const std::vector<std::string>& hosts) { + std::vector<TestRule> rules; + + // Block all sub-frame requests. + TestRule rule = CreateGenericRule(); + rule.condition->url_filter = std::string("*"); + rule.condition->resource_types = std::vector<std::string>({"sub_frame"}); + rules.push_back(rule); + + ASSERT_NO_FATAL_FAILURE( + LoadExtensionWithRules(rules, "test_extension", hosts)); + } + + void RunTests(const std::vector<FrameLoadResult>& expected_results) { + ASSERT_EQ(4u, expected_results.size()); + + GURL url = embedded_test_server()->GetURL("example.com", + "/page_with_four_frames.html"); + ui_test_utils::NavigateToURL(browser(), url); + ASSERT_TRUE(WasFrameWithScriptLoaded(GetMainFrame())); + + for (const auto& frame_result : expected_results) { + SCOPED_TRACE(base::StringPrintf("Testing child frame named %s", + frame_result.child_frame_name.c_str())); + + content::RenderFrameHost* child = + GetFrameByName(frame_result.child_frame_name); + EXPECT_TRUE(child); + EXPECT_EQ(frame_result.expect_frame_loaded, + WasFrameWithScriptLoaded(child)); + } + } + + std::string GetMatchPatternForDomain(const std::string& domain) const { + return "*://*." + domain + ".com/*"; + } + + private: + DISALLOW_COPY_AND_ASSIGN(DeclarativeNetRequestHostPermissionsBrowserTest); +}; + +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest, + AllURLs1) { + // All frames should be blocked since the extension has access to all hosts. + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithHostPermissions({"<all_urls>"})); + RunTests({{"frame_1", false}, + {"frame_2", false}, + {"frame_3", false}, + {"frame_4", false}}); +} + +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest, + AllURLs2) { + // All frames should be blocked since the extension has access to all hosts. + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithHostPermissions({"*://*/*"})); + RunTests({{"frame_1", false}, + {"frame_2", false}, + {"frame_3", false}, + {"frame_4", false}}); +} + +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest, + NoPermissions) { + // The extension has no host permissions. No frames should be blocked. + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithHostPermissions({})); + RunTests({{"frame_1", true}, + {"frame_2", true}, + {"frame_3", true}, + {"frame_4", true}}); +} + +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest, + SubframesWithNoInitiatorPermissions) { + // The extension has access to requests to "frame_1.com" and "frame_2.com", + // but not the initiator of those requests (example.com). No frames should be + // blocked. + ASSERT_NO_FATAL_FAILURE( + LoadExtensionWithHostPermissions({GetMatchPatternForDomain("frame_1"), + GetMatchPatternForDomain("frame_2")})); + RunTests({{"frame_1", true}, + {"frame_2", true}, + {"frame_3", true}, + {"frame_4", true}}); +} + +IN_PROC_BROWSER_TEST_P(DeclarativeNetRequestHostPermissionsBrowserTest, + SubframesWithInitiatorPermission) { + // The extension has access to requests to "frame_1.com" and "frame_4.com", + // and also the initiator of those requests (example.com). Hence |frame_1| and + // |frame_4| should be blocked. + ASSERT_NO_FATAL_FAILURE(LoadExtensionWithHostPermissions( + {GetMatchPatternForDomain("frame_1"), GetMatchPatternForDomain("frame_4"), + GetMatchPatternForDomain("example")})); + RunTests({{"frame_1", false}, + {"frame_2", true}, + {"frame_3", true}, + {"frame_4", false}}); +} + // Fixture to test the "resourceTypes" and "excludedResourceTypes" fields of a // declarative rule condition. class DeclarativeNetRequestResourceTypeBrowserTest @@ -1220,6 +1397,10 @@ INSTANTIATE_TEST_CASE_P(, ExtensionLoadType::UNPACKED)); INSTANTIATE_TEST_CASE_P(, + DeclarativeNetRequestHostPermissionsBrowserTest, + ::testing::Values(ExtensionLoadType::PACKED, + ExtensionLoadType::UNPACKED)); +INSTANTIATE_TEST_CASE_P(, DeclarativeNetRequestResourceTypeBrowserTest, ::testing::Values(ExtensionLoadType::PACKED, ExtensionLoadType::UNPACKED)); 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 e8b3fffeca9..0e5c1f20ae2 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 @@ -24,6 +24,7 @@ #include "extensions/common/file_util.h" #include "extensions/common/install_warning.h" #include "extensions/common/manifest_constants.h" +#include "extensions/common/url_pattern.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { @@ -129,10 +130,12 @@ class RuleIndexingTest : public DNRTestBase { if (rules_value_) { WriteManifestAndRuleset(extension_dir_, kJSONRulesetFilepath, - kJSONRulesFilename, *rules_value_); + kJSONRulesFilename, *rules_value_, + {URLPattern::kAllUrlsPattern}); } else { WriteManifestAndRuleset(extension_dir_, kJSONRulesetFilepath, - kJSONRulesFilename, rules_list_); + kJSONRulesFilename, rules_list_, + {URLPattern::kAllUrlsPattern}); } // Overwrite the JSON rules file with some invalid json. 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 eec02539495..932c7add27b 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 @@ -6,6 +6,7 @@ #include "base/files/file_path.h" #include "base/files/file_util.h" +#include "base/optional.h" #include "chrome/browser/extensions/api/declarative_net_request/dnr_test_base.h" #include "chrome/browser/extensions/chrome_test_extension_loader.h" #include "chrome/browser/extensions/extension_util.h" @@ -19,10 +20,12 @@ #include "extensions/common/api/declarative_net_request/constants.h" #include "extensions/common/api/declarative_net_request/test_utils.h" #include "extensions/common/file_util.h" +#include "extensions/common/url_pattern.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" +#include "url/origin.h" namespace extensions { namespace declarative_net_request { @@ -40,14 +43,16 @@ class RulesetManagerTest : public DNRTestBase { // Helper to create a ruleset matcher instance for the given |rules|. void CreateMatcherForRules(const std::vector<TestRule>& rules, const std::string& extension_dirname, - std::unique_ptr<RulesetMatcher>* matcher) { + std::unique_ptr<RulesetMatcher>* matcher, + const std::vector<std::string>& host_permissions = + {URLPattern::kAllUrlsPattern}) { base::FilePath extension_dir = temp_dir().GetPath().AppendASCII(extension_dirname); // Create extension directory. ASSERT_TRUE(base::CreateDirectory(extension_dir)); WriteManifestAndRuleset(extension_dir, kJSONRulesetFilepath, - kJSONRulesFilename, rules); + kJSONRulesFilename, rules, host_permissions); last_loaded_extension_ = CreateExtensionLoader()->LoadExtension(extension_dir); @@ -229,23 +234,46 @@ TEST_P(RulesetManagerTest, Redirect) { rule.action->redirect_url = std::string("http://google.com"); std::unique_ptr<RulesetMatcher> matcher; ASSERT_NO_FATAL_FAILURE( - CreateMatcherForRules({rule}, "test_extension", &matcher)); + CreateMatcherForRules({rule}, "test_extension", &matcher, + {"*://example.com/*", "*://abc.com/*"})); manager->AddRuleset(last_loaded_extension()->id(), std::move(matcher)); + // Create a request to "example.com" with an empty initiator. It should be + // redirected to "google.com". const bool is_incognito_context = false; - GURL redirect_url; + GURL redirect_url1; std::unique_ptr<net::URLRequest> request = GetRequestForURL("http://example.com"); + request->set_initiator(base::nullopt); extensions::WebRequestInfo request_info1(request.get()); EXPECT_TRUE(manager->ShouldRedirectRequest( - request_info1, is_incognito_context, &redirect_url)); - EXPECT_EQ(GURL("http://google.com"), redirect_url); + request_info1, is_incognito_context, &redirect_url1)); + EXPECT_EQ(GURL("http://google.com"), redirect_url1); + + // Change the initiator to "xyz.com". It should not be redirected since we + // don't have host permissions to the request initiator. + GURL redirect_url2; + request->set_initiator(url::Origin::Create(GURL("http://xyz.com"))); + extensions::WebRequestInfo request_info2(request.get()); + EXPECT_FALSE(manager->ShouldRedirectRequest( + request_info2, is_incognito_context, &redirect_url2)); + + // Change the initiator to "abc.com". It should be redirected since we have + // the required host permissions. + GURL redirect_url3; + request->set_initiator(url::Origin::Create(GURL("http://abc.com"))); + extensions::WebRequestInfo request_info3(request.get()); + EXPECT_TRUE(manager->ShouldRedirectRequest( + request_info3, is_incognito_context, &redirect_url3)); + EXPECT_EQ(GURL("http://google.com"), redirect_url3); // Ensure web-socket requests are not redirected. + GURL redirect_url4; request = GetRequestForURL("ws://example.com"); - extensions::WebRequestInfo request_info2(request.get()); + request->set_initiator(base::nullopt); + extensions::WebRequestInfo request_info4(request.get()); EXPECT_FALSE(manager->ShouldRedirectRequest( - request_info2, is_incognito_context, &redirect_url)); + request_info4, is_incognito_context, &redirect_url4)); } INSTANTIATE_TEST_CASE_P(, diff --git a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_matcher_unittest.cc b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_matcher_unittest.cc index 700f504554a..90209860ec6 100644 --- a/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_matcher_unittest.cc +++ b/chromium/chrome/browser/extensions/api/declarative_net_request/ruleset_matcher_unittest.cc @@ -18,6 +18,7 @@ #include "extensions/common/api/declarative_net_request/constants.h" #include "extensions/common/api/declarative_net_request/test_utils.h" #include "extensions/common/file_util.h" +#include "extensions/common/url_pattern.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" @@ -44,7 +45,8 @@ class RulesetMatcherTest : public DNRTestBase { // Create extension directory. ASSERT_TRUE(base::CreateDirectory(extension_dir)); WriteManifestAndRuleset(extension_dir, kJSONRulesetFilepath, - kJSONRulesFilename, rules); + kJSONRulesFilename, rules, + {URLPattern::kAllUrlsPattern}); extension_ = CreateExtensionLoader()->LoadExtension(extension_dir); ASSERT_TRUE(extension_); diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc index 8bfaa066863..c6c75b48921 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_apitest.cc @@ -44,6 +44,8 @@ struct TestFlags { bool picker_deleted; }; +// TODO(crbug.com/805145): Uncomment this when test is re-enabled. +#if 0 DesktopMediaID MakeFakeWebContentsMediaId(bool audio_share) { DesktopMediaID media_id(DesktopMediaID::TYPE_WEB_CONTENTS, DesktopMediaID::kNullId, @@ -52,6 +54,7 @@ DesktopMediaID MakeFakeWebContentsMediaId(bool audio_share) { media_id.audio_share = audio_share; return media_id; } +#endif class FakeDesktopMediaPicker : public DesktopMediaPicker { public: @@ -63,13 +66,8 @@ class FakeDesktopMediaPicker : public DesktopMediaPicker { ~FakeDesktopMediaPicker() override { expectation_->picker_deleted = true; } // DesktopMediaPicker interface. - void Show(content::WebContents* web_contents, - gfx::NativeWindow context, - gfx::NativeWindow parent, - const base::string16& app_name, - const base::string16& target_name, + void Show(const DesktopMediaPicker::Params& params, std::vector<std::unique_ptr<DesktopMediaList>> source_lists, - bool request_audio, const DoneCallback& done_callback) override { bool show_screens = false; bool show_windows = false; @@ -93,7 +91,8 @@ class FakeDesktopMediaPicker : public DesktopMediaPicker { EXPECT_EQ(expectation_->expect_screens, show_screens); EXPECT_EQ(expectation_->expect_windows, show_windows); EXPECT_EQ(expectation_->expect_tabs, show_tabs); - EXPECT_EQ(expectation_->expect_audio, request_audio); + EXPECT_EQ(expectation_->expect_audio, params.request_audio); + EXPECT_EQ(params.modality, ui::ModalType::MODAL_TYPE_CHILD); if (!expectation_->cancelled) { // Post a task to call the callback asynchronously. @@ -187,7 +186,8 @@ class DesktopCaptureApiTest : public ExtensionApiTest { // Flaky on Windows: http://crbug.com/301887 // Fails on Chrome OS: http://crbug.com/718512 -#if defined(OS_WIN) || defined(OS_CHROMEOS) +// Flaky on macOS: http://crbug.com/804897 +#if defined(OS_WIN) || defined(OS_CHROMEOS) || defined(OS_MACOSX) #define MAYBE_ChooseDesktopMedia DISABLED_ChooseDesktopMedia #else #define MAYBE_ChooseDesktopMedia ChooseDesktopMedia @@ -196,52 +196,55 @@ IN_PROC_BROWSER_TEST_F(DesktopCaptureApiTest, MAYBE_ChooseDesktopMedia) { // Each element in the following array corresponds to one test in // chrome/test/data/extensions/api_test/desktop_capture/test.js . TestFlags test_flags[] = { - // pickerUiCanceled() - {true, true, false, false, DesktopMediaID()}, - // chooseMedia() - {true, true, false, false, - DesktopMediaID(DesktopMediaID::TYPE_SCREEN, DesktopMediaID::kNullId)}, - // screensOnly() - {true, false, false, false, DesktopMediaID()}, - // WindowsOnly() - {false, true, false, false, DesktopMediaID()}, - // tabOnly() - {false, false, true, false, DesktopMediaID()}, - // audioShareNoApproval() - {true, true, true, true, - DesktopMediaID(DesktopMediaID::TYPE_WEB_CONTENTS, 123, false)}, - // audioShareApproval() - {true, true, true, true, - DesktopMediaID(DesktopMediaID::TYPE_WEB_CONTENTS, 123, true)}, - // chooseMediaAndGetStream() - {true, true, false, false, - DesktopMediaID(DesktopMediaID::TYPE_SCREEN, - webrtc::kFullDesktopScreenId)}, - // chooseMediaAndTryGetStreamWithInvalidId() - {true, true, false, false, - DesktopMediaID(DesktopMediaID::TYPE_SCREEN, - webrtc::kFullDesktopScreenId)}, - // cancelDialog() - {true, true, false, false, DesktopMediaID(), true}, + // pickerUiCanceled() + {true, true, false, false, DesktopMediaID()}, + // chooseMedia() + {true, true, false, false, + DesktopMediaID(DesktopMediaID::TYPE_SCREEN, DesktopMediaID::kNullId)}, + // screensOnly() + {true, false, false, false, DesktopMediaID()}, + // WindowsOnly() + {false, true, false, false, DesktopMediaID()}, + // tabOnly() + {false, false, true, false, DesktopMediaID()}, + // audioShareNoApproval() + {true, true, true, true, + DesktopMediaID(DesktopMediaID::TYPE_WEB_CONTENTS, 123, false)}, + // audioShareApproval() + {true, true, true, true, + DesktopMediaID(DesktopMediaID::TYPE_WEB_CONTENTS, 123, true)}, + // chooseMediaAndGetStream() + {true, true, false, false, + DesktopMediaID(DesktopMediaID::TYPE_SCREEN, webrtc::kFullDesktopScreenId)}, + // chooseMediaAndTryGetStreamWithInvalidId() + {true, true, false, false, + DesktopMediaID(DesktopMediaID::TYPE_SCREEN, webrtc::kFullDesktopScreenId)}, + // cancelDialog() + {true, true, false, false, DesktopMediaID(), true}, +// TODO(crbug.com/805145): Test fails; invalid device IDs being generated. +#if 0 // tabShareWithAudioGetStream() {false, false, true, true, MakeFakeWebContentsMediaId(true)}, - // windowShareWithAudioGetStream() - {false, true, false, true, - DesktopMediaID(DesktopMediaID::TYPE_WINDOW, DesktopMediaID::kFakeId, - true)}, - // screenShareWithAudioGetStream() - {true, false, false, true, - DesktopMediaID(DesktopMediaID::TYPE_SCREEN, webrtc::kFullDesktopScreenId, - true)}, +#endif + // windowShareWithAudioGetStream() + {false, true, false, true, + DesktopMediaID(DesktopMediaID::TYPE_WINDOW, DesktopMediaID::kFakeId, + true)}, + // screenShareWithAudioGetStream() + {true, false, false, true, + DesktopMediaID(DesktopMediaID::TYPE_SCREEN, webrtc::kFullDesktopScreenId, + true)}, +// TODO(crbug.com/805145): Test fails; invalid device IDs being generated. +#if 0 // tabShareWithoutAudioGetStream() {false, false, true, true, MakeFakeWebContentsMediaId(false)}, - // windowShareWithoutAudioGetStream() - {false, true, false, true, - DesktopMediaID(DesktopMediaID::TYPE_WINDOW, DesktopMediaID::kFakeId)}, - // screenShareWithoutAudioGetStream() - {true, false, false, true, - DesktopMediaID(DesktopMediaID::TYPE_SCREEN, - webrtc::kFullDesktopScreenId)}, +#endif + // windowShareWithoutAudioGetStream() + {false, true, false, true, + DesktopMediaID(DesktopMediaID::TYPE_WINDOW, DesktopMediaID::kFakeId)}, + // screenShareWithoutAudioGetStream() + {true, false, false, true, + DesktopMediaID(DesktopMediaID::TYPE_SCREEN, webrtc::kFullDesktopScreenId)}, }; picker_factory_.SetTestFlags(test_flags, arraysize(test_flags)); ASSERT_TRUE(RunExtensionTest("desktop_capture")) << message_; diff --git a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc index 392ecad385f..4e8b6cc9ffa 100644 --- a/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc +++ b/chromium/chrome/browser/extensions/api/desktop_capture/desktop_capture_base.cc @@ -26,8 +26,6 @@ #include "content/public/browser/web_contents.h" #include "extensions/common/manifest.h" #include "extensions/common/switches.h" -#include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" -#include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" #include "ui/base/l10n/l10n_util.h" using extensions::api::desktop_capture::ChooseDesktopMedia::Results::Options; @@ -123,8 +121,7 @@ bool DesktopCaptureChooseDesktopMediaFunctionBase::Execute( #else // !defined(OS_CHROMEOS) screen_list = std::make_unique<NativeDesktopMediaList>( content::DesktopMediaID::TYPE_SCREEN, - webrtc::DesktopCapturer::CreateScreenCapturer( - content::CreateDesktopCaptureOptions())); + content::desktop_capture::CreateScreenCapturer()); #endif // !defined(OS_CHROMEOS) } have_screen_list = true; @@ -151,8 +148,7 @@ bool DesktopCaptureChooseDesktopMediaFunctionBase::Execute( // used on multiple threads concurrently. window_list = std::make_unique<NativeDesktopMediaList>( content::DesktopMediaID::TYPE_WINDOW, - webrtc::DesktopCapturer::CreateWindowCapturer( - content::CreateDesktopCaptureOptions())); + content::desktop_capture::CreateWindowCapturer()); #endif // !defined(OS_CHROMEOS) } have_window_list = true; @@ -208,10 +204,14 @@ bool DesktopCaptureChooseDesktopMediaFunctionBase::Execute( DesktopMediaPicker::DoneCallback callback = base::Bind( &DesktopCaptureChooseDesktopMediaFunctionBase::OnPickerDialogResults, this); - - picker_->Show(web_contents, parent_window, parent_window, - base::UTF8ToUTF16(GetCallerDisplayName()), target_name, - std::move(source_lists), request_audio, callback); + DesktopMediaPicker::Params picker_params; + picker_params.web_contents = web_contents; + picker_params.context = parent_window; + picker_params.parent = parent_window; + picker_params.app_name = base::UTF8ToUTF16(GetCallerDisplayName()); + picker_params.target_name = target_name; + picker_params.request_audio = request_audio; + picker_->Show(picker_params, std::move(source_lists), callback); origin_ = origin; return true; } 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 dfa6519275e..0cdd23224d9 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 @@ -21,7 +21,6 @@ #include "chrome/browser/extensions/extension_service_test_with_install.h" #include "chrome/browser/extensions/extension_util.h" #include "chrome/browser/extensions/scripting_permissions_modifier.h" -#include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/extensions/test_extension_system.h" #include "chrome/browser/extensions/unpacked_installer.h" #include "chrome/browser/ui/browser.h" @@ -55,6 +54,7 @@ #include "extensions/common/feature_switch.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/value_builder.h" +#include "extensions/test/test_extension_dir.h" using testing::Return; using testing::_; @@ -156,8 +156,7 @@ bool DeveloperPrivateApiUnitTest::RunFunction( const scoped_refptr<UIThreadExtensionFunction>& function, const base::ListValue& args) { return extension_function_test_utils::RunFunction( - function.get(), args.CreateDeepCopy(), browser(), - extension_function_test_utils::NONE); + function.get(), args.CreateDeepCopy(), browser(), api_test_utils::NONE); } const Extension* DeveloperPrivateApiUnitTest::LoadUnpackedExtension() { 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 a8a5fa6acda..aaa7aced75d 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 @@ -73,7 +73,7 @@ IN_PROC_BROWSER_TEST_F(DeveloperPrivateApiTest, InspectAppWindowView) { base::StringPrintf("[{\"renderViewId\": %d, \"renderProcessId\": %d}]", window_view->render_view_id, window_view->render_process_id), - browser(), extension_function_test_utils::NONE); + browser(), api_test_utils::NONE); // Verify that dev tools opened. std::list<AppWindow*> app_windows = @@ -119,7 +119,7 @@ IN_PROC_BROWSER_TEST_F(DeveloperPrivateApiTest, InspectEmbeddedOptionsPage) { function.get(), base::StringPrintf("[{\"renderViewId\": %d, \"renderProcessId\": %d}]", view.render_view_id, view.render_process_id), - browser(), extension_function_test_utils::NONE); + browser(), api_test_utils::NONE); // Verify that dev tools opened. content::RenderFrameHost* rfh = content::RenderFrameHost::FromID( diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc index 53965e17392..15b031d88d6 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator.cc @@ -262,7 +262,7 @@ void ExtensionInfoGenerator::CreateExtensionInfo( if (pending_image_loads_ == 0) { // Don't call the callback re-entrantly. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(callback, base::Passed(&list_))); + FROM_HERE, base::BindOnce(callback, std::move(list_))); list_.clear(); } else { callback_ = callback; @@ -300,7 +300,7 @@ void ExtensionInfoGenerator::CreateExtensionsInfo( if (pending_image_loads_ == 0) { // Don't call the callback re-entrantly. base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, base::BindOnce(callback, base::Passed(&list_))); + FROM_HERE, base::BindOnce(callback, std::move(list_))); list_.clear(); } else { callback_ = callback; diff --git a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc index 8eb8f33bd4f..72c1bc79a1a 100644 --- a/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc +++ b/chromium/chrome/browser/extensions/api/developer_private/extension_info_generator_unittest.cc @@ -82,7 +82,7 @@ class ExtensionInfoGeneratorUnitTest : public ExtensionServiceTestBase { EXPECT_EQ(1u, list.size()); if (!list.empty()) info_out->reset(new developer::ExtensionInfo(std::move(list[0]))); - base::ResetAndReturn(&quit_closure_).Run(); + std::move(quit_closure_).Run(); } std::unique_ptr<developer::ExtensionInfo> GenerateExtensionInfo( @@ -103,7 +103,7 @@ class ExtensionInfoGeneratorUnitTest : public ExtensionServiceTestBase { void OnInfosGenerated(ExtensionInfoGenerator::ExtensionInfoList* out, ExtensionInfoGenerator::ExtensionInfoList list) { *out = std::move(list); - base::ResetAndReturn(&quit_closure_).Run(); + std::move(quit_closure_).Run(); } ExtensionInfoGenerator::ExtensionInfoList GenerateExtensionsInfo() { @@ -204,7 +204,7 @@ class ExtensionInfoGeneratorUnitTest : public ExtensionServiceTestBase { } private: - base::Closure quit_closure_; + base::OnceClosure quit_closure_; DISALLOW_COPY_AND_ASSIGN(ExtensionInfoGeneratorUnitTest); }; 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 e77604705a4..bb87fbcbfbd 100644 --- a/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc +++ b/chromium/chrome/browser/extensions/api/device_permissions_manager_unittest.cc @@ -18,7 +18,7 @@ #include "extensions/browser/api/hid/hid_device_manager.h" #include "extensions/browser/extension_prefs.h" #include "extensions/common/extension.h" -#include "services/device/public/interfaces/hid.mojom.h" +#include "services/device/public/mojom/hid.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" diff --git a/chromium/chrome/browser/extensions/api/dial/dial_api.cc b/chromium/chrome/browser/extensions/api/dial/dial_api.cc index a5922dc9eed..04c086f843e 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_api.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_api.cc @@ -255,7 +255,7 @@ void DialFetchDeviceDescriptionFunction::MaybeStartFetch(const GURL& url) { } device_description_fetcher_ = std::make_unique<DeviceDescriptionFetcher>( - url, Profile::FromBrowserContext(browser_context())->GetRequestContext(), + url, base::BindOnce(&DialFetchDeviceDescriptionFunction::OnFetchComplete, this), base::BindOnce(&DialFetchDeviceDescriptionFunction::OnFetchError, this)); diff --git a/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc b/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc index 67049da9bf4..1a8413a289c 100644 --- a/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc +++ b/chromium/chrome/browser/extensions/api/dial/dial_apitest.cc @@ -9,6 +9,8 @@ #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/media/router/discovery/dial/dial_registry.h" +#include "chrome/browser/media/router/providers/cast/dual_media_sink_service.h" +#include "chrome/browser/media/router/test/noop_dual_media_sink_service.h" #include "extensions/common/switches.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" @@ -33,6 +35,13 @@ class DialAPITest : public ExtensionApiTest { extensions::switches::kWhitelistedExtensionID, "ddchlicdkolnonkihahngkmmmjnjlkkf"); } + + void SetUp() override { + // Stub out DualMediaSinkService so it does not interfere with the test. + media_router::DualMediaSinkService::SetInstanceForTest( + new media_router::NoopDualMediaSinkService()); + ExtensionApiTest::SetUp(); + } }; } // namespace diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc index e4fd3fb38a5..5e70f755f52 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.cc @@ -31,9 +31,9 @@ #include "base/strings/string16.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" #include "base/task/cancelable_task_tracker.h" #include "base/threading/thread_task_runner_handle.h" +#include "base/time/time_to_iso8601.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" @@ -56,11 +56,10 @@ #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/common/extensions/api/downloads.h" +#include "components/download/public/common/download_interrupt_reasons.h" +#include "components/download/public/common/download_item.h" +#include "components/download/public/common/download_url_parameters.h" #include "components/web_modal/web_contents_modal_dialog_manager.h" -#include "content/public/browser/download_interrupt_reasons.h" -#include "content/public/browser/download_item.h" -#include "content/public/browser/download_save_info.h" -#include "content/public/browser/download_url_parameters.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" @@ -87,7 +86,7 @@ using content::BrowserContext; using content::BrowserThread; -using content::DownloadItem; +using download::DownloadItem; using content::DownloadManager; namespace download_extension_errors { @@ -193,7 +192,7 @@ const char* const kDangerStrings[] = { kDangerHost, kDangerUnwanted }; -static_assert(arraysize(kDangerStrings) == content::DOWNLOAD_DANGER_TYPE_MAX, +static_assert(arraysize(kDangerStrings) == download::DOWNLOAD_DANGER_TYPE_MAX, "kDangerStrings should have DOWNLOAD_DANGER_TYPE_MAX elements"); // Note: Any change to the state strings, should be accompanied by a @@ -204,38 +203,40 @@ const char* const kStateStrings[] = { kStateInterrupted, kStateInterrupted, }; -static_assert(arraysize(kStateStrings) == DownloadItem::MAX_DOWNLOAD_STATE, +static_assert(arraysize(kStateStrings) == + download::DownloadItem::MAX_DOWNLOAD_STATE, "kStateStrings should have MAX_DOWNLOAD_STATE elements"); -const char* DangerString(content::DownloadDangerType danger) { +const char* DangerString(download::DownloadDangerType danger) { DCHECK(danger >= 0); - DCHECK(danger < static_cast<content::DownloadDangerType>( - arraysize(kDangerStrings))); - if (danger < 0 || danger >= static_cast<content::DownloadDangerType>( - arraysize(kDangerStrings))) + DCHECK(danger < + static_cast<download::DownloadDangerType>(arraysize(kDangerStrings))); + if (danger < 0 || danger >= static_cast<download::DownloadDangerType>( + arraysize(kDangerStrings))) return ""; return kDangerStrings[danger]; } -content::DownloadDangerType DangerEnumFromString(const std::string& danger) { +download::DownloadDangerType DangerEnumFromString(const std::string& danger) { for (size_t i = 0; i < arraysize(kDangerStrings); ++i) { if (danger == kDangerStrings[i]) - return static_cast<content::DownloadDangerType>(i); + return static_cast<download::DownloadDangerType>(i); } - return content::DOWNLOAD_DANGER_TYPE_MAX; + return download::DOWNLOAD_DANGER_TYPE_MAX; } -const char* StateString(DownloadItem::DownloadState state) { +const char* StateString(download::DownloadItem::DownloadState state) { DCHECK(state >= 0); - DCHECK(state < static_cast<DownloadItem::DownloadState>( - arraysize(kStateStrings))); - if (state < 0 || state >= static_cast<DownloadItem::DownloadState>( - arraysize(kStateStrings))) + DCHECK(state < static_cast<download::DownloadItem::DownloadState>( + arraysize(kStateStrings))); + if (state < 0 || state >= static_cast<download::DownloadItem::DownloadState>( + arraysize(kStateStrings))) return ""; return kStateStrings[state]; } -DownloadItem::DownloadState StateEnumFromString(const std::string& state) { +download::DownloadItem::DownloadState StateEnumFromString( + const std::string& state) { for (size_t i = 0; i < arraysize(kStateStrings); ++i) { if ((kStateStrings[i] != NULL) && (state == kStateStrings[i])) return static_cast<DownloadItem::DownloadState>(i); @@ -243,15 +244,6 @@ DownloadItem::DownloadState StateEnumFromString(const std::string& state) { return DownloadItem::MAX_DOWNLOAD_STATE; } -std::string TimeToISO8601(const base::Time& t) { - base::Time::Exploded exploded; - t.UTCExplode(&exploded); - return base::StringPrintf( - "%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", exploded.year, exploded.month, - exploded.day_of_month, exploded.hour, exploded.minute, exploded.second, - exploded.millisecond); -} - std::unique_ptr<base::DictionaryValue> DownloadItemToJSON( DownloadItem* download_item, content::BrowserContext* browser_context) { @@ -273,25 +265,27 @@ std::unique_ptr<base::DictionaryValue> DownloadItemToJSON( json->SetBoolean(kCanResumeKey, download_item->CanResume()); json->SetBoolean(kPausedKey, download_item->IsPaused()); json->SetString(kMimeKey, download_item->GetMimeType()); - json->SetString(kStartTimeKey, TimeToISO8601(download_item->GetStartTime())); + json->SetString(kStartTimeKey, + base::TimeToISO8601(download_item->GetStartTime())); json->SetDouble(kBytesReceivedKey, download_item->GetReceivedBytes()); json->SetDouble(kTotalBytesKey, download_item->GetTotalBytes()); json->SetBoolean(kIncognitoKey, browser_context->IsOffTheRecord()); if (download_item->GetState() == DownloadItem::INTERRUPTED) { - json->SetString(kErrorKey, - content::DownloadInterruptReasonToString( - download_item->GetLastReason())); + json->SetString(kErrorKey, download::DownloadInterruptReasonToString( + download_item->GetLastReason())); } else if (download_item->GetState() == DownloadItem::CANCELLED) { json->SetString(kErrorKey, - content::DownloadInterruptReasonToString( - content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED)); + download::DownloadInterruptReasonToString( + download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED)); } if (!download_item->GetEndTime().is_null()) - json->SetString(kEndTimeKey, TimeToISO8601(download_item->GetEndTime())); + json->SetString(kEndTimeKey, + base::TimeToISO8601(download_item->GetEndTime())); base::TimeDelta time_remaining; if (download_item->TimeRemaining(&time_remaining)) { base::Time now = base::Time::Now(); - json->SetString(kEstimatedEndTimeKey, TimeToISO8601(now + time_remaining)); + json->SetString(kEstimatedEndTimeKey, + base::TimeToISO8601(now + time_remaining)); } DownloadedByExtension* by_ext = DownloadedByExtension::Get(download_item); if (by_ext) { @@ -563,9 +557,9 @@ void RunDownloadQuery( std::string danger_string = downloads::ToString(query_in.danger); if (!danger_string.empty()) { - content::DownloadDangerType danger_type = DangerEnumFromString( - danger_string); - if (danger_type == content::DOWNLOAD_DANGER_TYPE_MAX) { + download::DownloadDangerType danger_type = + DangerEnumFromString(danger_string); + if (danger_type == download::DOWNLOAD_DANGER_TYPE_MAX) { *error = errors::kInvalidDangerType; return; } @@ -768,11 +762,10 @@ class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data { // Returns false if this |extension_id| was not expected or if this // |extension_id| has already reported. The caller is responsible for // validating |filename|. - bool DeterminerCallback( - Profile* profile, - const std::string& extension_id, - const base::FilePath& filename, - downloads::FilenameConflictAction conflict_action) { + bool DeterminerCallback(content::BrowserContext* browser_context, + const std::string& extension_id, + const base::FilePath& filename, + downloads::FilenameConflictAction conflict_action) { DCHECK_CURRENTLY_ON(BrowserThread::UI); bool found_info = false; for (size_t index = 0; index < determiners_.size(); ++index) { @@ -800,7 +793,7 @@ class ExtensionDownloadsEventRouterData : public base::SupportsUserData::Data { &determined_conflict_action_, &warnings); if (!warnings.empty()) - WarningService::NotifyWarningsOnUI(profile, warnings); + WarningService::NotifyWarningsOnUI(browser_context, warnings); if (winner_extension_id == determiners_[index].extension_id) determiner_ = determiners_[index]; } @@ -965,18 +958,16 @@ const char DownloadedByExtension::kKey[] = "DownloadItem DownloadedByExtension"; DownloadedByExtension* DownloadedByExtension::Get( - content::DownloadItem* item) { + download::DownloadItem* item) { base::SupportsUserData::Data* data = item->GetUserData(kKey); return (data == NULL) ? NULL : static_cast<DownloadedByExtension*>(data); } -DownloadedByExtension::DownloadedByExtension( - content::DownloadItem* item, - const std::string& id, - const std::string& name) - : id_(id), - name_(name) { +DownloadedByExtension::DownloadedByExtension(download::DownloadItem* item, + const std::string& id, + const std::string& name) + : id_(id), name_(name) { item->SetUserData(kKey, base::WrapUnique(this)); } @@ -1030,8 +1021,8 @@ bool DownloadsDownloadFunction::RunAsync() { } } })"); - std::unique_ptr<content::DownloadUrlParameters> download_params( - new content::DownloadUrlParameters( + std::unique_ptr<download::DownloadUrlParameters> download_params( + new download::DownloadUrlParameters( download_url, render_frame_host()->GetProcess()->GetID(), render_frame_host()->GetRenderViewHost()->GetRoutingID(), render_frame_host()->GetRoutingID(), @@ -1082,14 +1073,18 @@ bool DownloadsDownloadFunction::RunAsync() { downloads::ToString(options.method); if (!method_string.empty()) download_params->set_method(method_string); - if (options.body.get()) - download_params->set_post_body(*options.body); + if (options.body.get()) { + download_params->set_post_body( + network::ResourceRequestBody::CreateFromBytes(options.body->data(), + options.body->size())); + } + download_params->set_callback(base::Bind( &DownloadsDownloadFunction::OnStarted, this, creator_suggested_filename, options.conflict_action)); // Prevent login prompts for 401/407 responses. download_params->set_do_not_prompt_for_login(true); - download_params->set_download_source(content::DownloadSource::EXTENSION_API); + download_params->set_download_source(download::DownloadSource::EXTENSION_API); DownloadManager* manager = BrowserContext::GetDownloadManager( current_profile); @@ -1102,11 +1097,11 @@ void DownloadsDownloadFunction::OnStarted( const base::FilePath& creator_suggested_filename, downloads::FilenameConflictAction creator_conflict_action, DownloadItem* item, - content::DownloadInterruptReason interrupt_reason) { + download::DownloadInterruptReason interrupt_reason) { DCHECK_CURRENTLY_ON(BrowserThread::UI); VLOG(1) << __func__ << " " << item << " " << interrupt_reason; if (item) { - DCHECK_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason); + DCHECK_EQ(download::DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason); SetResult(std::make_unique<base::Value>(static_cast<int>(item->GetId()))); if (!creator_suggested_filename.empty() || (creator_conflict_action != @@ -1124,8 +1119,8 @@ void DownloadsDownloadFunction::OnStarted( new DownloadedByExtension(item, extension()->id(), extension()->name()); item->UpdateObservers(); } else { - DCHECK_NE(content::DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason); - error_ = content::DownloadInterruptReasonToString(interrupt_reason); + DCHECK_NE(download::DOWNLOAD_INTERRUPT_REASON_NONE, interrupt_reason); + error_ = download::DownloadInterruptReasonToString(interrupt_reason); } SendResponse(error_.empty()); } @@ -1562,10 +1557,8 @@ bool DownloadsGetFileIconFunction::RunAsync() { float scale = 1.0; content::WebContents* web_contents = dispatcher()->GetVisibleWebContents(); - if (web_contents) { - scale = ui::GetScaleFactorForNativeView( - web_contents->GetRenderWidgetHostView()->GetNativeView()); - } + if (web_contents && web_contents->GetRenderWidgetHostView()) + scale = web_contents->GetRenderWidgetHostView()->GetDeviceScaleFactor(); EXTENSION_FUNCTION_VALIDATE(icon_extractor_->ExtractIconURLForPath( download_item->GetTargetFilePath(), scale, @@ -1733,7 +1726,7 @@ void ExtensionDownloadsEventRouter::DetermineFilenameInternal( } bool ExtensionDownloadsEventRouter::DetermineFilename( - Profile* profile, + content::BrowserContext* browser_context, bool include_incognito, const std::string& ext_id, int download_id, @@ -1742,7 +1735,8 @@ bool ExtensionDownloadsEventRouter::DetermineFilename( std::string* error) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RecordApiFunctions(DOWNLOADS_FUNCTION_DETERMINE_FILENAME); - DownloadItem* item = GetDownload(profile, include_incognito, download_id); + DownloadItem* item = + GetDownload(browser_context, include_incognito, download_id); ExtensionDownloadsEventRouterData* data = item ? ExtensionDownloadsEventRouterData::Get(item) : NULL; // maxListeners=1 in downloads.idl and suggestCallback in @@ -1766,8 +1760,8 @@ bool ExtensionDownloadsEventRouter::DetermineFilename( base::FilePath()); // If the invalid filename check is moved to before DeterminerCallback(), then // it will block forever waiting for this ext_id to report. - if (Fault(!data->DeterminerCallback( - profile, ext_id, filename, conflict_action), + if (Fault(!data->DeterminerCallback(browser_context, ext_id, filename, + conflict_action), errors::kUnexpectedDeterminer, error) || Fault((!const_filename.empty() && !valid_filename), errors::kInvalidFilename, error)) diff --git a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h index 084d39b0bc1..cd6e5759ce8 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api.h +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api.h @@ -69,9 +69,9 @@ namespace extensions { class DownloadedByExtension : public base::SupportsUserData::Data { public: - static DownloadedByExtension* Get(content::DownloadItem* item); + static DownloadedByExtension* Get(download::DownloadItem* item); - DownloadedByExtension(content::DownloadItem* item, + DownloadedByExtension(download::DownloadItem* item, const std::string& id, const std::string& name); @@ -100,8 +100,8 @@ class DownloadsDownloadFunction : public ChromeAsyncExtensionFunction { void OnStarted(const base::FilePath& creator_suggested_filename, extensions::api::downloads::FilenameConflictAction creator_conflict_action, - content::DownloadItem* item, - content::DownloadInterruptReason interrupt_reason); + download::DownloadItem* item, + download::DownloadInterruptReason interrupt_reason); DISALLOW_COPY_AND_ASSIGN(DownloadsDownloadFunction); }; @@ -330,7 +330,7 @@ class ExtensionDownloadsEventRouter // existing files, then |overwrite| will be true. Returns true on success, // false otherwise. static bool DetermineFilename( - Profile* profile, + content::BrowserContext* browser_context, bool include_incognito, const std::string& ext_id, int download_id, @@ -352,19 +352,18 @@ class ExtensionDownloadsEventRouter // an extension wants to change the target filename, then |change| will be // called with the new filename and a flag indicating whether the new file // should overwrite any old files of the same name. - void OnDeterminingFilename( - content::DownloadItem* item, - const base::FilePath& suggested_path, - const base::Closure& no_change, - const FilenameChangedCallback& change); + void OnDeterminingFilename(download::DownloadItem* item, + const base::FilePath& suggested_path, + const base::Closure& no_change, + const FilenameChangedCallback& change); // AllDownloadItemNotifier::Observer. void OnDownloadCreated(content::DownloadManager* manager, - content::DownloadItem* download_item) override; + download::DownloadItem* download_item) override; void OnDownloadUpdated(content::DownloadManager* manager, - content::DownloadItem* download_item) override; + download::DownloadItem* download_item) override; void OnDownloadRemoved(content::DownloadManager* manager, - content::DownloadItem* download_item) override; + download::DownloadItem* download_item) override; // extensions::EventRouter::Observer. void OnListenerRemoved(const extensions::EventListenerInfo& details) override; 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 ee607987815..618452122d6 100644 --- a/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/downloads/downloads_api_browsertest.cc @@ -26,28 +26,29 @@ #include "chrome/browser/download/download_file_icon_extractor.h" #include "chrome/browser/download/download_test_file_activity_observer.h" #include "chrome/browser/extensions/api/downloads/downloads_api.h" -#include "chrome/browser/extensions/browser_action_test_util.h" +#include "chrome/browser/extensions/api/downloads_internal/downloads_internal_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/net/url_request_mock_util.h" +#include "chrome/browser/platform_util_internal.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" +#include "chrome/browser/ui/extensions/browser_action_test_util.h" #include "chrome/common/extensions/api/downloads.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/download/public/common/download_item.h" #include "components/prefs/pref_service.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" -#include "content/public/browser/download_item.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_features.h" -#include "content/public/test/controllable_http_response.h" #include "content/public/test/download_test_observer.h" #include "content/public/test/test_download_http_response.h" #include "content/public/test/test_utils.h" @@ -55,6 +56,7 @@ #include "extensions/browser/notification_types.h" #include "net/base/data_url.h" #include "net/dns/mock_host_resolver.h" +#include "net/test/embedded_test_server/controllable_http_response.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "net/test/url_request/url_request_slow_download_job.h" #include "net/url_request/url_request.h" @@ -69,7 +71,7 @@ using content::BrowserContext; using content::BrowserThread; -using content::DownloadItem; +using download::DownloadItem; using content::DownloadManager; namespace errors = download_extension_errors; @@ -270,7 +272,7 @@ class DownloadExtensionTest : public ExtensionApiTest { // Danger type for the download. Only use DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS // and DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT. - content::DownloadDangerType danger_type; + download::DownloadDangerType danger_type; }; void LoadExtension(const char* name) { @@ -329,10 +331,12 @@ class DownloadExtensionTest : public ExtensionApiTest { DownloadTestFileActivityObserver observer(current_browser()->profile()); observer.EnableFileChooser(false); - first_download_ = std::make_unique<content::ControllableHttpResponse>( - embedded_test_server(), kFirstDownloadUrl); - second_download_ = std::make_unique<content::ControllableHttpResponse>( - embedded_test_server(), kSecondDownloadUrl); + first_download_ = + std::make_unique<net::test_server::ControllableHttpResponse>( + embedded_test_server(), kFirstDownloadUrl); + second_download_ = + std::make_unique<net::test_server::ControllableHttpResponse>( + embedded_test_server(), kSecondDownloadUrl); host_resolver()->AddRule("*", "127.0.0.1"); } @@ -354,10 +358,9 @@ class DownloadExtensionTest : public ExtensionApiTest { current_browser()->profile(), event_name, json_args); } - bool WaitForInterruption( - DownloadItem* item, - content::DownloadInterruptReason expected_error, - const std::string& on_created_event) { + bool WaitForInterruption(DownloadItem* item, + download::DownloadInterruptReason expected_error, + const std::string& on_created_event) { if (!WaitFor(downloads::OnCreated::kEventName, on_created_event)) return false; // Now, onCreated is always fired before interruption. @@ -370,7 +373,7 @@ class DownloadExtensionTest : public ExtensionApiTest { " \"previous\": \"in_progress\"," " \"current\": \"interrupted\"}}]", item->GetId(), - content::DownloadInterruptReasonToString(expected_error).c_str())); + download::DownloadInterruptReasonToString(expected_error).c_str())); } void ClearEvents() { @@ -426,7 +429,7 @@ class DownloadExtensionTest : public ExtensionApiTest { url_chain.push_back(GURL()); for (size_t i = 0; i < count; ++i) { DownloadItem* item = GetOnRecordManager()->CreateDownloadItem( - base::GenerateGUID(), content::DownloadItem::kInvalidId + 1 + i, + base::GenerateGUID(), download::DownloadItem::kInvalidId + 1 + i, downloads_directory().Append(history_info[i].filename), downloads_directory().Append(history_info[i].filename), url_chain, GURL(), GURL(), GURL(), GURL(), std::string(), @@ -440,9 +443,9 @@ class DownloadExtensionTest : public ExtensionApiTest { std::string(), // hash history_info[i].state, // state history_info[i].danger_type, - (history_info[i].state != content::DownloadItem::CANCELLED - ? content::DOWNLOAD_INTERRUPT_REASON_NONE - : content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED), + (history_info[i].state != download::DownloadItem::CANCELLED + ? download::DOWNLOAD_INTERRUPT_REASON_NONE + : download::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED), false, // opened current, // last_access_time false, std::vector<DownloadItem::ReceivedSlice>()); @@ -477,7 +480,7 @@ class DownloadExtensionTest : public ExtensionApiTest { } DownloadItem* CreateSlowTestDownload( - content::ControllableHttpResponse* response, + net::test_server::ControllableHttpResponse* response, const std::string& path) { if (!embedded_test_server()->Started()) StartEmbeddedTestServer(); @@ -515,7 +518,8 @@ class DownloadExtensionTest : public ExtensionApiTest { FinishSlowDownloads(second_download_.get()); } - void FinishSlowDownloads(content::ControllableHttpResponse* response) { + void FinishSlowDownloads( + net::test_server::ControllableHttpResponse* response) { std::unique_ptr<content::DownloadTestObserver> observer( CreateDownloadObserver(1)); response->Done(); @@ -547,10 +551,10 @@ class DownloadExtensionTest : public ExtensionApiTest { return result; } - extension_function_test_utils::RunFunctionFlags GetFlags() { - return current_browser()->profile()->IsOffTheRecord() ? - extension_function_test_utils::INCLUDE_INCOGNITO : - extension_function_test_utils::NONE; + api_test_utils::RunFunctionFlags GetFlags() { + return current_browser()->profile()->IsOffTheRecord() + ? api_test_utils::INCLUDE_INCOGNITO + : api_test_utils::NONE; } // extension_function_test_utils::RunFunction*() only uses browser for its @@ -619,8 +623,8 @@ class DownloadExtensionTest : public ExtensionApiTest { Browser* current_browser_; std::unique_ptr<DownloadsEventsListener> events_listener_; - std::unique_ptr<content::ControllableHttpResponse> first_download_; - std::unique_ptr<content::ControllableHttpResponse> second_download_; + std::unique_ptr<net::test_server::ControllableHttpResponse> first_download_; + std::unique_ptr<net::test_server::ControllableHttpResponse> second_download_; DISALLOW_COPY_AND_ASSIGN(DownloadExtensionTest); }; @@ -786,30 +790,30 @@ bool ItemIsInterrupted(DownloadItem* item) { return item->GetState() == DownloadItem::INTERRUPTED; } -content::DownloadInterruptReason InterruptReasonExtensionToContent( +download::DownloadInterruptReason InterruptReasonExtensionToComponent( downloads::InterruptReason error) { switch (error) { case downloads::INTERRUPT_REASON_NONE: - return content::DOWNLOAD_INTERRUPT_REASON_NONE; + return download::DOWNLOAD_INTERRUPT_REASON_NONE; #define INTERRUPT_REASON(name, value) \ case downloads::INTERRUPT_REASON_##name: \ - return content::DOWNLOAD_INTERRUPT_REASON_##name; -#include "content/public/browser/download_interrupt_reason_values.h" + return download::DOWNLOAD_INTERRUPT_REASON_##name; +#include "components/download/public/common/download_interrupt_reason_values.h" #undef INTERRUPT_REASON } NOTREACHED(); - return content::DOWNLOAD_INTERRUPT_REASON_NONE; + return download::DOWNLOAD_INTERRUPT_REASON_NONE; } downloads::InterruptReason InterruptReasonContentToExtension( - content::DownloadInterruptReason error) { + download::DownloadInterruptReason error) { switch (error) { - case content::DOWNLOAD_INTERRUPT_REASON_NONE: + case download::DOWNLOAD_INTERRUPT_REASON_NONE: return downloads::INTERRUPT_REASON_NONE; -#define INTERRUPT_REASON(name, value) \ - case content::DOWNLOAD_INTERRUPT_REASON_##name: \ +#define INTERRUPT_REASON(name, value) \ + case download::DOWNLOAD_INTERRUPT_REASON_##name: \ return downloads::INTERRUPT_REASON_##name; -#include "content/public/browser/download_interrupt_reason_values.h" +#include "components/download/public/common/download_interrupt_reason_values.h" #undef INTERRUPT_REASON } NOTREACHED(); @@ -1063,13 +1067,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_FileIcon_History) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("real.txt"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("fake.txt"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("real.txt"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("fake.txt"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector all_downloads; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &all_downloads)); @@ -1123,6 +1124,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadsShowDefaultFolderFunction) { + platform_util::internal::DisableShellOperationsForTesting(); ScopedCancellingItem item(CreateFirstSlowTestDownload()); ASSERT_TRUE(item.get()); @@ -1144,13 +1146,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchFilenameRegex) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("foobar"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("foobar"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector all_downloads; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &all_downloads)); @@ -1223,13 +1222,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchOrderBy) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &items)); @@ -1256,13 +1252,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchOrderByEmpty) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &items)); @@ -1293,13 +1286,10 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchDanger) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS } - }; + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}}; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), &items)); @@ -1379,15 +1369,12 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchPlural) { const HistoryDownloadInfo kHistoryInfo[] = { - { FILE_PATH_LITERAL("aaa"), - DownloadItem::CANCELLED, - content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }, - { FILE_PATH_LITERAL("zzz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT }, - { FILE_PATH_LITERAL("baz"), - DownloadItem::COMPLETE, - content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT }, + {FILE_PATH_LITERAL("aaa"), DownloadItem::CANCELLED, + download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS}, + {FILE_PATH_LITERAL("zzz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT}, + {FILE_PATH_LITERAL("baz"), DownloadItem::COMPLETE, + download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT}, }; DownloadManager::DownloadVector items; ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo), @@ -1767,7 +1754,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, EXPECT_EQ(GetExtensionURL(), item->GetSiteUrl().spec()); item->SimulateErrorForTesting( - content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED); + download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED); embedded_test_server_io_runner->PostTask(FROM_HERE, complete_callback); ASSERT_TRUE(WaitFor(downloads::OnChanged::kEventName, @@ -1991,7 +1978,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadItem* item = GetCurrentManager()->GetDownload(result_id); ASSERT_TRUE(item); ASSERT_TRUE(WaitForInterruption( - item, content::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST, + item, download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST, "[{\"state\": \"in_progress\"," " \"url\": \"javascript:document.write(\\\"hello\\\");\"}]")); @@ -2003,7 +1990,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, item = GetCurrentManager()->GetDownload(result_id); ASSERT_TRUE(item); ASSERT_TRUE(WaitForInterruption( - item, content::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST, + item, download::DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST, "[{\"state\": \"in_progress\"," " \"url\": \"javascript:return false;\"}]")); @@ -2015,7 +2002,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, item = GetCurrentManager()->GetDownload(result_id); ASSERT_TRUE(item); ASSERT_TRUE(WaitForInterruption( - item, content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, + item, download::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, "[{\"state\": \"in_progress\"," " \"url\": \"ftp://example.com/example.txt\"}]")); } @@ -2274,8 +2261,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, ASSERT_EQ(download_url, item->GetOriginalUrl().spec()); ASSERT_TRUE(WaitForInterruption( - item, - content::DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED, + item, download::DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED, base::StringPrintf("[{\"danger\": \"safe\"," " \"incognito\": false," " \"paused\": false," @@ -2367,8 +2353,7 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, ASSERT_EQ(download_url, item->GetOriginalUrl().spec()); ASSERT_TRUE(WaitForInterruption( - item, - content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, + item, download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, base::StringPrintf("[{\"danger\": \"safe\"," " \"incognito\": false," " \"bytesReceived\": 0.0," @@ -2509,16 +2494,14 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, ASSERT_EQ(download_url, item->GetOriginalUrl().spec()); ASSERT_TRUE(WaitForInterruption( - item, - content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, + item, download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, base::StringPrintf("[{\"danger\": \"safe\"," " \"incognito\": false," " \"mime\": \"\"," " \"paused\": false," " \"id\": %d," " \"url\": \"%s\"}]", - result_id, - download_url.c_str()))); + result_id, download_url.c_str()))); } // Test that downloadPostSuccess would fail if the resource requires the POST @@ -2552,16 +2535,14 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, ASSERT_EQ(download_url, item->GetOriginalUrl().spec()); ASSERT_TRUE(WaitForInterruption( - item, - content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, + item, download::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, base::StringPrintf("[{\"danger\": \"safe\"," " \"incognito\": false," " \"mime\": \"\"," " \"paused\": false," " \"id\": %d," " \"url\": \"%s\"}]", - result_id, - download_url.c_str()))); + result_id, download_url.c_str()))); } // Test that cancel()ing an in-progress download causes its state to transition @@ -2886,6 +2867,51 @@ IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, result_id))); } +// Tests downloadsInternal.determineFilename. +// Regression test for https://crbug.com/815362. +IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, + DownloadsInternalDetermineFilename) { + GoOnTheRecord(); + LoadExtension("downloads_split"); + AddFilenameDeterminer(); + ASSERT_TRUE(StartEmbeddedTestServer()); + std::string download_url = embedded_test_server()->GetURL("/slow?0").spec(); + + // Start downloading a file. + std::unique_ptr<base::Value> result(RunFunctionAndReturnResult( + new DownloadsDownloadFunction(), + base::StringPrintf(R"([{"url": "%s"}])", download_url.c_str()))); + ASSERT_TRUE(result.get()); + int result_id = result->GetInt(); + DownloadItem* item = GetCurrentManager()->GetDownload(result_id); + ASSERT_TRUE(item); + ScopedCancellingItem canceller(item); + ASSERT_EQ(download_url, item->GetOriginalUrl().spec()); + + // Wait for the onCreated and onDeterminingFilename events. + ASSERT_TRUE(WaitFor(downloads::OnCreated::kEventName, + base::StringPrintf(R"([{ + "danger": "safe", + "incognito": false, + "id": %d, + "mime": "text/plain", + "paused": false, + "url": "%s" + }])", + result_id, download_url.c_str()))); + ASSERT_TRUE( + WaitFor(downloads::OnDeterminingFilename::kEventName, + base::StringPrintf( + R"([{"id": %d, "filename": "slow.txt"}])", result_id))); + ASSERT_TRUE(item->GetTargetFilePath().empty()); + ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState()); + + std::unique_ptr<base::Value> determine_result(RunFunctionAndReturnResult( + new DownloadsInternalDetermineFilenameFunction(), + base::StringPrintf(R"([%d, "", "uniquify"])", result_id))); + EXPECT_FALSE(determine_result.get()); // No return value. +} + IN_PROC_BROWSER_TEST_F( DownloadExtensionTest, DownloadExtensionTest_OnDeterminingFilename_DangerousOverride) { @@ -4315,14 +4341,14 @@ IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DownloadsApiTest) { TEST(DownloadInterruptReasonEnumsSynced, DownloadInterruptReasonEnumsSynced) { -#define INTERRUPT_REASON(name, value) \ - EXPECT_EQ(InterruptReasonContentToExtension( \ - content::DOWNLOAD_INTERRUPT_REASON_##name), \ - downloads::INTERRUPT_REASON_##name); \ - EXPECT_EQ( \ - InterruptReasonExtensionToContent(downloads::INTERRUPT_REASON_##name), \ - content::DOWNLOAD_INTERRUPT_REASON_##name); -#include "content/public/browser/download_interrupt_reason_values.h" // NOLINT +#define INTERRUPT_REASON(name, value) \ + EXPECT_EQ(InterruptReasonContentToExtension( \ + download::DOWNLOAD_INTERRUPT_REASON_##name), \ + downloads::INTERRUPT_REASON_##name); \ + EXPECT_EQ( \ + InterruptReasonExtensionToComponent(downloads::INTERRUPT_REASON_##name), \ + download::DOWNLOAD_INTERRUPT_REASON_##name); +#include "components/download/public/common/download_interrupt_reason_values.h" #undef INTERRUPT_REASON } diff --git a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc index 109d0b84a3e..db6580819bf 100644 --- a/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc +++ b/chromium/chrome/browser/extensions/api/downloads_internal/downloads_internal_api.cc @@ -19,21 +19,21 @@ DownloadsInternalDetermineFilenameFunction:: typedef extensions::api::downloads_internal::DetermineFilename::Params DetermineFilenameParams; -bool DownloadsInternalDetermineFilenameFunction::RunAsync() { +ExtensionFunction::ResponseAction +DownloadsInternalDetermineFilenameFunction::Run() { std::unique_ptr<DetermineFilenameParams> params( DetermineFilenameParams::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); base::FilePath::StringType filename; EXTENSION_FUNCTION_VALIDATE(args_->GetString(1, &filename)); - return ExtensionDownloadsEventRouter::DetermineFilename( - GetProfile(), - include_incognito(), - extension()->id(), - params->download_id, - base::FilePath(filename), + std::string error; + bool result = ExtensionDownloadsEventRouter::DetermineFilename( + browser_context(), include_incognito(), extension()->id(), + params->download_id, base::FilePath(filename), extensions::api::downloads::ParseFilenameConflictAction( params->conflict_action), - &error_); + &error); + return RespondNow(result ? NoArguments() : Error(error)); } } // namespace extensions 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 f7da2b58564..4d6acf505cf 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 @@ -6,17 +6,17 @@ #define CHROME_BROWSER_EXTENSIONS_API_DOWNLOADS_INTERNAL_DOWNLOADS_INTERNAL_API_H_ #include "base/macros.h" -#include "chrome/browser/extensions/chrome_extension_function.h" +#include "extensions/browser/extension_function.h" namespace extensions { class DownloadsInternalDetermineFilenameFunction - : public ChromeAsyncExtensionFunction { + : public UIThreadExtensionFunction { public: DECLARE_EXTENSION_FUNCTION("downloadsInternal.determineFilename", DOWNLOADSINTERNAL_DETERMINEFILENAME); DownloadsInternalDetermineFilenameFunction(); - bool RunAsync() override; + ResponseAction Run() override; protected: ~DownloadsInternalDetermineFilenameFunction() override; diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc index 7f41f2d8534..c8dc598aa2b 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api.cc @@ -43,6 +43,7 @@ #include "components/proximity_auth/screenlock_state.h" #include "components/proximity_auth/switches.h" #include "components/signin/core/account_id/account_id.h" +#include "components/strings/grit/components_strings.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/browser_context_keyed_api_factory.h" #include "ui/base/l10n/l10n_util.h" @@ -157,9 +158,8 @@ ExtensionFunction::ResponseAction EasyUnlockPrivateGetStringsFunction::Run() { #endif // defined(OS_CHROMEOS) // Common strings. - strings->SetString( - "learnMoreLinkTitle", - l10n_util::GetStringUTF16(IDS_EASY_UNLOCK_LEARN_MORE_LINK_TITLE)); + strings->SetString("learnMoreLinkTitle", + l10n_util::GetStringUTF16(IDS_LEARN_MORE)); strings->SetString("deviceType", device_type); // Setup notification strings. @@ -302,10 +302,8 @@ ExtensionFunction::ResponseAction EasyUnlockPrivateGetStringsFunction::Run() { "setupAndroidSmartLockDoneButtonText", l10n_util::GetStringUTF16( IDS_EASY_UNLOCK_SETUP_ANDROID_SMART_LOCK_DONE_BUTTON_LABEL)); - strings->SetString( - "setupAndroidSmartLockAboutLinkText", - l10n_util::GetStringUTF16( - IDS_EASY_UNLOCK_SETUP_ANDROID_SMART_LOCK_ABOUT_LINK_TEXT)); + strings->SetString("setupAndroidSmartLockAboutLinkText", + l10n_util::GetStringUTF16(IDS_LEARN_MORE)); // Step 3: Setup completed successfully. strings->SetString( "setupCompleteHeaderTitle", diff --git a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc index 290b81d3093..69a148dabf9 100644 --- a/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc +++ b/chromium/chrome/browser/extensions/api/easy_unlock_private/easy_unlock_private_api_chromeos_unittest.cc @@ -184,10 +184,7 @@ TEST_F(EasyUnlockPrivateApiTest, GenerateEcP256KeyPair) { function->set_has_callback(true); ASSERT_TRUE(extension_function_test_utils::RunFunction( - function.get(), - "[]", - browser(), - extension_function_test_utils::NONE)); + function.get(), "[]", browser(), extensions::api_test_utils::NONE)); const base::ListValue* result_list = function->GetResultList(); ASSERT_TRUE(result_list); @@ -231,7 +228,7 @@ TEST_F(EasyUnlockPrivateApiTest, PerformECDHKeyAgreement) { ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)); + extensions::api_test_utils::NONE)); EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get())); } @@ -277,7 +274,7 @@ TEST_F(EasyUnlockPrivateApiTest, CreateSecureMessage) { ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)); + extensions::api_test_utils::NONE)); EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get())); } @@ -307,7 +304,7 @@ TEST_F(EasyUnlockPrivateApiTest, CreateSecureMessage_EmptyOptions) { ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)); + extensions::api_test_utils::NONE)); EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get())); } @@ -346,7 +343,7 @@ TEST_F(EasyUnlockPrivateApiTest, CreateSecureMessage_AsymmetricSign) { ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)); + extensions::api_test_utils::NONE)); EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get())); } @@ -384,7 +381,7 @@ TEST_F(EasyUnlockPrivateApiTest, UnwrapSecureMessage) { ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)); + extensions::api_test_utils::NONE)); EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get())); } @@ -414,7 +411,7 @@ TEST_F(EasyUnlockPrivateApiTest, UnwrapSecureMessage_EmptyOptions) { ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)); + extensions::api_test_utils::NONE)); EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get())); } @@ -450,7 +447,7 @@ TEST_F(EasyUnlockPrivateApiTest, UnwrapSecureMessage_AsymmetricSign) { ASSERT_TRUE(extension_function_test_utils::RunFunction( function.get(), std::move(args), browser(), - extension_function_test_utils::NONE)); + extensions::api_test_utils::NONE)); EXPECT_EQ(expected_result, GetSingleBinaryResultAsString(function.get())); } @@ -500,10 +497,8 @@ TEST_F(EasyUnlockPrivateApiTest, AutoPairing) { scoped_refptr<EasyUnlockPrivateSetAutoPairingResultFunction> function( new EasyUnlockPrivateSetAutoPairingResultFunction()); ASSERT_TRUE(extension_function_test_utils::RunFunction( - function.get(), - "[{\"success\":false, \"errorMessage\":\"fake_error\"}]", - browser(), - extension_function_test_utils::NONE)); + function.get(), "[{\"success\":false, \"errorMessage\":\"fake_error\"}]", + browser(), extensions::api_test_utils::NONE)); EXPECT_FALSE(result.success); EXPECT_EQ("fake_error", result.error); @@ -512,10 +507,8 @@ TEST_F(EasyUnlockPrivateApiTest, AutoPairing) { base::Unretained(&result))); function = new EasyUnlockPrivateSetAutoPairingResultFunction(); ASSERT_TRUE(extension_function_test_utils::RunFunction( - function.get(), - "[{\"success\":true}]", - browser(), - extension_function_test_utils::NONE)); + function.get(), "[{\"success\":true}]", browser(), + extensions::api_test_utils::NONE)); EXPECT_TRUE(result.success); EXPECT_TRUE(result.error.empty()); } 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 51661075426..35679e37510 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 @@ -11,6 +11,8 @@ #include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/enterprise_device_attributes.h" +#include "chromeos/system/statistics_provider.h" +#include "components/user_manager/user.h" #include "components/user_manager/user_manager.h" namespace extensions { @@ -18,23 +20,13 @@ namespace extensions { namespace { // Checks for the current browser context if the user is affiliated. -bool IsPermittedToGetDeviceId(content::BrowserContext* context) { +bool IsPermittedToGetDeviceAttributes(content::BrowserContext* context) { const user_manager::User* user = chromeos::ProfileHelper::Get()->GetUserByProfile( Profile::FromBrowserContext(context)); return user->IsAffiliated(); } -// Returns the directory device id for the permitted extensions or an empty -// string. -std::string GetDirectoryDeviceId(content::BrowserContext* context) { - return IsPermittedToGetDeviceId(context) - ? g_browser_process->platform_part() - ->browser_policy_connector_chromeos() - ->GetDirectoryApiID() - : std::string(); -} - } // namespace EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction:: @@ -45,10 +37,71 @@ EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction:: ExtensionFunction::ResponseAction EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction::Run() { - const std::string device_id = GetDirectoryDeviceId(browser_context()); + std::string device_id; + if (IsPermittedToGetDeviceAttributes(browser_context())) { + device_id = g_browser_process->platform_part() + ->browser_policy_connector_chromeos() + ->GetDirectoryApiID(); + } return RespondNow(ArgumentList( api::enterprise_device_attributes::GetDirectoryDeviceId::Results::Create( device_id))); } +EnterpriseDeviceAttributesGetDeviceSerialNumberFunction:: + EnterpriseDeviceAttributesGetDeviceSerialNumberFunction() {} + +EnterpriseDeviceAttributesGetDeviceSerialNumberFunction:: + ~EnterpriseDeviceAttributesGetDeviceSerialNumberFunction() {} + +ExtensionFunction::ResponseAction +EnterpriseDeviceAttributesGetDeviceSerialNumberFunction::Run() { + std::string serial_number; + if (IsPermittedToGetDeviceAttributes(browser_context())) { + serial_number = chromeos::system::StatisticsProvider::GetInstance() + ->GetEnterpriseMachineID(); + } + return RespondNow(ArgumentList( + api::enterprise_device_attributes::GetDeviceSerialNumber::Results::Create( + serial_number))); +} + +EnterpriseDeviceAttributesGetDeviceAssetIdFunction:: + EnterpriseDeviceAttributesGetDeviceAssetIdFunction() {} + +EnterpriseDeviceAttributesGetDeviceAssetIdFunction:: + ~EnterpriseDeviceAttributesGetDeviceAssetIdFunction() {} + +ExtensionFunction::ResponseAction +EnterpriseDeviceAttributesGetDeviceAssetIdFunction::Run() { + std::string asset_id; + if (IsPermittedToGetDeviceAttributes(browser_context())) { + asset_id = g_browser_process->platform_part() + ->browser_policy_connector_chromeos() + ->GetDeviceAssetID(); + } + return RespondNow(ArgumentList( + api::enterprise_device_attributes::GetDeviceAssetId::Results::Create( + asset_id))); +} + +EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction:: + EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction() {} + +EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction:: + ~EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction() {} + +ExtensionFunction::ResponseAction +EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction::Run() { + std::string annotated_location; + if (IsPermittedToGetDeviceAttributes(browser_context())) { + annotated_location = g_browser_process->platform_part() + ->browser_policy_connector_chromeos() + ->GetDeviceAnnotatedLocation(); + } + return RespondNow(ArgumentList( + api::enterprise_device_attributes::GetDeviceAnnotatedLocation::Results:: + Create(annotated_location))); +} + } // namespace extensions 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 ca1d02370c7..3f993c2174d 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 @@ -24,5 +24,52 @@ class EnterpriseDeviceAttributesGetDirectoryDeviceIdFunction ENTERPRISE_DEVICEATTRIBUTES_GETDIRECTORYDEVICEID); }; +class EnterpriseDeviceAttributesGetDeviceSerialNumberFunction + : public UIThreadExtensionFunction { + public: + EnterpriseDeviceAttributesGetDeviceSerialNumberFunction(); + + protected: + ~EnterpriseDeviceAttributesGetDeviceSerialNumberFunction() override; + + ResponseAction Run() override; + + private: + DECLARE_EXTENSION_FUNCTION( + "enterprise.deviceAttributes.getDeviceSerialNumber", + ENTERPRISE_DEVICEATTRIBUTES_GETDEVICESERIALNUMBER); +}; + +class EnterpriseDeviceAttributesGetDeviceAssetIdFunction + : public UIThreadExtensionFunction { + public: + EnterpriseDeviceAttributesGetDeviceAssetIdFunction(); + + protected: + ~EnterpriseDeviceAttributesGetDeviceAssetIdFunction() override; + + ResponseAction Run() override; + + private: + DECLARE_EXTENSION_FUNCTION("enterprise.deviceAttributes.getDeviceAssetId", + ENTERPRISE_DEVICEATTRIBUTES_GETDEVICEASSETID); +}; + +class EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction + : public UIThreadExtensionFunction { + public: + EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction(); + + protected: + ~EnterpriseDeviceAttributesGetDeviceAnnotatedLocationFunction() override; + + ResponseAction Run() override; + + private: + DECLARE_EXTENSION_FUNCTION( + "enterprise.deviceAttributes.getDeviceAnnotatedLocation", + ENTERPRISE_DEVICEATTRIBUTES_GETDEVICEANNOTATEDLOCATION); +}; + } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_ENTERPRISE_DEVICE_ATTRIBUTES_ENTERPRISE_DEVICE_ATTRIBUTES_API_H_ diff --git a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc index b4422a1d396..84603c4d929 100644 --- a/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc +++ b/chromium/chrome/browser/extensions/api/enterprise_device_attributes/enterprise_device_attributes_apitest.cc @@ -4,7 +4,9 @@ #include <memory> +#include "base/json/json_writer.h" #include "base/strings/stringprintf.h" +#include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chromeos/policy/affiliation_test_helper.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" @@ -14,6 +16,8 @@ #include "chrome/browser/net/url_request_mock_util.h" #include "chrome/test/base/ui_test_utils.h" #include "chromeos/dbus/fake_session_manager_client.h" +#include "chromeos/system/fake_statistics_provider.h" +#include "chromeos/system/statistics_provider.h" #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/policy_constants.h" @@ -31,6 +35,9 @@ namespace { constexpr char kDeviceId[] = "device_id"; +constexpr char kSerialNumber[] = "serial_number"; +constexpr char kAssetId[] = "asset_id"; +constexpr char kAnnotatedLocation[] = "annotated_location"; constexpr base::FilePath::CharType kTestExtensionDir[] = FILE_PATH_LITERAL("extensions/api_test/enterprise_device_attributes"); constexpr base::FilePath::CharType kUpdateManifestFileName[] = @@ -51,6 +58,21 @@ struct Params { bool affiliated_; }; +base::Value BuildCustomArg(const std::string& expected_directory_device_id, + const std::string& expected_serial_number, + const std::string& expected_asset_id, + const std::string& expected_annotated_location) { + base::Value custom_arg(base::Value::Type::DICTIONARY); + custom_arg.SetKey("expectedDirectoryDeviceId", + base::Value(expected_directory_device_id)); + custom_arg.SetKey("expectedSerialNumber", + base::Value(expected_serial_number)); + custom_arg.SetKey("expectedAssetId", base::Value(expected_asset_id)); + custom_arg.SetKey("expectedAnnotatedLocation", + base::Value(expected_annotated_location)); + return custom_arg; +} + } // namespace namespace extensions { @@ -60,6 +82,8 @@ class EnterpriseDeviceAttributesTest : public ::testing::WithParamInterface<Params> { public: EnterpriseDeviceAttributesTest() { + fake_statistics_provider_.SetMachineStatistic( + chromeos::system::kSerialNumberKey, kSerialNumber); set_exit_when_last_browser_closes(false); set_chromeos_user_ = false; } @@ -110,6 +134,8 @@ class EnterpriseDeviceAttributesTest : policy::DevicePolicyBuilder* device_policy = test_helper_.device_policy(); device_policy->SetDefaultSigningKey(); device_policy->policy_data().set_directory_api_id(kDeviceId); + device_policy->policy_data().set_annotated_asset_id(kAssetId); + device_policy->policy_data().set_annotated_location(kAnnotatedLocation); device_policy->Build(); fake_session_manager_client->set_device_policy(device_policy->GetBlob()); @@ -170,9 +196,15 @@ class EnterpriseDeviceAttributesTest : // only very little functionality from RunExtensionSubtest(). Thus so that // don't make RunExtensionSubtest() to complex we just introduce a new // function. - bool TestExtension(Browser* browser, const std::string& page_url) { + bool TestExtension(Browser* browser, + const std::string& page_url, + const base::Value& custom_arg_value) { DCHECK(!page_url.empty()) << "page_url cannot be empty"; + std::string custom_arg; + base::JSONWriter::Write(custom_arg_value, &custom_arg); + SetCustomArg(custom_arg); + extensions::ResultCatcher catcher; ui_test_utils::NavigateToURL(browser, GURL(page_url)); @@ -190,6 +222,7 @@ class EnterpriseDeviceAttributesTest : private: policy::MockConfigurationPolicyProvider policy_provider_; policy::DevicePolicyCrosTestHelper test_helper_; + chromeos::system::ScopedFakeStatisticsProvider fake_statistics_provider_; }; IN_PROC_BROWSER_TEST_P(EnterpriseDeviceAttributesTest, PRE_Success) { @@ -206,13 +239,21 @@ IN_PROC_BROWSER_TEST_P(EnterpriseDeviceAttributesTest, Success) { EXPECT_EQ(GetParam().affiliated_, user_manager::UserManager::Get()-> FindUser(affiliated_account_id_)->IsAffiliated()); - // Device ID is available only for affiliated user. - std::string device_id = GetParam().affiliated_ ? kDeviceId : ""; + // Device attributes are available only for affiliated user. + std::string expected_directory_device_id = + GetParam().affiliated_ ? kDeviceId : ""; + std::string expected_serial_number = + GetParam().affiliated_ ? kSerialNumber : ""; + std::string expected_asset_id = GetParam().affiliated_ ? kAssetId : ""; + std::string expected_annotated_location = + GetParam().affiliated_ ? kAnnotatedLocation : ""; // Pass the expected value (device_id) to test. - ASSERT_TRUE(TestExtension(CreateBrowser(profile()), - base::StringPrintf("chrome-extension://%s/basic.html?%s", - kTestExtensionID, device_id.c_str()))) + ASSERT_TRUE(TestExtension( + CreateBrowser(profile()), + base::StringPrintf("chrome-extension://%s/basic.html", kTestExtensionID), + BuildCustomArg(expected_directory_device_id, expected_serial_number, + expected_asset_id, expected_annotated_location))) << message_; } 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 6ca6aa5a0ef..d974bf51ac0 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 @@ -181,7 +181,8 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { std::string RunFunctionAndReturnError(UIThreadExtensionFunction* function, std::unique_ptr<base::ListValue> args, Browser* browser) { - utils::RunFunction(function, std::move(args), browser, utils::NONE); + utils::RunFunction(function, std::move(args), browser, + extensions::api_test_utils::NONE); EXPECT_EQ(ExtensionFunction::FAILED, *function->response_type()); return function->GetError(); } @@ -195,7 +196,8 @@ class EPKChallengeKeyTestBase : public BrowserWithTestWindowTest { scoped_refptr<ExtensionFunction> function_owner(function); // Without a callback the function will not generate a result. function->set_has_callback(true); - utils::RunFunction(function, std::move(args), browser, utils::NONE); + utils::RunFunction(function, std::move(args), browser, + extensions::api_test_utils::NONE); EXPECT_TRUE(function->GetError().empty()) << "Unexpected error: " << function->GetError(); const base::Value* single_result = NULL; @@ -324,16 +326,16 @@ TEST_F(EPKChallengeMachineKeyTest, KeyExists) { // GetCertificate must not be called if the key exists. EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); - EXPECT_TRUE( - utils::RunFunction(func_.get(), CreateArgs(), browser(), utils::NONE)); + EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), + extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeMachineKeyTest, KeyNotRegisteredByDefault) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .Times(0); - EXPECT_TRUE( - utils::RunFunction(func_.get(), CreateArgs(), browser(), utils::NONE)); + EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), + extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeMachineKeyTest, KeyNotRegistered) { @@ -341,7 +343,7 @@ TEST_F(EPKChallengeMachineKeyTest, KeyNotRegistered) { .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgsNoRegister(), browser(), - utils::NONE)); + extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeMachineKeyTest, Success) { @@ -514,8 +516,8 @@ TEST_F(EPKChallengeUserKeyTest, KeyExists) { // GetCertificate must not be called if the key exists. EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)).Times(0); - EXPECT_TRUE( - utils::RunFunction(func_.get(), CreateArgs(), browser(), utils::NONE)); + EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgs(), browser(), + extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeUserKeyTest, KeyNotRegistered) { @@ -523,7 +525,7 @@ TEST_F(EPKChallengeUserKeyTest, KeyNotRegistered) { .Times(0); EXPECT_TRUE(utils::RunFunction(func_.get(), CreateArgsNoRegister(), browser(), - utils::NONE)); + extensions::api_test_utils::NONE)); } TEST_F(EPKChallengeUserKeyTest, PersonalDevice) { 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 f81fd5c960b..03541c19880 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 @@ -320,7 +320,8 @@ TEST_F(EPKPChallengeMachineKeyTest, KeyExists) { EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) .Times(0); - EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), utils::NONE)); + EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), + extensions::api_test_utils::NONE)); } TEST_F(EPKPChallengeMachineKeyTest, AttestationNotPrepared) { @@ -363,7 +364,7 @@ TEST_P(EPKPChallengeMachineKeyAllProfilesTest, Success) { .Times(1); std::unique_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( - func_.get(), kArgs, browser(), utils::NONE)); + func_.get(), kArgs, browser(), extensions::api_test_utils::NONE)); std::string response; value->GetAsString(&response); @@ -490,15 +491,16 @@ TEST_F(EPKPChallengeUserKeyTest, KeyExists) { EXPECT_CALL(mock_attestation_flow_, GetCertificate(_, _, _, _, _)) .Times(0); - EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), utils::NONE)); + EXPECT_TRUE(utils::RunFunction(func_.get(), kArgs, browser(), + extensions::api_test_utils::NONE)); } TEST_F(EPKPChallengeUserKeyTest, KeyNotRegistered) { EXPECT_CALL(mock_async_method_caller_, TpmAttestationRegisterKey(_, _, _, _)) .Times(0); - EXPECT_TRUE(utils::RunFunction( - func_.get(), "[\"Y2hhbGxlbmdl\", false]", browser(), utils::NONE)); + EXPECT_TRUE(utils::RunFunction(func_.get(), "[\"Y2hhbGxlbmdl\", false]", + browser(), extensions::api_test_utils::NONE)); } TEST_F(EPKPChallengeUserKeyTest, PersonalDevice) { @@ -533,7 +535,7 @@ TEST_F(EPKPChallengeUserKeyTest, Success) { .Times(1); std::unique_ptr<base::Value> value(utils::RunFunctionAndReturnSingleResult( - func_.get(), kArgs, browser(), utils::NONE)); + func_.get(), kArgs, browser(), extensions::api_test_utils::NONE)); std::string response; value->GetAsString(&response); diff --git a/chromium/chrome/browser/extensions/api/experience_sampling_private/OWNERS b/chromium/chrome/browser/extensions/api/experience_sampling_private/OWNERS deleted file mode 100644 index 885f0ab7205..00000000000 --- a/chromium/chrome/browser/extensions/api/experience_sampling_private/OWNERS +++ /dev/null @@ -1 +0,0 @@ -felt@chromium.org diff --git a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling.cc b/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling.cc deleted file mode 100644 index ebf4250039f..00000000000 --- a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling.cc +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2014 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/experience_sampling_private/experience_sampling.h" - -#include <utility> - -#include "base/values.h" -#include "chrome/browser/browser_process.h" -#include "chrome/browser/profiles/profile.h" -#include "chrome/browser/profiles/profile_manager.h" -#include "chrome/common/extensions/api/experience_sampling_private.h" -#include "extensions/browser/event_router.h" -#include "url/gurl.h" - -namespace extensions { - -// static -const char ExperienceSamplingEvent::kProceed[] = "proceed"; -const char ExperienceSamplingEvent::kDeny[] = "deny"; -const char ExperienceSamplingEvent::kIgnore[] = "ignore"; -const char ExperienceSamplingEvent::kCancel[] = "cancel"; -const char ExperienceSamplingEvent::kReload[] = "reload"; - -// static -const char ExperienceSamplingEvent::kMaliciousDownload[] = - "download_warning_malicious"; -const char ExperienceSamplingEvent::kDangerousDownload[] = - "download_warning_dangerous"; -const char ExperienceSamplingEvent::kDownloadDangerPrompt[] = - "download_danger_prompt"; -const char ExperienceSamplingEvent::kExtensionInstallDialog[] = - "extension_install_dialog_"; - -// static -std::unique_ptr<ExperienceSamplingEvent> ExperienceSamplingEvent::Create( - const std::string& element_name, - const GURL& destination, - const GURL& referrer) { - Profile* profile = NULL; - if (g_browser_process->profile_manager()) - profile = g_browser_process->profile_manager()->GetLastUsedProfile(); - if (!profile) - return std::unique_ptr<ExperienceSamplingEvent>(); - return std::unique_ptr<ExperienceSamplingEvent>(new ExperienceSamplingEvent( - element_name, destination, referrer, profile)); -} - -// static -std::unique_ptr<ExperienceSamplingEvent> ExperienceSamplingEvent::Create( - const std::string& element_name) { - return ExperienceSamplingEvent::Create(element_name, GURL(), GURL()); -} - -ExperienceSamplingEvent::ExperienceSamplingEvent( - const std::string& element_name, - const GURL& destination, - const GURL& referrer, - content::BrowserContext* browser_context) - : has_viewed_details_(false), - has_viewed_learn_more_(false), - browser_context_(browser_context) { - ui_element_.name = element_name; - ui_element_.destination = destination.GetAsReferrer().possibly_invalid_spec(); - ui_element_.referrer = referrer.GetAsReferrer().possibly_invalid_spec(); - ui_element_.time = base::Time::Now().ToJsTime(); -} - -ExperienceSamplingEvent::~ExperienceSamplingEvent() { -} - -void ExperienceSamplingEvent::CreateUserDecisionEvent( - const std::string& decision_name) { - // Check if this is from an incognito context. If it is, don't create and send - // any events. - if (browser_context_ && browser_context_->IsOffTheRecord()) - return; - api::experience_sampling_private::UserDecision decision; - decision.name = decision_name; - decision.learn_more = has_viewed_learn_more(); - decision.details = has_viewed_details(); - decision.time = base::Time::Now().ToJsTime(); - - std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(ui_element_.ToValue()); - args->Append(decision.ToValue()); - std::unique_ptr<Event> event( - new Event(events::EXPERIENCE_SAMPLING_PRIVATE_ON_DECISION, - api::experience_sampling_private::OnDecision::kEventName, - std::move(args))); - EventRouter* router = EventRouter::Get(browser_context_); - if (router) - router->BroadcastEvent(std::move(event)); -} - -void ExperienceSamplingEvent::CreateOnDisplayedEvent() { - // Check if this is from an incognito context. If it is, don't create and send - // any events. - if (browser_context_ && browser_context_->IsOffTheRecord()) - return; - std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(ui_element_.ToValue()); - std::unique_ptr<Event> event( - new Event(events::EXPERIENCE_SAMPLING_PRIVATE_ON_DISPLAYED, - api::experience_sampling_private::OnDisplayed::kEventName, - std::move(args))); - EventRouter* router = EventRouter::Get(browser_context_); - if (router) - router->BroadcastEvent(std::move(event)); -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling.h b/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling.h deleted file mode 100644 index 30f6a68f0d2..00000000000 --- a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling.h +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2014 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_EXPERIENCE_SAMPLING_PRIVATE_EXPERIENCE_SAMPLING_H_ -#define CHROME_BROWSER_EXTENSIONS_API_EXPERIENCE_SAMPLING_PRIVATE_EXPERIENCE_SAMPLING_H_ - -#include <memory> - -#include "base/macros.h" -#include "chrome/common/extensions/api/experience_sampling_private.h" - -namespace content { -class BrowserContext; -} - -class GURL; - -namespace extensions { - -using api::experience_sampling_private::UIElement; - -class ExperienceSamplingEvent { - public: - // String constants for user decision events. - static const char kProceed[]; - static const char kDeny[]; - static const char kIgnore[]; - static const char kCancel[]; - static const char kReload[]; - - // String constants for event names. - static const char kMaliciousDownload[]; - static const char kDangerousDownload[]; - static const char kDownloadDangerPrompt[]; - static const char kExtensionInstallDialog[]; - - // The Create() functions can return an empty scoped_ptr if they cannot find - // the BrowserContext. Code using them should check the scoped pointer using - // scoped_ptr::get(). - static std::unique_ptr<ExperienceSamplingEvent> Create( - const std::string& element_name, - const GURL& destination, - const GURL& referrer); - - static std::unique_ptr<ExperienceSamplingEvent> Create( - const std::string& element_name); - - ExperienceSamplingEvent(const std::string& element_name, - const GURL& destination, - const GURL& referrer, - content::BrowserContext* browser_context); - ~ExperienceSamplingEvent(); - - // Sends an extension API event for the user seeing this event. - void CreateOnDisplayedEvent(); - // Sends an extension API event for the user making a decision about this - // event. - void CreateUserDecisionEvent(const std::string& decision_name); - - bool has_viewed_details() const { return has_viewed_details_; } - void set_has_viewed_details(bool viewed) { has_viewed_details_ = viewed; } - bool has_viewed_learn_more() const { return has_viewed_learn_more_; } - void set_has_viewed_learn_more(bool viewed) { - has_viewed_learn_more_ = viewed; - } - - private: - bool has_viewed_details_; - bool has_viewed_learn_more_; - content::BrowserContext* browser_context_; - UIElement ui_element_; - - DISALLOW_COPY_AND_ASSIGN(ExperienceSamplingEvent); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_EXPERIENCE_SAMPLING_PRIVATE_EXPERIENCE_SAMPLING_H_ diff --git a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api.cc b/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api.cc deleted file mode 100644 index f212226b785..00000000000 --- a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api.cc +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2014 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/experience_sampling_private/experience_sampling_private_api.h" - -#include "base/metrics/field_trial.h" -#include "chrome/common/extensions/api/experience_sampling_private.h" - -namespace sampling = extensions::api::experience_sampling_private; - -namespace extensions { - -bool ExperienceSamplingPrivateGetBrowserInfoFunction::RunAsync() { - std::string field_trials; - sampling::BrowserInfo info; - - base::FieldTrialList::StatesToString(&field_trials); - info.variations = field_trials; - - SetResult(info.ToValue()); - SendResponse(true /* success */); - return true; -} - -} // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api.h b/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api.h deleted file mode 100644 index e199f288704..00000000000 --- a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2014 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_EXPERIENCE_SAMPLING_PRIVATE_EXPERIENCE_SAMPLING_PRIVATE_API_H_ -#define CHROME_BROWSER_EXTENSIONS_API_EXPERIENCE_SAMPLING_PRIVATE_EXPERIENCE_SAMPLING_PRIVATE_API_H_ - -#include "chrome/browser/extensions/chrome_extension_function.h" - -namespace extensions { - -class ExperienceSamplingPrivateGetBrowserInfoFunction - : public ChromeAsyncExtensionFunction { - protected: - ~ExperienceSamplingPrivateGetBrowserInfoFunction() override {} - - // ExtensionFuction: - bool RunAsync() override; - - private: - DECLARE_EXTENSION_FUNCTION("experienceSamplingPrivate.getBrowserInfo", - EXPERIENCESAMPLINGPRIVATE_GETBROWSERINFO); -}; - -} // namespace extensions - -#endif // CHROME_BROWSER_EXTENSIONS_API_EXPERIENCE_SAMPLING_PRIVATE_EXPERIENCE_SAMPLING_PRIVATE_API_H_ diff --git a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api_unittest.cc b/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api_unittest.cc deleted file mode 100644 index e71b6037c51..00000000000 --- a/chromium/chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api_unittest.cc +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/metrics/field_trial.h" -#include "chrome/browser/extensions/api/experience_sampling_private/experience_sampling_private_api.h" -#include "chrome/browser/extensions/extension_api_unittest.h" -#include "chrome/browser/extensions/extension_function_test_utils.h" - - -namespace utils = extension_function_test_utils; - -namespace extensions { - -typedef ExtensionApiUnittest ExperienceSamplingPrivateTest; - -// Tests that chrome.experienceSamplingPrivate.getBrowserInfo() returns expected -// field trials and groups. -TEST_F(ExperienceSamplingPrivateTest, GetBrowserInfoTest) { - // Start with an empty FieldTrialList. - std::unique_ptr<base::FieldTrialList> trial_list( - new base::FieldTrialList(nullptr)); - std::unique_ptr<base::DictionaryValue> result(RunFunctionAndReturnDictionary( - new ExperienceSamplingPrivateGetBrowserInfoFunction(), "[]")); - ASSERT_TRUE(result->HasKey("variations")); - std::string trials_string; - EXPECT_TRUE(result->GetStringWithoutPathExpansion("variations", - &trials_string)); - ASSERT_EQ("", trials_string); - - // Set field trials using a string. - base::FieldTrialList::CreateTrialsFromString( - "*Some name/Winner/*xxx/yyyy/*zzz/default/", - std::set<std::string>()); - result = RunFunctionAndReturnDictionary( - new ExperienceSamplingPrivateGetBrowserInfoFunction(), "[]"); - ASSERT_TRUE(result->HasKey("variations")); - EXPECT_TRUE(result->GetStringWithoutPathExpansion("variations", - &trials_string)); - ASSERT_EQ("Some name/Winner/xxx/yyyy/zzz/default/", trials_string); -} - -} // namespace extensions 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 c057b5bebfb..35432dbe223 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 @@ -12,7 +12,6 @@ #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/extension_action/extension_action_api.h" -#include "chrome/browser/extensions/browser_action_test_util.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" @@ -26,6 +25,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/extensions/browser_action_test_util.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" @@ -1020,7 +1020,7 @@ IN_PROC_BROWSER_TEST_F(NavigatingExtensionPopupBrowserTest, DownloadViaPost) { downloads_observer.WaitForFinished(); EXPECT_EQ(0u, downloads_observer.NumDangerousDownloadsSeen()); EXPECT_EQ(1u, downloads_observer.NumDownloadsSeenInState( - content::DownloadItem::COMPLETE)); + download::DownloadItem::COMPLETE)); EXPECT_TRUE(base::PathExists(downloads_directory->GetPath().AppendASCII( "download-test3-attachment.gif"))); 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 d2a853e242d..f709e6c9f33 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 @@ -7,7 +7,6 @@ #include "base/run_loop.h" #include "base/test/test_timeouts.h" #include "build/build_config.h" -#include "chrome/browser/extensions/browser_action_test_util.h" #include "chrome/browser/extensions/extension_action.h" #include "chrome/browser/extensions/extension_action_manager.h" #include "chrome/browser/extensions/extension_apitest.h" @@ -18,6 +17,7 @@ #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/extensions/browser_action_test_util.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/ui/toolbar/toolbar_actions_model.h" #include "chrome/test/base/interactive_test_utils.h" @@ -134,16 +134,23 @@ class BrowserActionInteractiveTest : public ExtensionApiTest { } // Open an extension popup via the chrome.browserAction.openPopup API. + // If |will_reply| is true, then the listener is responsible for having a + // test message listener that replies to the extension. Otherwise, this + // method will create a listener and reply to the extension before returning + // to avoid leaking an API function while waiting for a reply. void OpenPopupViaAPI(bool will_reply) { // Setup the notification observer to wait for the popup to finish loading. content::WindowedNotificationObserver frame_observer( content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME, content::NotificationService::AllSources()); - ExtensionTestMessageListener listener("ready", will_reply); + std::unique_ptr<ExtensionTestMessageListener> listener; + if (!will_reply) + listener = std::make_unique<ExtensionTestMessageListener>("ready", false); // Show first popup in first window and expect it to have loaded. ASSERT_TRUE(RunExtensionSubtest("browser_action/open_popup", "open_popup_succeeds.html")) << message_; - EXPECT_TRUE(listener.WaitUntilSatisfied()); + if (listener) + EXPECT_TRUE(listener->WaitUntilSatisfied()); frame_observer.Wait(); EnsurePopupActive(); } @@ -446,21 +453,20 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, } #if defined(OS_WIN) -// Test that forcibly closing the browser and popup HWND does not cause a crash. -// http://crbug.com/400646 -IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, - DISABLED_DestroyHWNDDoesNotCrash) { +// Forcibly closing a browser HWND with a popup should not cause a crash. +IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, DestroyHWNDDoesNotCrash) { if (!ShouldRunPopupTest()) return; OpenPopupViaAPI(false); BrowserActionTestUtil test_util(browser()); - const gfx::NativeView view = test_util.GetPopupNativeView(); - EXPECT_NE(static_cast<gfx::NativeView>(NULL), view); - const HWND hwnd = views::HWNDForNativeView(view); - EXPECT_EQ(hwnd, - views::HWNDForNativeView(browser()->window()->GetNativeWindow())); - EXPECT_EQ(TRUE, ::IsWindow(hwnd)); + const gfx::NativeView popup_view = test_util.GetPopupNativeView(); + EXPECT_NE(static_cast<gfx::NativeView>(nullptr), popup_view); + const HWND popup_hwnd = views::HWNDForNativeView(popup_view); + EXPECT_EQ(TRUE, ::IsWindow(popup_hwnd)); + const HWND browser_hwnd = + views::HWNDForNativeView(browser()->window()->GetNativeWindow()); + EXPECT_EQ(TRUE, ::IsWindow(browser_hwnd)); // Create a new browser window to prevent the message loop from terminating. browser()->OpenURL(content::OpenURLParams(GURL("about:"), content::Referrer(), @@ -468,9 +474,10 @@ IN_PROC_BROWSER_TEST_F(BrowserActionInteractiveTest, ui::PAGE_TRANSITION_TYPED, false)); // Forcibly closing the browser HWND should not cause a crash. - EXPECT_EQ(TRUE, ::CloseWindow(hwnd)); - EXPECT_EQ(TRUE, ::DestroyWindow(hwnd)); - EXPECT_EQ(FALSE, ::IsWindow(hwnd)); + EXPECT_EQ(TRUE, ::CloseWindow(browser_hwnd)); + EXPECT_EQ(TRUE, ::DestroyWindow(browser_hwnd)); + EXPECT_EQ(FALSE, ::IsWindow(browser_hwnd)); + EXPECT_EQ(FALSE, ::IsWindow(popup_hwnd)); } #endif // OS_WIN 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 017614b8028..6466d63c75f 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 @@ -96,31 +96,31 @@ static base::LazyInstance<BrowserContextKeyedAPIFactory<ExtensionActionAPI>>:: ExtensionActionAPI::ExtensionActionAPI(content::BrowserContext* context) : browser_context_(context), extension_prefs_(nullptr) { - ExtensionFunctionRegistry* registry = + ExtensionFunctionRegistry& registry = ExtensionFunctionRegistry::GetInstance(); // Browser Actions - registry->RegisterFunction<BrowserActionSetIconFunction>(); - registry->RegisterFunction<BrowserActionSetTitleFunction>(); - registry->RegisterFunction<BrowserActionSetBadgeTextFunction>(); - registry->RegisterFunction<BrowserActionSetBadgeBackgroundColorFunction>(); - registry->RegisterFunction<BrowserActionSetPopupFunction>(); - registry->RegisterFunction<BrowserActionGetTitleFunction>(); - registry->RegisterFunction<BrowserActionGetBadgeTextFunction>(); - registry->RegisterFunction<BrowserActionGetBadgeBackgroundColorFunction>(); - registry->RegisterFunction<BrowserActionGetPopupFunction>(); - registry->RegisterFunction<BrowserActionEnableFunction>(); - registry->RegisterFunction<BrowserActionDisableFunction>(); - registry->RegisterFunction<BrowserActionOpenPopupFunction>(); + registry.RegisterFunction<BrowserActionSetIconFunction>(); + registry.RegisterFunction<BrowserActionSetTitleFunction>(); + registry.RegisterFunction<BrowserActionSetBadgeTextFunction>(); + registry.RegisterFunction<BrowserActionSetBadgeBackgroundColorFunction>(); + registry.RegisterFunction<BrowserActionSetPopupFunction>(); + registry.RegisterFunction<BrowserActionGetTitleFunction>(); + registry.RegisterFunction<BrowserActionGetBadgeTextFunction>(); + registry.RegisterFunction<BrowserActionGetBadgeBackgroundColorFunction>(); + registry.RegisterFunction<BrowserActionGetPopupFunction>(); + registry.RegisterFunction<BrowserActionEnableFunction>(); + registry.RegisterFunction<BrowserActionDisableFunction>(); + registry.RegisterFunction<BrowserActionOpenPopupFunction>(); // Page Actions - registry->RegisterFunction<PageActionShowFunction>(); - registry->RegisterFunction<PageActionHideFunction>(); - registry->RegisterFunction<PageActionSetIconFunction>(); - registry->RegisterFunction<PageActionSetTitleFunction>(); - registry->RegisterFunction<PageActionSetPopupFunction>(); - registry->RegisterFunction<PageActionGetTitleFunction>(); - registry->RegisterFunction<PageActionGetPopupFunction>(); + registry.RegisterFunction<PageActionShowFunction>(); + registry.RegisterFunction<PageActionHideFunction>(); + registry.RegisterFunction<PageActionSetIconFunction>(); + registry.RegisterFunction<PageActionSetTitleFunction>(); + registry.RegisterFunction<PageActionSetPopupFunction>(); + registry.RegisterFunction<PageActionGetTitleFunction>(); + registry.RegisterFunction<PageActionGetPopupFunction>(); } ExtensionActionAPI::~ExtensionActionAPI() { @@ -226,8 +226,9 @@ void ExtensionActionAPI::DispatchExtensionActionClicked( if (event_name) { std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append( - ExtensionTabUtil::CreateTabObject(web_contents, extension)->ToValue()); + args->Append(ExtensionTabUtil::CreateTabObject( + web_contents, ExtensionTabUtil::kScrubTab, extension) + ->ToValue()); DispatchEventToExtension(web_contents->GetBrowserContext(), extension_action.extension_id(), histogram_value, 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 abc8ca885cc..8aaa5170ffd 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 @@ -11,12 +11,12 @@ #include "base/strings/stringprintf.h" #include "chrome/browser/extensions/browsertest_util.h" #include "chrome/browser/extensions/extension_apitest.h" -#include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "extensions/browser/state_store.h" #include "extensions/test/extension_test_message_listener.h" +#include "extensions/test/test_extension_dir.h" namespace extensions { namespace { diff --git a/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc b/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc index af719794f36..0815a0b5907 100644 --- a/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc +++ b/chromium/chrome/browser/extensions/api/file_system/request_file_system_notification.cc @@ -19,10 +19,10 @@ #include "chrome/grit/generated_resources.h" #include "extensions/common/extension.h" #include "ui/base/l10n/l10n_util.h" -#include "ui/message_center/notification.h" -#include "ui/message_center/notification_delegate.h" -#include "ui/message_center/notification_types.h" -#include "ui/message_center/notifier_id.h" +#include "ui/message_center/public/cpp/notification.h" +#include "ui/message_center/public/cpp/notification_delegate.h" +#include "ui/message_center/public/cpp/notification_types.h" +#include "ui/message_center/public/cpp/notifier_id.h" using file_manager::Volume; using message_center::Notification; diff --git a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc index 7c80a0cf2c0..373c8081e5f 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_apitest.cc @@ -518,8 +518,8 @@ class IdentityGetAccountsFunctionTest : public IdentityTestWithSignin { new IdentityGetAccountsFunction); func->set_extension( ExtensionBuilder("Test").SetID(kExtensionId).Build().get()); - if (!utils::RunFunction( - func.get(), std::string("[]"), browser(), utils::NONE)) { + if (!utils::RunFunction(func.get(), std::string("[]"), browser(), + api_test_utils::NONE)) { return GenerateFailureResult(accounts, NULL) << "getAccounts did not return a result."; } @@ -819,7 +819,7 @@ class GetAuthTokenFunctionTest const OAuth2TokenService::ScopeSet& scopes) override { if (on_access_token_requested_.is_null()) return; - base::ResetAndReturn(&on_access_token_requested_).Run(); + std::move(on_access_token_requested_).Run(); } std::string extension_id_; @@ -2020,10 +2020,8 @@ class RemoveCachedAuthTokenFunctionTest : public ExtensionBrowserTest { func->set_extension( ExtensionBuilder("Test").SetID(kExtensionId).Build().get()); return utils::RunFunction( - func.get(), - std::string("[{\"token\": \"") + kAccessToken + "\"}]", - browser(), - extension_function_test_utils::NONE); + func.get(), std::string("[{\"token\": \"") + kAccessToken + "\"}]", + browser(), api_test_utils::NONE); } IdentityAPI* id_api() { diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc index 6281011f2f0..00eb5916020 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_accounts_function.cc @@ -10,8 +10,8 @@ #include "components/signin/core/browser/profile_management_switches.h" #include "content/public/browser/browser_context.h" #include "content/public/common/service_manager_connection.h" -#include "services/identity/public/interfaces/account.mojom.h" -#include "services/identity/public/interfaces/constants.mojom.h" +#include "services/identity/public/mojom/account.mojom.h" +#include "services/identity/public/mojom/constants.mojom.h" #include "services/service_manager/public/cpp/connector.h" namespace extensions { 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 1e3973c8d5d..9f9aab7b280 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 @@ -7,7 +7,7 @@ #include "extensions/browser/extension_function.h" #include "extensions/browser/extension_function_histogram_value.h" -#include "services/identity/public/interfaces/identity_manager.mojom.h" +#include "services/identity/public/mojom/identity_manager.mojom.h" namespace extensions { 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 3d31a6e98d9..ad7069a0f30 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 @@ -28,7 +28,7 @@ #include "extensions/common/extension_l10n_util.h" #include "google_apis/gaia/gaia_urls.h" #include "services/identity/public/cpp/scope_set.h" -#include "services/identity/public/interfaces/constants.mojom.h" +#include "services/identity/public/mojom/constants.mojom.h" #include "services/service_manager/public/cpp/connector.h" #if defined(OS_CHROMEOS) 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 bfaca4ed14e..ed99f975a37 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 @@ -13,7 +13,7 @@ #include "google_apis/gaia/oauth2_mint_token_flow.h" #include "google_apis/gaia/oauth2_token_service.h" #include "services/identity/public/cpp/account_state.h" -#include "services/identity/public/interfaces/identity_manager.mojom.h" +#include "services/identity/public/mojom/identity_manager.mojom.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc index 085f4c7b41c..b5bf6028018 100644 --- a/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc +++ b/chromium/chrome/browser/extensions/api/identity/identity_get_profile_user_info_function.cc @@ -10,7 +10,7 @@ #include "content/public/common/service_manager_connection.h" #include "extensions/common/extension.h" #include "extensions/common/permissions/permissions_data.h" -#include "services/identity/public/interfaces/constants.mojom.h" +#include "services/identity/public/mojom/constants.mojom.h" #include "services/service_manager/public/cpp/connector.h" namespace extensions { 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 17a201c0649..72d93ab920a 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 @@ -9,7 +9,7 @@ #include "extensions/browser/extension_function.h" #include "extensions/browser/extension_function_histogram_value.h" #include "services/identity/public/cpp/account_state.h" -#include "services/identity/public/interfaces/identity_manager.mojom.h" +#include "services/identity/public/mojom/identity_manager.mojom.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc index 2c4dc2e4cf4..ddcd1a3b317 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/image_writer_private_apitest.cc @@ -69,7 +69,6 @@ class ImageWriterPrivateApiTest : public ExtensionApiTest { protected: - base::MessageLoopForUI message_loop_; image_writer::ImageWriterTestUtils test_utils_; }; 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 7d81d3c4a6e..8510dfde7a0 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 @@ -11,7 +11,7 @@ #include "base/optional.h" #include "base/threading/thread_restrictions.h" #include "chrome/grit/generated_resources.h" -#include "chrome/services/removable_storage_writer/public/interfaces/constants.mojom.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" 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 3ab0136b017..6ac29f5ab5e 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 @@ -15,7 +15,7 @@ #include "base/memory/ref_counted.h" #include "base/sequence_checker.h" #include "base/sequenced_task_runner.h" -#include "chrome/services/removable_storage_writer/public/interfaces/removable_storage_writer.mojom.h" +#include "chrome/services/removable_storage_writer/public/mojom/removable_storage_writer.mojom.h" namespace service_manager { class Connector; 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 68e923f6766..5c0a2ce7983 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 @@ -15,7 +15,7 @@ #include "base/task_scheduler/post_task.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/extensions/api/image_writer_private/operation.h" -#include "chrome/services/removable_storage_writer/public/interfaces/removable_storage_writer.mojom.h" +#include "chrome/services/removable_storage_writer/public/mojom/removable_storage_writer.mojom.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/service_manager_connection.h" 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 8c89c0334bb..58739bb2437 100644 --- a/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc +++ b/chromium/chrome/browser/extensions/api/image_writer_private/operation.cc @@ -251,8 +251,8 @@ void Operation::GetMD5SumOfFile( } } - PostTask(base::BindOnce(&Operation::MD5Chunk, this, Passed(std::move(file)), - 0, file_size, progress_offset, progress_scale, + PostTask(base::BindOnce(&Operation::MD5Chunk, this, std::move(file), 0, + file_size, progress_offset, progress_scale, std::move(callback))); } @@ -294,10 +294,9 @@ void Operation::MD5Chunk( progress_offset; SetProgress(percent_curr); - PostTask(base::BindOnce(&Operation::MD5Chunk, this, - Passed(std::move(file)), bytes_processed + len, - bytes_total, progress_offset, progress_scale, - std::move(callback))); + PostTask(base::BindOnce( + &Operation::MD5Chunk, this, std::move(file), bytes_processed + len, + bytes_total, progress_offset, progress_scale, std::move(callback))); // Skip closing the file. return; } else { 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 fcff500fa4c..3f0a8bceef5 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 @@ -260,7 +260,7 @@ TEST_F(ImageWriterOperationTest, VerifyFileFailure) { test_utils_.GetDevicePath(), kDevicePattern, kTestFileSize); operation_->Start(); - operation_->VerifyWrite(base::Bind(&base::DoNothing)); + operation_->VerifyWrite(base::DoNothing()); content::RunAllTasksUntilIdle(); } #endif // !defined(OS_CHROMEOS) 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 efd57030204..6d1fd598890 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 @@ -13,6 +13,7 @@ #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" #include "extensions/browser/extension_registry.h" +#include "ui/base/ime/ime_bridge.h" #include "ui/keyboard/keyboard_util.h" namespace input_ime = extensions::api::input_ime; @@ -413,6 +414,9 @@ InputImeAPI::~InputImeAPI() = default; void InputImeAPI::Shutdown() { EventRouter::Get(browser_context_)->UnregisterObserver(this); registrar_.RemoveAll(); + if (observer_ && ui::IMEBridge::Get()) { + ui::IMEBridge::Get()->SetObserver(nullptr); + } } static base::LazyInstance<BrowserContextKeyedAPIFactory<InputImeAPI>>:: 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 511b1fc2dfb..6aba7251fcf 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 @@ -24,6 +24,7 @@ #include "extensions/browser/extension_function.h" #include "extensions/browser/extension_registry_observer.h" #include "extensions/common/extension.h" +#include "ui/base/ime/ime_bridge_observer.h" #include "ui/base/ime/ime_engine_handler_interface.h" #include "ui/base/ime/text_input_flags.h" @@ -62,7 +63,6 @@ class ImeObserver : public input_method::InputMethodEngineBase::Observer { int cursor_pos, int anchor_pos, int offset_pos) override; - void OnRequestEngineSwitch() override {} protected: // Helper function used to forward the given event to the |profile_|'s event @@ -176,6 +176,7 @@ class InputImeAPI : public BrowserContextKeyedAPI, // BrowserContextKeyedAPI implementation. static BrowserContextKeyedAPIFactory<InputImeAPI>* GetFactoryInstance(); + void Shutdown() override; // ExtensionRegistryObserver implementation. @@ -210,6 +211,8 @@ class InputImeAPI : public BrowserContextKeyedAPI, extension_registry_observer_; content::NotificationRegistrar registrar_; + + std::unique_ptr<ui::IMEBridgeObserver> observer_; }; InputImeEventRouter* GetInputImeEventRouter(Profile* profile); 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 11bccc7e86d..76519202074 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 @@ -63,6 +63,20 @@ bool IsInputImeEnabled() { switches::kDisableInputImeAPI); } +class ImeBridgeObserver : public ui::IMEBridgeObserver { + public: + void OnRequestSwitchEngine() override { + Browser* browser = chrome::FindLastActive(); + if (!browser) + return; + extensions::InputImeEventRouter* router = + extensions::GetInputImeEventRouter(browser->profile()); + if (!router) + return; + ui::IMEBridge::Get()->SetCurrentEngineHandler(router->active_engine()); + } +}; + class ImeObserverNonChromeOS : public ui::ImeObserver { public: ImeObserverNonChromeOS(const std::string& extension_id, Profile* profile) @@ -94,17 +108,6 @@ class ImeObserverNonChromeOS : public ui::ImeObserver { OnCompositionBoundsChanged::kEventName, std::move(args)); } - void OnRequestEngineSwitch() override { - Browser* browser = chrome::FindLastActive(); - if (!browser) - return; - extensions::InputImeEventRouter* router = - extensions::GetInputImeEventRouter(browser->profile()); - if (!router) - return; - ui::IMEBridge::Get()->SetCurrentEngineHandler(router->active_engine()); - } - private: // ImeObserver overrides. void DispatchEventToExtension( @@ -145,6 +148,10 @@ void InputImeAPI::OnExtensionLoaded(content::BrowserContext* browser_context, const Extension* extension) { // No-op if called multiple times. ui::IMEBridge::Initialize(); + if (!observer_) { + observer_ = std::make_unique<ImeBridgeObserver>(); + ui::IMEBridge::Get()->SetObserver(observer_.get()); + } // Set the preference kPrefNeverActivatedSinceLoaded true to indicate // input.ime.activate API has been never called since loaded. 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 e42d686bd00..59177c3676e 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 @@ -12,6 +12,7 @@ #include <utility> #include <vector> +#include "base/containers/flat_set.h" #include "base/feature_list.h" #include "base/stl_util.h" #include "base/strings/string16.h" @@ -32,6 +33,7 @@ #include "chrome/common/extensions/api/language_settings_private.h" #include "chrome/common/pref_names.h" #include "components/language/core/browser/language_model.h" +#include "components/language/core/common/locale_util.h" #include "components/spellcheck/common/spellcheck_common.h" #include "components/translate/core/browser/translate_download_manager.h" #include "components/translate/core/browser/translate_prefs.h" @@ -178,15 +180,14 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() { app_locale, translate_prefs->IsTranslateAllowedByPolicy(), &languages); // Get the list of available locales (display languages) and convert to a set. - const std::vector<std::string>& locales = l10n_util::GetAvailableLocales(); - const std::unordered_set<std::string> locale_set(locales.begin(), - locales.end()); + const base::flat_set<std::string> locale_set( + l10n_util::GetAvailableLocales()); // Get the list of spell check languages and convert to a set. std::vector<std::string> spellcheck_languages = spellcheck::SpellCheckLanguages(); - const std::unordered_set<std::string> spellcheck_language_set( - spellcheck_languages.begin(), spellcheck_languages.end()); + const base::flat_set<std::string> spellcheck_language_set( + std::move(spellcheck_languages)); // Build the language list. std::unique_ptr<base::ListValue> language_list(new base::ListValue); @@ -198,15 +199,20 @@ LanguageSettingsPrivateGetLanguageListFunction::Run() { language.native_display_name = entry.native_display_name; // Set optional fields only if they differ from the default. - if (locale_set.count(entry.code) > 0) { - language.supports_ui.reset(new bool(true)); - } - if (spellcheck_language_set.count(entry.code) > 0) { + if (base::ContainsKey(spellcheck_language_set, entry.code)) { language.supports_spellcheck.reset(new bool(true)); } if (entry.supports_translate) { language.supports_translate.reset(new bool(true)); } + if (base::FeatureList::IsEnabled(translate::kRegionalLocalesAsDisplayUI)) { + std::string temp_locale = entry.code; + if (language::ConvertToActualUILocale(&temp_locale)) { + language.supports_ui.reset(new bool(true)); + } + } else if (base::ContainsKey(locale_set, entry.code)) { + language.supports_ui.reset(new bool(true)); + } language_list->Append(language.ToValue()); } 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 12e2e46e9c2..8e1ad435a91 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 @@ -27,8 +27,6 @@ #include "chrome/common/web_application_info.h" #include "components/favicon/core/favicon_service.h" #include "content/public/browser/browser_context.h" -#include "content/public/browser/utility_process_host.h" -#include "content/public/browser/utility_process_host_client.h" #include "content/public/browser/web_contents.h" #include "content/public/common/service_manager_connection.h" #include "extensions/browser/api/management/management_api.h" 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 c4cae1b7845..e144c34a723 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_browsertest.cc @@ -216,10 +216,8 @@ class ExtensionManagementApiEscalationTest : function->SetRenderFrameHost(browser()->tab_strip_model()-> GetActiveWebContents()->GetMainFrame()); bool response = util::RunFunction( - function.get(), - base::StringPrintf("[\"%s\", %s]", kId, enabled_string), - browser(), - util::NONE); + function.get(), base::StringPrintf("[\"%s\", %s]", kId, enabled_string), + browser(), api_test_utils::NONE); if (expected_error.empty()) { EXPECT_EQ(true, response); } else { 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 15518413297..4ffb76c9097 100644 --- a/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/management/management_api_unittest.cc @@ -81,7 +81,7 @@ bool ManagementApiUnitTest::RunFunction( const base::ListValue& args) { return extension_function_test_utils::RunFunction( function.get(), base::WrapUnique(args.DeepCopy()), browser(), - extension_function_test_utils::NONE); + api_test_utils::NONE); } void ManagementApiUnitTest::SetUp() { diff --git a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc index b2e8d86bea0..b2acf5e8de8 100644 --- a/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc +++ b/chromium/chrome/browser/extensions/api/media_galleries/media_galleries_apitest.cc @@ -27,7 +27,7 @@ #include "chrome/browser/ui/extensions/app_launch_params.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/common/chrome_paths.h" -#include "components/nacl/common/features.h" +#include "components/nacl/common/buildflags.h" #include "components/storage_monitor/storage_info.h" #include "components/storage_monitor/storage_monitor.h" #include "content/public/browser/web_contents.h" 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 46218419192..4b96ce3fc8f 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 @@ -4,6 +4,8 @@ #include "chrome/browser/extensions/api/media_perception_private/media_perception_api_delegate_chromeos.h" +#include "base/bind.h" +#include "chrome/browser/browser_process.h" #include "chrome/browser/component_updater/cros_component_installer.h" namespace media_perception = extensions::api::media_perception_private; @@ -30,6 +32,13 @@ std::string GetComponentNameForComponentType( return ""; } +void OnLoadComponent( + MediaPerceptionAPIDelegate::LoadCrOSComponentCallback load_callback, + component_updater::CrOSComponentManager::Error error, + const base::FilePath& mount_point) { + std::move(load_callback).Run(mount_point); +} + } // namespace MediaPerceptionAPIDelegateChromeOS::MediaPerceptionAPIDelegateChromeOS() = @@ -43,7 +52,7 @@ void MediaPerceptionAPIDelegateChromeOS::LoadCrOSComponent( g_browser_process->platform_part()->cros_component_manager()->Load( GetComponentNameForComponentType(type), component_updater::CrOSComponentManager::MountPolicy::kMount, - std::move(load_callback)); + base::BindOnce(OnLoadComponent, std::move(load_callback))); } } // namespace extensions 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 eeaa8191412..37f434a3de3 100644 --- a/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc +++ b/chromium/chrome/browser/extensions/api/messaging/chrome_messaging_delegate.cc @@ -82,7 +82,13 @@ std::unique_ptr<base::DictionaryValue> ChromeMessagingDelegate::MaybeGetTabInfo( // Only the tab id is useful to platform apps for internal use. The // unnecessary bits will be stripped out in // MessagingBindings::DispatchOnConnect(). - return ExtensionTabUtil::CreateTabObject(web_contents)->ToValue(); + // Note: We don't bother scrubbing the tab object, because this is only + // reached as a result of a tab (or content script) messaging the extension. + // We need the extension to see the sender so that it can validate if it + // trusts it or not. + return ExtensionTabUtil::CreateTabObject( + web_contents, ExtensionTabUtil::kDontScrubTab, nullptr) + ->ToValue(); } return nullptr; } diff --git a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.cc b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.cc index 17963d18b30..7171d6263c3 100644 --- a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.cc +++ b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.cc @@ -36,11 +36,6 @@ IncognitoConnectabilityInfoBarDelegate:: } } -infobars::InfoBarDelegate::Type -IncognitoConnectabilityInfoBarDelegate::GetInfoBarType() const { - return PAGE_ACTION_TYPE; -} - infobars::InfoBarDelegate::InfoBarIdentifier IncognitoConnectabilityInfoBarDelegate::GetIdentifier() const { return INCOGNITO_CONNECTABILITY_INFOBAR_DELEGATE; diff --git a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.h b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.h index 8b067019516..002dfe9c733 100644 --- a/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.h +++ b/chromium/chrome/browser/extensions/api/messaging/incognito_connectability_infobar_delegate.h @@ -36,7 +36,6 @@ class IncognitoConnectabilityInfoBarDelegate : public ConfirmInfoBarDelegate { ~IncognitoConnectabilityInfoBarDelegate() override; // ConfirmInfoBarDelegate: - Type GetInfoBarType() const override; infobars::InfoBarDelegate::InfoBarIdentifier GetIdentifier() const override; base::string16 GetMessageText() const override; base::string16 GetButtonLabel(InfoBarButton button) const override; 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 a0cf87625fd..53effb4a1dd 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 @@ -24,7 +24,6 @@ #include "base/strings/stringprintf.h" #include "base/test/test_timeouts.h" #include "base/threading/platform_thread.h" -#include "base/threading/sequenced_worker_pool.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/messaging/native_messaging_test_util.h" 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 ec99eaed500..0d36259d062 100644 --- a/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc +++ b/chromium/chrome/browser/extensions/api/messaging/native_process_launcher.cc @@ -16,7 +16,6 @@ #include "base/memory/ref_counted.h" #include "base/strings/stringprintf.h" #include "base/task_scheduler/post_task.h" -#include "base/threading/sequenced_worker_pool.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/messaging/native_messaging_host_manifest.h" #include "chrome/common/chrome_paths.h" @@ -228,8 +227,8 @@ void NativeProcessLauncherImpl::Core::PostErrorResult( content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, - this, callback, error, Passed(base::Process()), - Passed(base::File()), Passed(base::File()))); + this, callback, error, base::Process(), base::File(), + base::File())); } void NativeProcessLauncherImpl::Core::PostResult( @@ -240,8 +239,8 @@ void NativeProcessLauncherImpl::Core::PostResult( content::BrowserThread::PostTask( content::BrowserThread::IO, FROM_HERE, base::BindOnce(&NativeProcessLauncherImpl::Core::CallCallbackOnIOThread, - this, callback, RESULT_SUCCESS, Passed(&process), - Passed(&read_file), Passed(&write_file))); + this, callback, RESULT_SUCCESS, std::move(process), + std::move(read_file), std::move(write_file))); } NativeProcessLauncherImpl::NativeProcessLauncherImpl( diff --git a/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc b/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc index e9994eab59b..ae13ce020fb 100644 --- a/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc +++ b/chromium/chrome/browser/extensions/api/networking_config_chromeos_apitest_chromeos.cc @@ -25,8 +25,8 @@ #include "extensions/test/result_catcher.h" #include "net/base/net_errors.h" #include "third_party/cros_system_api/dbus/service_constants.h" -#include "ui/message_center/notification.h" -#include "ui/message_center/notification_delegate.h" +#include "ui/message_center/public/cpp/notification.h" +#include "ui/message_center/public/cpp/notification_delegate.h" using chromeos::DBusThreadManager; using chromeos::NetworkPortalDetector; @@ -82,8 +82,7 @@ class NetworkingConfigTest content::RunAllPendingInMessageLoop(); network_portal_detector_ = new NetworkPortalDetectorImpl( - g_browser_process->system_request_context(), - true /* create_notification_controller */); + test_loader_factory(), true /* create_notification_controller */); chromeos::network_portal_detector::InitializeForTesting( network_portal_detector_); network_portal_detector_->Enable(false /* start_detection */); diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_browsertest.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_browsertest.cc index a03527e9a0d..9ab7402b18d 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_browsertest.cc @@ -8,7 +8,7 @@ #include "base/run_loop.h" #include "base/task_scheduler/post_task.h" #include "chrome/browser/extensions/api/networking_private/networking_private_credentials_getter.h" -#include "chrome/services/wifi_util_win/public/interfaces/wifi_credentials_getter.mojom.h" +#include "chrome/services/wifi_util_win/public/mojom/wifi_credentials_getter.mojom.h" #include "chrome/test/base/in_process_browser_test.h" #include "content/public/browser/browser_thread.h" diff --git a/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc index 467a374a407..8a1bab0998d 100644 --- a/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc +++ b/chromium/chrome/browser/extensions/api/networking_private/networking_private_credentials_getter_win.cc @@ -11,8 +11,8 @@ #include "base/macros.h" #include "base/strings/string_piece.h" #include "chrome/browser/extensions/api/networking_private/networking_private_crypto.h" -#include "chrome/services/wifi_util_win/public/interfaces/constants.mojom.h" -#include "chrome/services/wifi_util_win/public/interfaces/wifi_credentials_getter.mojom.h" +#include "chrome/services/wifi_util_win/public/mojom/constants.mojom.h" +#include "chrome/services/wifi_util_win/public/mojom/wifi_credentials_getter.mojom.h" #include "content/public/browser/browser_thread.h" #include "content/public/common/service_manager_connection.h" #include "services/service_manager/public/cpp/connector.h" diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.cc b/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.cc index 5df72d7fce9..53b6a30f029 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.cc +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_display_helper.cc @@ -11,7 +11,7 @@ #include "chrome/browser/notifications/notification_display_service.h" #include "chrome/browser/notifications/notification_display_service_factory.h" #include "chrome/browser/notifications/notification_handler.h" -#include "ui/message_center/notification.h" +#include "ui/message_center/public/cpp/notification.h" #include "url/gurl.h" namespace extensions { diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc index 0a29eb6e9e4..da8e0798932 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.cc @@ -12,13 +12,15 @@ #include "chrome/browser/extensions/api/notifications/extension_notification_display_helper.h" #include "chrome/browser/extensions/api/notifications/extension_notification_display_helper_factory.h" #include "chrome/browser/notifications/notification_common.h" +#include "chrome/browser/notifications/notifier_state_tracker.h" +#include "chrome/browser/notifications/notifier_state_tracker_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/api/notifications.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/app_window/native_app_window.h" #include "extensions/common/constants.h" -#include "ui/message_center/notifier_id.h" +#include "ui/message_center/public/cpp/notifier_id.h" #include "url/gurl.h" namespace extensions { @@ -107,6 +109,14 @@ void ExtensionNotificationHandler::OnClick( std::move(completed_closure).Run(); } +void ExtensionNotificationHandler::DisableNotifications(Profile* profile, + const GURL& origin) { + message_center::NotifierId notifier_id( + message_center::NotifierId::APPLICATION, origin.host()); + NotifierStateTrackerFactory::GetForProfile(profile)->SetNotifierEnabled( + notifier_id, false /* enabled */); +} + void ExtensionNotificationHandler::SendEvent( Profile* profile, const std::string& extension_id, diff --git a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h index 062dab0ac8a..60464d79f35 100644 --- a/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h +++ b/chromium/chrome/browser/extensions/api/notifications/extension_notification_handler.h @@ -36,6 +36,7 @@ class ExtensionNotificationHandler : public NotificationHandler { const base::Optional<int>& action_index, const base::Optional<base::string16>& reply, base::OnceClosure completed_closure) override; + void DisableNotifications(Profile* profile, const GURL& origin) override; protected: // Overriden in unit tests. 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 03dcc746162..607fd500580 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 @@ -72,7 +72,7 @@ TEST_F(ExtensionNotificationHandlerTest, CloseHandler) { handler.SetTestExpectations(kChromeExtensionId, "notifications.onClosed", 2); handler.OnClose(profile.get(), GURL(kChromeExtensionOrigin), kChromeNotificationId, false /* by_user */, - base::BindOnce(&base::DoNothing)); + base::DoNothing()); } TEST_F(ExtensionNotificationHandlerTest, ClickHandler) { @@ -84,7 +84,7 @@ TEST_F(ExtensionNotificationHandlerTest, ClickHandler) { handler.SetTestExpectations(kChromeExtensionId, "notifications.onClicked", 1); handler.OnClick(profile.get(), GURL(kChromeExtensionOrigin), kChromeNotificationId, base::nullopt /* action_index */, - base::nullopt /* reply */, base::BindOnce(&base::DoNothing)); + base::nullopt /* reply */, base::DoNothing()); } TEST_F(ExtensionNotificationHandlerTest, ClickHandlerButton) { @@ -97,7 +97,7 @@ TEST_F(ExtensionNotificationHandlerTest, ClickHandlerButton) { "notifications.onButtonClicked", 2); handler.OnClick(profile.get(), GURL(kChromeExtensionOrigin), kChromeNotificationId, 1 /* action_index */, - base::nullopt /* reply */, base::BindOnce(&base::DoNothing)); + base::nullopt /* reply */, base::DoNothing()); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc index fb63bc5e496..fa154f233e9 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_api.cc @@ -48,10 +48,11 @@ #include "ui/gfx/image/image_skia_operations.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/gfx/skia_util.h" -#include "ui/message_center/notification.h" -#include "ui/message_center/notification_delegate.h" -#include "ui/message_center/notifier_id.h" +#include "ui/message_center/public/cpp/features.h" #include "ui/message_center/public/cpp/message_center_constants.h" +#include "ui/message_center/public/cpp/notification.h" +#include "ui/message_center/public/cpp/notification_delegate.h" +#include "ui/message_center/public/cpp/notifier_id.h" #include "url/gurl.h" using message_center::NotifierId; @@ -352,15 +353,19 @@ bool NotificationsApiFunction::CreateNotification( if (has_list_items) { using api::notifications::NotificationItem; for (const NotificationItem& api_item : *options->items) { - optional_fields.items.push_back(message_center::NotificationItem( - base::UTF8ToUTF16(api_item.title), - base::UTF8ToUTF16(api_item.message))); + optional_fields.items.push_back({base::UTF8ToUTF16(api_item.title), + base::UTF8ToUTF16(api_item.message)}); } } if (options->is_clickable.get()) optional_fields.clickable = *options->is_clickable; + optional_fields.settings_button_handler = + base::FeatureList::IsEnabled(message_center::kNewStyleNotifications) + ? message_center::SettingsButtonHandler::INLINE + : message_center::SettingsButtonHandler::NONE; + // TODO(crbug.com/772004): Remove the manual limitation in favor of an IDL // annotation once supported. if (id.size() > kNotificationIdLengthLimit) { @@ -510,9 +515,8 @@ bool NotificationsApiFunction::UpdateNotification( std::vector<message_center::NotificationItem> items; using api::notifications::NotificationItem; for (const NotificationItem& api_item : *options->items) { - items.push_back(message_center::NotificationItem( - base::UTF8ToUTF16(api_item.title), - base::UTF8ToUTF16(api_item.message))); + items.push_back({base::UTF8ToUTF16(api_item.title), + base::UTF8ToUTF16(api_item.message)}); } notification->set_items(items); } diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_api.h b/chromium/chrome/browser/extensions/api/notifications/notifications_api.h index 74278ac150f..b52400a65a6 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_api.h +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_api.h @@ -11,7 +11,7 @@ #include "chrome/browser/extensions/chrome_extension_function.h" #include "chrome/common/extensions/api/notifications.h" #include "extensions/browser/extension_function.h" -#include "ui/message_center/notification_types.h" +#include "ui/message_center/public/cpp/notification_types.h" namespace message_center { class Notification; diff --git a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc index 6b34b68c345..d999be59789 100644 --- a/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc +++ b/chromium/chrome/browser/extensions/api/notifications/notifications_apitest.cc @@ -38,8 +38,8 @@ #include "extensions/common/features/feature.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" -#include "ui/message_center/notification.h" -#include "ui/message_center/notifier_id.h" +#include "ui/message_center/public/cpp/notification.h" +#include "ui/message_center/public/cpp/notifier_id.h" #if defined(OS_MACOSX) #include "base/mac/mac_util.h" @@ -311,7 +311,8 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestGetPermissionLevel) { notification_function->set_has_callback(true); std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( - notification_function.get(), "[]", browser(), utils::NONE)); + notification_function.get(), "[]", browser(), + extensions::api_test_utils::NONE)); EXPECT_EQ(base::Value::Type::STRING, result->type()); std::string permission_level; @@ -334,7 +335,8 @@ IN_PROC_BROWSER_TEST_F(NotificationsApiTest, TestGetPermissionLevel) { GetNotifierStateTracker()->SetNotifierEnabled(notifier_id, false); std::unique_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( - notification_function.get(), "[]", browser(), utils::NONE)); + notification_function.get(), "[]", browser(), + extensions::api_test_utils::NONE)); EXPECT_EQ(base::Value::Type::STRING, result->type()); std::string permission_level; 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 bc265038114..0a6441b4d03 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 @@ -72,9 +72,9 @@ PageCaptureSaveAsMHTMLFunction::PageCaptureSaveAsMHTMLFunction() { PageCaptureSaveAsMHTMLFunction::~PageCaptureSaveAsMHTMLFunction() { if (mhtml_file_.get()) { - BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, - base::BindOnce(&ClearFileReferenceOnIOThread, - base::Passed(&mhtml_file_))); + BrowserThread::PostTask( + BrowserThread::IO, FROM_HERE, + base::BindOnce(&ClearFileReferenceOnIOThread, std::move(mhtml_file_))); } } diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc index eebc8e3692e..f1b79559ce1 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_api.cc @@ -192,8 +192,50 @@ PasswordsPrivateExportPasswordsFunction::Run() { PasswordsPrivateDelegate* delegate = PasswordsPrivateDelegateFactory::GetForBrowserContext(browser_context(), true /* create */); - delegate->ExportPasswords(GetAssociatedWebContents()); + delegate->ExportPasswords( + base::BindOnce( + &PasswordsPrivateExportPasswordsFunction::ExportRequestCompleted, + this), + GetAssociatedWebContents()); + return RespondLater(); +} + +void PasswordsPrivateExportPasswordsFunction::ExportRequestCompleted( + const std::string& error) { + if (error.empty()) + Respond(NoArguments()); + else + Error(error); +} + +//////////////////////////////////////////////////////////////////////////////// +// PasswordsPrivateCancelExportPasswordsFunction + +PasswordsPrivateCancelExportPasswordsFunction:: + ~PasswordsPrivateCancelExportPasswordsFunction() {} + +ExtensionFunction::ResponseAction +PasswordsPrivateCancelExportPasswordsFunction::Run() { + PasswordsPrivateDelegate* delegate = + PasswordsPrivateDelegateFactory::GetForBrowserContext(browser_context(), + true /* create */); + delegate->CancelExportPasswords(); return RespondNow(NoArguments()); } +//////////////////////////////////////////////////////////////////////////////// +// PasswordsPrivateRequestExportProgressStatusFunction + +PasswordsPrivateRequestExportProgressStatusFunction:: + ~PasswordsPrivateRequestExportProgressStatusFunction() {} + +ExtensionFunction::ResponseAction +PasswordsPrivateRequestExportProgressStatusFunction::Run() { + PasswordsPrivateDelegate* delegate = + PasswordsPrivateDelegateFactory::GetForBrowserContext(browser_context(), + true /* create */); + return RespondNow(OneArgument(std::make_unique<base::Value>( + ToString(delegate->GetExportProgressStatus())))); +} + } // namespace extensions 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 59f7e3caf2a..f541487c4f4 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 @@ -155,9 +155,45 @@ class PasswordsPrivateExportPasswordsFunction ResponseAction Run() override; private: + void ExportRequestCompleted(const std::string& error); + DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateExportPasswordsFunction); }; +class PasswordsPrivateCancelExportPasswordsFunction + : public UIThreadExtensionFunction { + public: + PasswordsPrivateCancelExportPasswordsFunction() {} + DECLARE_EXTENSION_FUNCTION("passwordsPrivate.cancelExportPasswords", + PASSWORDSPRIVATE_CANCELEXPORTPASSWORDS); + + protected: + ~PasswordsPrivateCancelExportPasswordsFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateCancelExportPasswordsFunction); +}; + +class PasswordsPrivateRequestExportProgressStatusFunction + : public UIThreadExtensionFunction { + public: + PasswordsPrivateRequestExportProgressStatusFunction() {} + DECLARE_EXTENSION_FUNCTION("passwordsPrivate.requestExportProgressStatus", + PASSWORDSPRIVATE_REQUESTEXPORTPROGRESSSTATUS); + + protected: + ~PasswordsPrivateRequestExportProgressStatusFunction() override; + + // ExtensionFunction overrides. + ResponseAction Run() override; + + private: + DISALLOW_COPY_AND_ASSIGN(PasswordsPrivateRequestExportProgressStatusFunction); +}; + } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_PASSWORDS_PRIVATE_API_H_ 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 09c69a450f0..6a1ac5b9d6b 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 @@ -150,15 +150,30 @@ class TestDelegate : public PasswordsPrivateDelegate { importPasswordsTriggered = true; } - void ExportPasswords(content::WebContents* web_contents) override { + void ExportPasswords(base::OnceCallback<void(const std::string&)> callback, + content::WebContents* web_contents) override { // The testing of password exporting itself should be handled via // |PasswordManagerPorter|. exportPasswordsTriggered = true; + std::move(callback).Run(std::string()); + } + + void CancelExportPasswords() override { + cancelExportPasswordsTriggered = true; + } + + api::passwords_private::ExportProgressStatus GetExportProgressStatus() + override { + // The testing of password exporting itself should be handled via + // |PasswordManagerPorter|. + return api::passwords_private::ExportProgressStatus:: + EXPORT_PROGRESS_STATUS_IN_PROGRESS; } // Flags for detecting whether import/export operations have been invoked. bool importPasswordsTriggered = false; bool exportPasswordsTriggered = false; + bool cancelExportPasswordsTriggered = false; private: // The current list of entries/exceptions. Cached here so that when new @@ -220,6 +235,10 @@ class PasswordsPrivateApiTest : public ExtensionApiTest { return s_test_delegate_->exportPasswordsTriggered; } + bool cancelExportPasswordsWasTriggered() { + return s_test_delegate_->cancelExportPasswordsTriggered; + } + private: static TestDelegate* s_test_delegate_; @@ -281,4 +300,17 @@ IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest, ExportPasswords) { } } +IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest, CancelExportPasswords) { + EXPECT_FALSE(cancelExportPasswordsWasTriggered()); + EXPECT_TRUE(RunPasswordsSubtest("cancelExportPasswords")) << message_; + + if (!ExtensionApiTest::ExtensionSubtestsAreSkipped()) { + EXPECT_TRUE(cancelExportPasswordsWasTriggered()); + } +} + +IN_PROC_BROWSER_TEST_F(PasswordsPrivateApiTest, RequestExportProgressStatus) { + EXPECT_TRUE(RunPasswordsSubtest("requestExportProgressStatus")) << message_; +} + } // namespace extensions 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 4ac97e242d3..3b921ff9bc8 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 @@ -17,6 +17,7 @@ #include "chrome/browser/ui/passwords/password_ui_view.h" #include "chrome/common/extensions/api/passwords_private.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/password_manager/core/browser/ui/export_progress_status.h" #include "extensions/browser/extension_function.h" namespace content { @@ -76,8 +77,18 @@ class PasswordsPrivateDelegate : public KeyedService { virtual void ImportPasswords(content::WebContents* web_contents) = 0; // Trigger the password export procedure, allowing the user to save a file - // containing their passwords. - virtual void ExportPasswords(content::WebContents* web_contents) = 0; + // containing their passwords. |callback| will be called with an error + // message if the request is rejected, because another export is in progress. + virtual void ExportPasswords( + base::OnceCallback<void(const std::string&)> callback, + content::WebContents* web_contents) = 0; + + // Cancel any ongoing export. + virtual void CancelExportPasswords() = 0; + + // Get the most recent progress status. + virtual api::passwords_private::ExportProgressStatus + GetExportProgressStatus() = 0; }; } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc index 30280a6a7d5..8b975a1f16c 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.cc @@ -31,6 +31,43 @@ #include "chrome/browser/password_manager/password_manager_util_mac.h" #endif +namespace { + +// The error message returned to the UI when Chrome refuses to start multiple +// exports. +const char kExportInProgress[] = "in-progress"; +// The error message returned to the UI when the user fails to reauthenticate. +const char kReauthenticationFailed[] = "reauth-failed"; + +// Map password_manager::ExportProgressStatus to +// extensions::api::passwords_private::ExportProgressStatus. +extensions::api::passwords_private::ExportProgressStatus ConvertStatus( + password_manager::ExportProgressStatus status) { + switch (status) { + case password_manager::ExportProgressStatus::NOT_STARTED: + return extensions::api::passwords_private::ExportProgressStatus:: + EXPORT_PROGRESS_STATUS_NOT_STARTED; + case password_manager::ExportProgressStatus::IN_PROGRESS: + return extensions::api::passwords_private::ExportProgressStatus:: + EXPORT_PROGRESS_STATUS_IN_PROGRESS; + case password_manager::ExportProgressStatus::SUCCEEDED: + return extensions::api::passwords_private::ExportProgressStatus:: + EXPORT_PROGRESS_STATUS_SUCCEEDED; + case password_manager::ExportProgressStatus::FAILED_CANCELLED: + return extensions::api::passwords_private::ExportProgressStatus:: + EXPORT_PROGRESS_STATUS_FAILED_CANCELLED; + case password_manager::ExportProgressStatus::FAILED_WRITE_FAILED: + return extensions::api::passwords_private::ExportProgressStatus:: + EXPORT_PROGRESS_STATUS_FAILED_WRITE_FAILED; + } + + NOTREACHED(); + return extensions::api::passwords_private::ExportProgressStatus:: + EXPORT_PROGRESS_STATUS_NONE; +} + +} // namespace + namespace extensions { PasswordsPrivateDelegateImpl::PasswordsPrivateDelegateImpl(Profile* profile) @@ -38,7 +75,10 @@ PasswordsPrivateDelegateImpl::PasswordsPrivateDelegateImpl(Profile* profile) password_manager_presenter_( std::make_unique<PasswordManagerPresenter>(this)), password_manager_porter_(std::make_unique<PasswordManagerPorter>( - password_manager_presenter_.get())), + password_manager_presenter_.get(), + base::BindRepeating( + &PasswordsPrivateDelegateImpl::OnPasswordsExportProgress, + base::Unretained(this)))), password_access_authenticator_( base::BindRepeating(&PasswordsPrivateDelegateImpl::OsReauthCall, base::Unretained(this))), @@ -132,7 +172,8 @@ void PasswordsPrivateDelegateImpl::RequestShowPasswordInternal( // TODO(stevenjb): Pass this directly to RequestShowPassword(); see // crbug.com/495290. web_contents_ = web_contents; - if (!password_access_authenticator_.EnsureUserIsAuthenticated()) { + if (!password_access_authenticator_.EnsureUserIsAuthenticated( + password_manager::ReauthPurpose::VIEW_PASSWORD)) { return; } @@ -140,11 +181,13 @@ void PasswordsPrivateDelegateImpl::RequestShowPasswordInternal( password_manager_presenter_->RequestShowPassword(index); } -bool PasswordsPrivateDelegateImpl::OsReauthCall() { +bool PasswordsPrivateDelegateImpl::OsReauthCall( + password_manager::ReauthPurpose purpose) { #if defined(OS_WIN) - return password_manager_util_win::AuthenticateUser(GetNativeWindow()); + return password_manager_util_win::AuthenticateUser(GetNativeWindow(), + purpose); #elif defined(OS_MACOSX) - return password_manager_util_mac::AuthenticateUser(); + return password_manager_util_mac::AuthenticateUser(purpose); #else return true; #endif @@ -240,18 +283,31 @@ void PasswordsPrivateDelegateImpl::ImportPasswords( } void PasswordsPrivateDelegateImpl::ExportPasswords( + base::OnceCallback<void(const std::string&)> callback, content::WebContents* web_contents) { // Save |web_contents| so that it can be used later when GetNativeWindow() is // called. Note: This is safe because the |web_contents| is used before // exiting this method. TODO(crbug.com/495290): Pass the native window // directly to the reauth-handling code. web_contents_ = web_contents; - if (!password_access_authenticator_.ForceUserReauthentication()) { + if (!password_access_authenticator_.ForceUserReauthentication( + password_manager::ReauthPurpose::EXPORT)) { + std::move(callback).Run(kReauthenticationFailed); return; } password_manager_porter_->set_web_contents(web_contents); - password_manager_porter_->Store(); + bool accepted = password_manager_porter_->Store(); + std::move(callback).Run(accepted ? std::string() : kExportInProgress); +} + +void PasswordsPrivateDelegateImpl::CancelExportPasswords() { + password_manager_porter_->CancelStore(); +} + +api::passwords_private::ExportProgressStatus +PasswordsPrivateDelegateImpl::GetExportProgressStatus() { + return ConvertStatus(password_manager_porter_->GetExportProgressStatus()); } #if !defined(OS_ANDROID) @@ -261,13 +317,23 @@ gfx::NativeWindow PasswordsPrivateDelegateImpl::GetNativeWindow() const { } #endif +void PasswordsPrivateDelegateImpl::OnPasswordsExportProgress( + password_manager::ExportProgressStatus status, + const std::string& folder_name) { + PasswordsPrivateEventRouter* router = + PasswordsPrivateEventRouterFactory::GetForProfile(profile_); + if (router) { + router->OnPasswordsExportProgress(ConvertStatus(status), folder_name); + } +} + void PasswordsPrivateDelegateImpl::Shutdown() { password_manager_presenter_.reset(); password_manager_porter_.reset(); } void PasswordsPrivateDelegateImpl::SetOsReauthCallForTesting( - base::RepeatingCallback<bool()> os_reauth_call) { + PasswordAccessAuthenticator::ReauthCallback os_reauth_call) { password_access_authenticator_.SetOsReauthCallForTesting( std::move(os_reauth_call)); } 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 a7c7e4a6a3f..c9d02bcb6d0 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 @@ -16,12 +16,14 @@ #include "base/observer_list.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/passwords_private/passwords_private_delegate.h" +#include "chrome/browser/password_manager/reauth_purpose.h" #include "chrome/browser/ui/passwords/password_access_authenticator.h" #include "chrome/browser/ui/passwords/password_manager_porter.h" #include "chrome/browser/ui/passwords/password_manager_presenter.h" #include "chrome/browser/ui/passwords/password_ui_view.h" #include "chrome/common/extensions/api/passwords_private.h" #include "components/keyed_service/core/keyed_service.h" +#include "components/password_manager/core/browser/ui/export_progress_status.h" #include "extensions/browser/extension_function.h" class Profile; @@ -51,7 +53,11 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, void RequestShowPassword(size_t index, content::WebContents* web_contents) override; void ImportPasswords(content::WebContents* web_contents) override; - void ExportPasswords(content::WebContents* web_contents) override; + void ExportPasswords(base::OnceCallback<void(const std::string&)> accepted, + content::WebContents* web_contents) override; + void CancelExportPasswords() override; + api::passwords_private::ExportProgressStatus GetExportProgressStatus() + override; // PasswordUIView implementation. Profile* GetProfile() override; @@ -68,12 +74,17 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, gfx::NativeWindow GetNativeWindow() const override; #endif + // Callback for when the password list has been written to the destination. + void OnPasswordsExportProgress(password_manager::ExportProgressStatus status, + const std::string& folder_name); + // KeyedService overrides: void Shutdown() override; // Use this in tests to mock the OS-level reauthentication. void SetOsReauthCallForTesting( - base::RepeatingCallback<bool()> os_reauth_call); + base::RepeatingCallback<bool(password_manager::ReauthPurpose)> + os_reauth_call); private: // Called after the lists are fetched. Once both lists have been set, the @@ -93,7 +104,7 @@ class PasswordsPrivateDelegateImpl : public PasswordsPrivateDelegate, // Triggers an OS-dependent UI to present OS account login challenge and // returns true if the user passed that challenge. - bool OsReauthCall(); + bool OsReauthCall(password_manager::ReauthPurpose purpose); // Not owned by this class. Profile* profile_; 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 18816b55a21..4b8102b3239 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 @@ -13,6 +13,7 @@ #include "base/macros.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" +#include "base/test/mock_callback.h" #include "base/values.h" #include "chrome/browser/extensions/api/passwords_private/passwords_private_delegate_impl.h" #include "chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h" @@ -27,6 +28,8 @@ #include "testing/gtest/include/gtest/gtest.h" using PasswordFormList = std::vector<std::unique_ptr<autofill::PasswordForm>>; +using ::testing::Ne; +using ::testing::StrictMock; namespace extensions { @@ -99,7 +102,9 @@ void PasswordEventObserver::OnBroadcastEvent(const extensions::Event& event) { enum class ReauthResult { PASS, FAIL }; -bool FakeOsReauthCall(bool* reauth_called, ReauthResult result) { +bool FakeOsReauthCall(bool* reauth_called, + ReauthResult result, + password_manager::ReauthPurpose purpose) { *reauth_called = true; return result == ReauthResult::PASS; } @@ -255,6 +260,8 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestFailedReauthOnView) { TEST_F(PasswordsPrivateDelegateImplTest, TestReauthOnExport) { SetUpPasswordStore({CreateSampleForm()}); + StrictMock<base::MockCallback<base::OnceCallback<void(const std::string&)>>> + mock_accepted; PasswordsPrivateDelegateImpl delegate(&profile_); // Spin the loop to allow PasswordStore tasks posted on the creation of @@ -265,17 +272,35 @@ TEST_F(PasswordsPrivateDelegateImplTest, TestReauthOnExport) { delegate.SetOsReauthCallForTesting(base::BindRepeating( &FakeOsReauthCall, &reauth_called, ReauthResult::PASS)); - delegate.ExportPasswords(nullptr); + EXPECT_CALL(mock_accepted, Run(std::string())).Times(2); + + delegate.ExportPasswords(mock_accepted.Get(), nullptr); EXPECT_TRUE(reauth_called); // Export should ignore previous reauthentication results. reauth_called = false; - delegate.ExportPasswords(nullptr); + delegate.ExportPasswords(mock_accepted.Get(), nullptr); EXPECT_TRUE(reauth_called); +} + +TEST_F(PasswordsPrivateDelegateImplTest, TestReauthFailedOnExport) { + SetUpPasswordStore({CreateSampleForm()}); + StrictMock<base::MockCallback<base::OnceCallback<void(const std::string&)>>> + mock_accepted; - // TODO(crbug.com/341477): Once the export flow has defined messages to UI, - // such as progress indication, intercept them with PasswordEventObserver and - // check that exporting is aborted if the authentication failed. + PasswordsPrivateDelegateImpl delegate(&profile_); + // Spin the loop to allow PasswordStore tasks posted on the creation of + // |delegate| to be completed. + base::RunLoop().RunUntilIdle(); + + EXPECT_CALL(mock_accepted, Run(std::string("reauth-failed"))); + + bool reauth_called = false; + delegate.SetOsReauthCallForTesting(base::BindRepeating( + &FakeOsReauthCall, &reauth_called, ReauthResult::FAIL)); + + delegate.ExportPasswords(mock_accepted.Get(), nullptr); + EXPECT_TRUE(reauth_called); } } // namespace extensions diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.cc b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.cc index ca05c357e70..3851d77d807 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.cc +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.cc @@ -42,10 +42,10 @@ void PasswordsPrivateEventRouter::SendSavedPasswordListToListeners() { // If there is nothing to send, return early. return; - std::unique_ptr<Event> extension_event( - new Event(events::PASSWORDS_PRIVATE_ON_SAVED_PASSWORDS_LIST_CHANGED, - api::passwords_private::OnSavedPasswordsListChanged::kEventName, - cached_saved_password_parameters_->CreateDeepCopy())); + auto extension_event = std::make_unique<Event>( + events::PASSWORDS_PRIVATE_ON_SAVED_PASSWORDS_LIST_CHANGED, + api::passwords_private::OnSavedPasswordsListChanged::kEventName, + cached_saved_password_parameters_->CreateDeepCopy()); event_router_->BroadcastEvent(std::move(extension_event)); } @@ -62,10 +62,10 @@ void PasswordsPrivateEventRouter::SendPasswordExceptionListToListeners() { // If there is nothing to send, return early. return; - std::unique_ptr<Event> extension_event(new Event( + auto extension_event = std::make_unique<Event>( events::PASSWORDS_PRIVATE_ON_PASSWORD_EXCEPTIONS_LIST_CHANGED, api::passwords_private::OnPasswordExceptionsListChanged::kEventName, - cached_password_exception_parameters_->CreateDeepCopy())); + cached_password_exception_parameters_->CreateDeepCopy()); event_router_->BroadcastEvent(std::move(extension_event)); } @@ -76,13 +76,30 @@ void PasswordsPrivateEventRouter::OnPlaintextPasswordFetched( params.index = index; params.plaintext_password = plaintext_password; - std::unique_ptr<base::ListValue> event_value(new base::ListValue); + auto event_value = std::make_unique<base::ListValue>(); event_value->Append(params.ToValue()); - std::unique_ptr<Event> extension_event(new Event( + auto extension_event = std::make_unique<Event>( events::PASSWORDS_PRIVATE_ON_PLAINTEXT_PASSWORD_RETRIEVED, api::passwords_private::OnPlaintextPasswordRetrieved::kEventName, - std::move(event_value))); + std::move(event_value)); + event_router_->BroadcastEvent(std::move(extension_event)); +} + +void PasswordsPrivateEventRouter::OnPasswordsExportProgress( + api::passwords_private::ExportProgressStatus status, + const std::string& folder_name) { + api::passwords_private::PasswordExportProgress params; + params.status = status; + params.folder_name = std::make_unique<std::string>(std::move(folder_name)); + + auto event_value = std::make_unique<base::ListValue>(); + event_value->Append(params.ToValue()); + + auto extension_event = std::make_unique<Event>( + events::PASSWORDS_PRIVATE_ON_PASSWORDS_FILE_EXPORT_PROGRESS, + api::passwords_private::OnPasswordsFileExportProgress::kEventName, + std::move(event_value)); event_router_->BroadcastEvent(std::move(extension_event)); } diff --git a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h index b1d529327d2..b4bcfa6284c 100644 --- a/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h +++ b/chromium/chrome/browser/extensions/api/passwords_private/passwords_private_event_router.h @@ -5,6 +5,10 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_PASSWORDS_PRIVATE_EVENT_ROUTER_H_ #define CHROME_BROWSER_EXTENSIONS_API_PASSWORDS_PRIVATE_PASSWORDS_PRIVATE_EVENT_ROUTER_H_ +#include <memory> +#include <string> +#include <vector> + #include "base/macros.h" #include "chrome/common/extensions/api/passwords_private.h" #include "components/keyed_service/core/keyed_service.h" @@ -41,6 +45,14 @@ class PasswordsPrivateEventRouter : public KeyedService { void OnPlaintextPasswordFetched(size_t index, const std::string& plaintext_password); + // Notifies listeners after the passwords have been written to the export + // destination. + // |folder_name| In case of failure to export, this will describe destination + // we tried to write on. + void OnPasswordsExportProgress( + api::passwords_private::ExportProgressStatus status, + const std::string& folder_name); + protected: explicit PasswordsPrivateEventRouter(content::BrowserContext* context); 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 28b90107c8b..a365158dbde 100644 --- a/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/permissions/permissions_api_unittest.cc @@ -59,8 +59,7 @@ class PermissionsAPIUnitTest : public ExtensionServiceTestWithInstall { new PermissionsContainsFunction()); function->set_extension(extension.get()); bool run_result = extension_function_test_utils::RunFunction( - function.get(), args_string, browser(), - extension_function_test_utils::NONE); + function.get(), args_string, browser(), api_test_utils::NONE); EXPECT_TRUE(run_result) << function->GetError(); bool has_permission; diff --git a/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc b/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc index 2964d6272fc..d66dd3a6f5b 100644 --- a/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc +++ b/chromium/chrome/browser/extensions/api/preference/preference_api_prefs_unittest.cc @@ -212,8 +212,8 @@ class ControlledPrefsInstallIncognitoPersistent new base::Value("val1")); InstallExtensionControlledPrefIncognito(extension1(), kPref1, new base::Value("val2")); - std::unique_ptr<PrefService> incog_prefs( - prefs_.CreateIncognitoPrefService()); + std::unique_ptr<PrefService> incog_prefs = + prefs_.CreateIncognitoPrefService(); std::string actual = incog_prefs->GetString(kPref1); EXPECT_EQ("val2", actual); } @@ -223,8 +223,8 @@ class ControlledPrefsInstallIncognitoPersistent std::string actual = prefs()->pref_service()->GetString(kPref1); EXPECT_EQ("val1", actual); // Incognito pref service shall see incognito values. - std::unique_ptr<PrefService> incog_prefs( - prefs_.CreateIncognitoPrefService()); + std::unique_ptr<PrefService> incog_prefs = + prefs_.CreateIncognitoPrefService(); actual = incog_prefs->GetString(kPref1); EXPECT_EQ("val2", actual); } @@ -243,8 +243,8 @@ class ControlledPrefsInstallIncognitoSessionOnly new base::Value("val1")); InstallExtensionControlledPrefIncognitoSessionOnly(extension1(), kPref1, new base::Value("val2")); - std::unique_ptr<PrefService> incog_prefs( - prefs_.CreateIncognitoPrefService()); + std::unique_ptr<PrefService> incog_prefs = + prefs_.CreateIncognitoPrefService(); std::string actual = incog_prefs->GetString(kPref1); EXPECT_EQ("val2", actual); } @@ -255,8 +255,8 @@ class ControlledPrefsInstallIncognitoSessionOnly // Incognito pref service shall see session-only incognito values only // during first run. Once the pref service was reloaded, all values shall be // discarded. - std::unique_ptr<PrefService> incog_prefs( - prefs_.CreateIncognitoPrefService()); + std::unique_ptr<PrefService> incog_prefs = + prefs_.CreateIncognitoPrefService(); actual = incog_prefs->GetString(kPref1); if (iteration_ == 0) { EXPECT_EQ("val2", actual); @@ -314,8 +314,8 @@ class ControlledPrefsNotifyWhenNeeded : public ExtensionControlledPrefsTest { registrar.Add(kPref1, observer.GetCallback()); MockPrefChangeCallback incognito_observer(prefs()->pref_service()); - std::unique_ptr<PrefService> incog_prefs( - prefs_.CreateIncognitoPrefService()); + std::unique_ptr<PrefService> incog_prefs = + prefs_.CreateIncognitoPrefService(); PrefChangeRegistrar incognito_registrar; incognito_registrar.Init(incog_prefs.get()); incognito_registrar.Add(kPref1, incognito_observer.GetCallback()); diff --git a/chromium/chrome/browser/extensions/api/processes/processes_api.cc b/chromium/chrome/browser/extensions/api/processes/processes_api.cc index 63c005ec295..4ec343e20b9 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_api.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_api.cc @@ -372,11 +372,12 @@ void ProcessesEventRouter::UpdateRefreshTypesFlagsBasedOnListeners() { refresh_types |= GetRefreshTypesFlagOnlyEssentialData(); } + const int64_t on_updated_types = GetRefreshTypesForProcessOptionalData(); if (HasEventListeners(api::processes::OnUpdated::kEventName)) - refresh_types |= GetRefreshTypesForProcessOptionalData(); + refresh_types |= on_updated_types; if (HasEventListeners(api::processes::OnUpdatedWithMemory::kEventName)) - refresh_types |= task_manager::REFRESH_TYPE_MEMORY; + refresh_types |= (on_updated_types | task_manager::REFRESH_TYPE_MEMORY); SetRefreshTypesFlags(refresh_types); } diff --git a/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc b/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc index d75a4065760..42668f2615d 100644 --- a/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc +++ b/chromium/chrome/browser/extensions/api/processes/processes_apitest.cc @@ -9,6 +9,7 @@ #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_window.h" +#include "chrome/common/extensions/api/processes.h" #include "extensions/common/switches.h" #include "extensions/test/extension_test_message_listener.h" @@ -69,6 +70,48 @@ IN_PROC_BROWSER_TEST_F(ProcessesApiTest, ProcessesApiListeners) { EXPECT_EQ(0, GetListenersCount()); } +IN_PROC_BROWSER_TEST_F(ProcessesApiTest, OnUpdatedWithMemoryRefreshTypes) { + EXPECT_EQ(0, GetListenersCount()); + + // Load an extension that listen to the onUpdatedWithMemory. + ExtensionTestMessageListener listener("ready", false /* will_reply */); + const extensions::Extension* extension = + LoadExtension(test_data_dir_.AppendASCII("processes") + .AppendASCII("onupdated_with_memory")); + ASSERT_TRUE(extension); + ASSERT_TRUE(listener.WaitUntilSatisfied()); + + // The memory refresh type must be enabled now. + const task_manager::TaskManagerInterface* task_manager = + task_manager::TaskManagerInterface::GetTaskManager(); + EXPECT_EQ(1, GetListenersCount()); + extensions::EventRouter* event_router = + extensions::EventRouter::Get(profile()); + EXPECT_TRUE(event_router->HasEventListener( + extensions::api::processes::OnUpdatedWithMemory::kEventName)); + EXPECT_FALSE(event_router->HasEventListener( + extensions::api::processes::OnUpdated::kEventName)); + EXPECT_TRUE(task_manager->IsResourceRefreshEnabled( + task_manager::REFRESH_TYPE_MEMORY)); + + // Despite the fact that there are no onUpdated listeners, refresh types for + // CPU, Network, SQLite, V8 memory, and webcache stats should be enabled. + constexpr task_manager::RefreshType kOnUpdatedRefreshTypes[] = { + task_manager::REFRESH_TYPE_CPU, + task_manager::REFRESH_TYPE_NETWORK_USAGE, + task_manager::REFRESH_TYPE_SQLITE_MEMORY, + task_manager::REFRESH_TYPE_V8_MEMORY, + task_manager::REFRESH_TYPE_WEBCACHE_STATS, + }; + + for (const auto& type : kOnUpdatedRefreshTypes) + EXPECT_TRUE(task_manager->IsResourceRefreshEnabled(type)); + + // Unload the extensions and make sure the listeners count is updated. + UnloadExtension(extension->id()); + EXPECT_EQ(0, GetListenersCount()); +} + IN_PROC_BROWSER_TEST_F(ProcessesApiTest, CannotTerminateBrowserProcess) { ASSERT_TRUE(RunExtensionTest("processes/terminate-browser-process")) << message_; diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc index 780aafeeb1e..8efe3706631 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.cc @@ -26,7 +26,7 @@ #include "components/proxy_config/proxy_config_dictionary.h" #include "extensions/common/error_utils.h" #include "net/base/data_url.h" -#include "net/proxy/proxy_config.h" +#include "net/proxy_resolution/proxy_config.h" namespace extensions { @@ -378,16 +378,16 @@ std::unique_ptr<base::DictionaryValue> CreateProxyRulesDict( rules.ParseFromString(proxy_servers); switch (rules.type) { - case net::ProxyConfig::ProxyRules::TYPE_NO_RULES: + case net::ProxyConfig::ProxyRules::Type::EMPTY: return NULL; - case net::ProxyConfig::ProxyRules::TYPE_SINGLE_PROXY: + case net::ProxyConfig::ProxyRules::Type::PROXY_LIST: if (!rules.single_proxies.IsEmpty()) { extension_proxy_rules->Set( keys::field_name[keys::SCHEME_ALL], CreateProxyServerDict(rules.single_proxies.Get())); } break; - case net::ProxyConfig::ProxyRules::TYPE_PROXY_PER_SCHEME: + case net::ProxyConfig::ProxyRules::Type::PROXY_LIST_PER_SCHEME: if (!rules.proxies_for_http.IsEmpty()) { extension_proxy_rules->Set( keys::field_name[keys::SCHEME_HTTP], diff --git a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.h b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.h index f572165276e..43428988aa6 100644 --- a/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.h +++ b/chromium/chrome/browser/extensions/api/proxy/proxy_api_helpers.h @@ -11,7 +11,7 @@ #include <string> #include "components/proxy_config/proxy_prefs.h" -#include "net/proxy/proxy_config.h" +#include "net/proxy_resolution/proxy_config.h" class ProxyConfigDictionary; diff --git a/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc b/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc index 2999bdd5c46..a1f7840198a 100644 --- a/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc +++ b/chromium/chrome/browser/extensions/api/runtime/runtime_apitest.cc @@ -7,7 +7,6 @@ #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" -#include "chrome/browser/extensions/test_extension_dir.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/test/browser_test_utils.h" #include "extensions/browser/api/runtime/runtime_api.h" @@ -17,6 +16,7 @@ #include "extensions/browser/extension_registry.h" #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/test/result_catcher.h" +#include "extensions/test/test_extension_dir.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "url/url_constants.h" diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc index aba5cc99f59..872c24eba79 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_api.cc @@ -6,6 +6,7 @@ #include <stddef.h> +#include <algorithm> #include <memory> #include <utility> #include <vector> @@ -380,8 +381,8 @@ ExtensionFunction::ResponseAction SessionsGetDevicesFunction::Run() { ExtensionFunction::ResponseValue SessionsRestoreFunction::GetRestoredTabResult( content::WebContents* contents) { - std::unique_ptr<tabs::Tab> tab( - ExtensionTabUtil::CreateTabObject(contents, extension())); + std::unique_ptr<tabs::Tab> tab(ExtensionTabUtil::CreateTabObject( + contents, ExtensionTabUtil::kScrubTab, extension())); std::unique_ptr<api::sessions::Session> restored_session( CreateSessionModelHelper(base::Time::Now().ToTimeT(), std::move(tab), std::unique_ptr<windows::Window>())); @@ -390,14 +391,15 @@ ExtensionFunction::ResponseValue SessionsRestoreFunction::GetRestoredTabResult( ExtensionFunction::ResponseValue SessionsRestoreFunction::GetRestoredWindowResult(int window_id) { - WindowController* controller = NULL; + Browser* browser = nullptr; std::string error; - if (!windows_util::GetWindowFromWindowID(this, window_id, 0, &controller, - &error)) { + if (!windows_util::GetBrowserFromWindowID(this, window_id, 0, &browser, + &error)) { return Error(error); } std::unique_ptr<base::DictionaryValue> window_value( - controller->CreateWindowValueWithTabs(extension())); + ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), ExtensionTabUtil::kPopulateTabs)); std::unique_ptr<windows::Window> window( windows::Window::FromValue(*window_value)); return ArgumentList(Restore::Results::Create(*CreateSessionModelHelper( diff --git a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc index 6f68a4cd4d0..9d457c2dcae 100644 --- a/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc +++ b/chromium/chrome/browser/extensions/api/sessions/sessions_apitest.cc @@ -30,8 +30,6 @@ #include "components/browser_sync/profile_sync_service_mock.h" #include "components/sync/device_info/local_device_info_provider_mock.h" #include "components/sync/driver/sync_api_component_factory_mock.h" -#include "components/sync/model/attachments/attachment_id.h" -#include "components/sync/model/attachments/attachment_service_proxy_for_test.h" #include "components/sync/model/fake_sync_change_processor.h" #include "components/sync/model/sync_error_factory_mock.h" #include "components/sync_sessions/sessions_sync_manager.h" @@ -266,16 +264,14 @@ void ExtensionSessionsTest::CreateSessionModels() { sync_pb::EntitySpecifics entity; entity.mutable_session()->CopyFrom(meta); initial_data.push_back(syncer::SyncData::CreateRemoteData( - 1, entity, base::Time(), syncer::AttachmentIdList(), - syncer::AttachmentServiceProxyForTest::Create(), + 1, entity, base::Time(), sync_sessions::SessionsSyncManager::TagHashFromSpecifics( entity.session()))); for (size_t i = 0; i < tabs.size(); i++) { sync_pb::EntitySpecifics entity; entity.mutable_session()->CopyFrom(tabs[i]); initial_data.push_back(syncer::SyncData::CreateRemoteData( - i + 2, entity, base::Time(), syncer::AttachmentIdList(), - syncer::AttachmentServiceProxyForTest::Create(), + i + 2, entity, base::Time(), sync_sessions::SessionsSyncManager::TagHashFromSpecifics( entity.session()))); } @@ -329,7 +325,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionSessionsTest, std::unique_ptr<base::DictionaryValue> restored_window_session( utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( CreateFunction<SessionsRestoreFunction>(true).get(), "[\"tag3.3\"]", - browser_, utils::INCLUDE_INCOGNITO))); + browser_, api_test_utils::INCLUDE_INCOGNITO))); ASSERT_TRUE(restored_window_session); std::unique_ptr<base::ListValue> result( 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 12188832837..ea8c4d19412 100644 --- a/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc +++ b/chromium/chrome/browser/extensions/api/settings_private/prefs_util.cc @@ -284,6 +284,8 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[ash::prefs::kAccessibilityScreenMagnifierEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[ash::prefs::kAccessibilityScreenMagnifierScale] = + settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[ash::prefs::kAccessibilitySelectToSpeakEnabled] = settings_api::PrefType::PREF_TYPE_BOOLEAN; (*s_whitelist)[ash::prefs::kAccessibilityStickyKeysEnabled] = @@ -364,6 +366,10 @@ const PrefsUtil::TypedPrefMap& PrefsUtil::GetWhitelistedKeys() { settings_api::PrefType::PREF_TYPE_NUMBER; (*s_whitelist)[ash::prefs::kNightLightCustomEndTime] = settings_api::PrefType::PREF_TYPE_NUMBER; + (*s_whitelist)[ash::prefs::kDockedMagnifierEnabled] = + settings_api::PrefType::PREF_TYPE_BOOLEAN; + (*s_whitelist)[ash::prefs::kDockedMagnifierScale] = + settings_api::PrefType::PREF_TYPE_NUMBER; // Input method settings. (*s_whitelist)[::prefs::kLanguagePreloadEngines] = @@ -633,20 +639,24 @@ settings_private::SetPrefResult PrefsUtil::SetPref(const std::string& pref_name, switch (pref->GetType()) { case base::Value::Type::BOOLEAN: - case base::Value::Type::DOUBLE: case base::Value::Type::LIST: case base::Value::Type::DICTIONARY: pref_service->Set(pref_name, *value); break; - case base::Value::Type::INTEGER: { - // In JS all numbers are doubles. + case base::Value::Type::DOUBLE: + case base::Value::Type::INTEGER: + // Explicitly set the double value or the integer value. + // Otherwise if the number is a whole number like 2.0, it will + // automatically be of type INTEGER causing type mismatches in + // PrefService::SetUserPrefValue for doubles, and vice versa. double double_value; if (!value->GetAsDouble(&double_value)) return settings_private::SetPrefResult::PREF_TYPE_MISMATCH; - - pref_service->SetInteger(pref_name, static_cast<int>(double_value)); + if (pref->GetType() == base::Value::Type::DOUBLE) + pref_service->SetDouble(pref_name, double_value); + else + pref_service->SetInteger(pref_name, static_cast<int>(double_value)); break; - } case base::Value::Type::STRING: { std::string string_value; if (!value->GetAsString(&string_value)) 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 27fd02882f8..68b294cade7 100644 --- a/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc +++ b/chromium/chrome/browser/extensions/api/socket/udp_socket_unittest.cc @@ -15,17 +15,37 @@ #include "base/single_thread_task_runner.h" #include "base/test/test_timeouts.h" #include "base/threading/thread_task_runner_handle.h" +#include "chrome/browser/extensions/extension_service_test_base.h" #include "chrome/test/base/browser_with_test_window_test.h" +#include "content/public/browser/storage_partition.h" #include "extensions/browser/api/socket/udp_socket.h" #include "net/base/io_buffer.h" #include "net/base/ip_address.h" +#include "net/base/test_completion_callback.h" +#include "services/network/network_context.h" +#include "services/network/public/mojom/udp_socket.mojom.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { -// UDPSocketUnitTest exists solely to make it easier to pass a specific -// gtest_filter argument during development. -class UDPSocketUnitTest : public BrowserWithTestWindowTest { +class UDPSocketUnitTest : public extensions::ExtensionServiceTestBase { + protected: + // extensions::ExtensionServiceTestBase: + void SetUp() override { InitializeEmptyExtensionService(); } + + std::unique_ptr<UDPSocket> CreateSocket() { + network::mojom::NetworkContext* network_context = + content::BrowserContext::GetDefaultStoragePartition(profile()) + ->GetNetworkContext(); + network::mojom::UDPSocketPtrInfo socket; + network::mojom::UDPSocketReceiverPtr receiver_ptr; + network::mojom::UDPSocketReceiverRequest receiver_request = + mojo::MakeRequest(&receiver_ptr); + network_context->CreateUDPSocket(mojo::MakeRequest(&socket), + std::move(receiver_ptr)); + return std::make_unique<UDPSocket>( + std::move(socket), std::move(receiver_request), "abcdefghijklmnopqrst"); + } }; static void OnConnected(int result) { @@ -40,8 +60,8 @@ static void OnCompleted(int bytes_read, // Do nothing; don't care. } -static const char test_message[] = "$$TESTMESSAGETESTMESSAGETESTMESSAGETEST$$"; -static const int test_message_length = arraysize(test_message); +static const char kTestMessage[] = "$$TESTMESSAGETESTMESSAGETESTMESSAGETEST$$"; +static const int kTestMessageLength = arraysize(kTestMessage); net::AddressList CreateAddressList(const char* address_string, int port) { net::IPAddress ip; @@ -50,50 +70,69 @@ net::AddressList CreateAddressList(const char* address_string, int port) { } static void OnSendCompleted(int result) { - EXPECT_EQ(test_message_length, result); + EXPECT_EQ(kTestMessageLength, result); } -TEST(UDPSocketUnitTest, TestUDPSocketRecvFrom) { - base::MessageLoopForIO io_loop; // For RecvFrom to do its threaded work. - UDPSocket socket("abcdefghijklmnopqrst"); +TEST_F(UDPSocketUnitTest, TestUDPSocketRecvFrom) { + std::unique_ptr<UDPSocket> socket = CreateSocket(); // Confirm that we can call two RecvFroms in quick succession without // triggering crbug.com/146606. - socket.Connect(CreateAddressList("127.0.0.1", 40000), - base::Bind(&OnConnected)); - socket.RecvFrom(4096, base::Bind(&OnCompleted)); - socket.RecvFrom(4096, base::Bind(&OnCompleted)); + socket->Connect(CreateAddressList("127.0.0.1", 40000), + base::BindRepeating(&OnConnected)); + socket->RecvFrom(4096, base::BindRepeating(&OnCompleted)); + socket->RecvFrom(4096, base::BindRepeating(&OnCompleted)); } -TEST(UDPSocketUnitTest, TestUDPMulticastJoinGroup) { +TEST_F(UDPSocketUnitTest, TestUDPMulticastJoinGroup) { const char kGroup[] = "237.132.100.17"; - UDPSocket src("abcdefghijklmnopqrst"); - UDPSocket dest("abcdefghijklmnopqrst"); + std::unique_ptr<UDPSocket> src = CreateSocket(); + std::unique_ptr<UDPSocket> dest = CreateSocket(); - EXPECT_EQ(0, dest.Bind("0.0.0.0", 13333)); - EXPECT_EQ(0, dest.JoinGroup(kGroup)); - std::vector<std::string> groups = dest.GetJoinedGroups(); + { + net::TestCompletionCallback callback; + dest->Bind("0.0.0.0", 13333, callback.callback()); + EXPECT_EQ(net::OK, callback.WaitForResult()); + } + { + net::TestCompletionCallback callback; + dest->JoinGroup(kGroup, callback.callback()); + EXPECT_EQ(net::OK, callback.WaitForResult()); + } + std::vector<std::string> groups = dest->GetJoinedGroups(); EXPECT_EQ(static_cast<size_t>(1), groups.size()); EXPECT_EQ(kGroup, *groups.begin()); - EXPECT_NE(0, dest.LeaveGroup("237.132.100.13")); - EXPECT_EQ(0, dest.LeaveGroup(kGroup)); - groups = dest.GetJoinedGroups(); + { + net::TestCompletionCallback callback; + dest->LeaveGroup("237.132.100.13", callback.callback()); + EXPECT_NE(net::OK, callback.WaitForResult()); + } + { + net::TestCompletionCallback callback; + dest->LeaveGroup(kGroup, callback.callback()); + EXPECT_EQ(net::OK, callback.WaitForResult()); + } + groups = dest->GetJoinedGroups(); EXPECT_EQ(static_cast<size_t>(0), groups.size()); } -TEST(UDPSocketUnitTest, TestUDPMulticastTimeToLive) { +TEST_F(UDPSocketUnitTest, TestUDPMulticastTimeToLive) { const char kGroup[] = "237.132.100.17"; - UDPSocket socket("abcdefghijklmnopqrst"); - EXPECT_NE(0, socket.SetMulticastTimeToLive(-1)); // Negative TTL shall fail. - EXPECT_EQ(0, socket.SetMulticastTimeToLive(3)); - socket.Connect(CreateAddressList(kGroup, 13333), base::Bind(&OnConnected)); + std::unique_ptr<UDPSocket> socket = CreateSocket(); + + EXPECT_NE(0, socket->SetMulticastTimeToLive(-1)); // Negative TTL shall fail. + EXPECT_EQ(0, socket->SetMulticastTimeToLive(3)); + socket->Connect(CreateAddressList(kGroup, 13333), + base::BindRepeating(&OnConnected)); } -TEST(UDPSocketUnitTest, TestUDPMulticastLoopbackMode) { +TEST_F(UDPSocketUnitTest, TestUDPMulticastLoopbackMode) { const char kGroup[] = "237.132.100.17"; - UDPSocket socket("abcdefghijklmnopqrst"); - EXPECT_EQ(0, socket.SetMulticastLoopbackMode(false)); - socket.Connect(CreateAddressList(kGroup, 13333), base::Bind(&OnConnected)); + std::unique_ptr<UDPSocket> socket = CreateSocket(); + + EXPECT_EQ(0, socket->SetMulticastLoopbackMode(false)); + socket->Connect(CreateAddressList(kGroup, 13333), + base::BindRepeating(&OnConnected)); } // Send a test multicast packet every second. @@ -102,8 +141,8 @@ static void SendMulticastPacket(const base::Closure& quit_run_loop, UDPSocket* src, int result) { if (result == 0) { - scoped_refptr<net::IOBuffer> data = new net::WrappedIOBuffer(test_message); - src->Write(data, test_message_length, base::Bind(&OnSendCompleted)); + scoped_refptr<net::IOBuffer> data = new net::WrappedIOBuffer(kTestMessage); + src->Write(data, kTestMessageLength, base::BindRepeating(&OnSendCompleted)); base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&SendMulticastPacket, quit_run_loop, src, result), @@ -118,37 +157,48 @@ static void OnMulticastReadCompleted(const base::Closure& quit_run_loop, bool* packet_received, int count, scoped_refptr<net::IOBuffer> io_buffer, - bool socket_destroying) { - EXPECT_EQ(test_message_length, count); - EXPECT_EQ(0, strncmp(io_buffer->data(), test_message, test_message_length)); + bool socket_destroying, + const std::string& ip, + uint16_t port) { + EXPECT_EQ(kTestMessageLength, count); + EXPECT_EQ(0, strncmp(io_buffer->data(), kTestMessage, kTestMessageLength)); *packet_received = true; quit_run_loop.Run(); } -TEST(UDPSocketUnitTest, TestUDPMulticastRecv) { +TEST_F(UDPSocketUnitTest, TestUDPMulticastRecv) { const int kPort = 9999; const char kGroup[] = "237.132.100.17"; bool packet_received = false; - base::MessageLoopForIO io_loop; // For Read to do its threaded work. - UDPSocket dest("abcdefghijklmnopqrst"); - UDPSocket src("abcdefghijklmnopqrst"); - - base::RunLoop run_loop; + std::unique_ptr<UDPSocket> src = CreateSocket(); + std::unique_ptr<UDPSocket> dest = CreateSocket(); // Receiver - EXPECT_EQ(0, dest.Bind("0.0.0.0", kPort)); - EXPECT_EQ(0, dest.JoinGroup(kGroup)); - dest.Read(1024, base::Bind(&OnMulticastReadCompleted, run_loop.QuitClosure(), - &packet_received)); + { + net::TestCompletionCallback callback; + dest->Bind("0.0.0.0", kPort, callback.callback()); + EXPECT_EQ(net::OK, callback.WaitForResult()); + } + { + net::TestCompletionCallback callback; + dest->JoinGroup(kGroup, callback.callback()); + EXPECT_EQ(net::OK, callback.WaitForResult()); + } + base::RunLoop run_loop; + // |dest| is used with Bind(), so use RecvFrom() instead of Read(). + dest->RecvFrom(1024, + base::BindRepeating(&OnMulticastReadCompleted, + run_loop.QuitClosure(), &packet_received)); // Sender - EXPECT_EQ(0, src.SetMulticastTimeToLive(0)); - src.Connect(CreateAddressList(kGroup, kPort), - base::Bind(&SendMulticastPacket, run_loop.QuitClosure(), &src)); + EXPECT_EQ(0, src->SetMulticastTimeToLive(0)); + src->Connect(CreateAddressList(kGroup, kPort), + base::BindRepeating(&SendMulticastPacket, run_loop.QuitClosure(), + src.get())); // If not received within the test action timeout, quit the message loop. - io_loop.task_runner()->PostDelayedTask(FROM_HERE, run_loop.QuitClosure(), - TestTimeouts::action_timeout()); + base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( + FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout()); run_loop.Run(); 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 8997b290ed0..2e38a78801c 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 @@ -173,9 +173,8 @@ void ManagedValueStoreCache::ExtensionTracker::LoadSchemas( } GetExtensionFileTaskRunner()->PostTask( - FROM_HERE, - base::BindOnce(&ExtensionTracker::LoadSchemasOnFileTaskRunner, - base::Passed(&added), weak_factory_.GetWeakPtr())); + FROM_HERE, base::BindOnce(&ExtensionTracker::LoadSchemasOnFileTaskRunner, + std::move(added), weak_factory_.GetWeakPtr())); } bool ManagedValueStoreCache::ExtensionTracker::UsesManagedStorage( @@ -327,7 +326,7 @@ void ManagedValueStoreCache::OnPolicyUpdated(const policy::PolicyNamespace& ns, GetBackendTaskRunner()->PostTask( FROM_HERE, base::BindOnce(&ManagedValueStoreCache::UpdatePolicyOnBackend, base::Unretained(this), ns.component_id, - base::Passed(current.DeepCopy()))); + current.DeepCopy())); } // static diff --git a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc index b62b194dcff..7cc6951d468 100644 --- a/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc +++ b/chromium/chrome/browser/extensions/api/streams_private/streams_private_apitest.cc @@ -16,9 +16,10 @@ #include "chrome/common/extensions/api/streams_private.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/ui_test_utils.h" +#include "components/download/public/common/download_item.h" #include "components/prefs/pref_service.h" -#include "content/public/browser/download_item.h" #include "content/public/browser/download_manager.h" +#include "content/public/browser/download_request_utils.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "content/public/test/download_test_observer.h" @@ -35,10 +36,10 @@ using content::BrowserContext; using content::BrowserThread; -using content::DownloadItem; using content::DownloadManager; -using content::DownloadUrlParameters; using content::WebContents; +using download::DownloadItem; +using download::DownloadUrlParameters; using extensions::Event; using extensions::ExtensionSystem; using extensions::ResultCatcher; @@ -399,7 +400,7 @@ IN_PROC_BROWSER_TEST_F(StreamsPrivateApiTest, MAYBE_DirectDownload) { browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(web_contents); std::unique_ptr<DownloadUrlParameters> params( - DownloadUrlParameters::CreateForWebContentsMainFrame( + content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents, url, TRAFFIC_ANNOTATION_FOR_TESTS)); params->set_file_path(target_path); diff --git a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h index cb4ad6f0b90..3e792d1bf2c 100644 --- a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h +++ b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h @@ -15,7 +15,7 @@ #include "chrome/browser/sync_file_system/sync_status_code.h" #include "chrome/common/extensions/api/sync_file_system.h" #include "storage/browser/fileapi/file_system_url.h" -#include "third_party/WebKit/common/quota/quota_types.mojom.h" +#include "third_party/WebKit/public/mojom/quota/quota_types.mojom.h" namespace storage { class FileSystemContext; diff --git a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc index 4a19a726f23..2ff9bc7e96f 100644 --- a/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/sync_file_system/sync_file_system_browsertest.cc @@ -10,7 +10,6 @@ #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/task_scheduler/post_task.h" -#include "base/threading/sequenced_worker_pool.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/apps/app_browsertest_util.h" 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 44d733eacea..520f0c136d0 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 @@ -59,6 +59,7 @@ class TabCaptureApiTest : public ExtensionApiTest { class TabCaptureApiPixelTest : public TabCaptureApiTest { public: void SetUp() override { + // TODO(crbug/754872): Update this to match WCVCD content_browsertests. if (!IsTooIntensiveForThisPlatform()) EnablePixelOutput(); TabCaptureApiTest::SetUp(); @@ -178,8 +179,10 @@ IN_PROC_BROWSER_TEST_F(TabCaptureApiPixelTest, EndToEndWithoutRemoting) { return; } AddExtensionToCommandLineWhitelist(); + // TODO(crbug/758057): Determine why color accuracy went down in this test + // with the new VIZ-based tab capturer. ASSERT_TRUE(RunExtensionSubtest( - "tab_capture", "end_to_end.html?method=local&colorDeviation=10")) + "tab_capture", "end_to_end.html?method=local&colorDeviation=50")) << message_; } diff --git a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc index e1984cfcaaa..38e56a88a20 100644 --- a/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc +++ b/chromium/chrome/browser/extensions/api/tab_capture/tab_capture_performancetest.cc @@ -42,15 +42,9 @@ constexpr size_t kTrimEvents = 24; // 1 sec at 24fps, or 0.4 sec at 60 fps. constexpr size_t kMinDataPoints = 100; // ~5 sec at 24fps. enum TestFlags { - // TODO(miu): Remove kUseGpu (since the GPU is required), kForceGpuComposited - // (because there's no longer a such thing as Chrome w/o a compositor), and - // maybe kDisableVsync. http://crbug.com/567848 kUseGpu = 1 << 0, // Only execute test if --enable-gpu was given // on the command line. This is required for // tests that run on GPU. - kForceGpuComposited = 1 << 1, // Force the test to use the compositor. - kDisableVsync = 1 << 2, // Do not limit framerate to vertical refresh. - // when on GPU, nor to 60hz when not on GPU. kTestThroughWebRTC = 1 << 3, // Send video through a webrtc loopback. kSmallWindow = 1 << 4, // Window size: 1 = 800x600, 0 = 2000x1000 }; @@ -71,12 +65,8 @@ class TabCapturePerformanceTest std::string GetSuffixForTestFlags() { std::string suffix; - if (HasFlag(kForceGpuComposited)) - suffix += "_comp"; if (HasFlag(kUseGpu)) - suffix += "_gpu"; - if (HasFlag(kDisableVsync)) - suffix += "_novsync"; + suffix += "_comp_gpu"; if (HasFlag(kTestThroughWebRTC)) suffix += "_webrtc"; if (HasFlag(kSmallWindow)) @@ -86,6 +76,8 @@ class TabCapturePerformanceTest void SetUp() override { EnablePixelOutput(); + if (!HasFlag(kUseGpu)) + UseSoftwareCompositing(); ExtensionApiTest::SetUp(); } @@ -105,12 +97,10 @@ class TabCapturePerformanceTest if (!HasFlag(kUseGpu)) command_line->AppendSwitch(switches::kDisableGpu); - if (HasFlag(kDisableVsync)) - command_line->AppendSwitch(switches::kDisableGpuVsync); - command_line->AppendSwitchASCII( extensions::switches::kWhitelistedExtensionID, kExtensionId); + ExtensionApiTest::SetUpCommandLine(command_line); } @@ -258,9 +248,6 @@ class TabCapturePerformanceTest ASSERT_TRUE(tracing::BeginTracing("gpu,gpu.capture")); std::string page = "performance.html"; page += HasFlag(kTestThroughWebRTC) ? "?WebRTC=1" : "?WebRTC=0"; - // Ideally we'd like to run a higher capture rate when vsync is disabled, - // but libjingle currently doesn't allow that. - // page += HasFlag(kDisableVsync) ? "&fps=300" : "&fps=30"; page += "&fps=60"; ASSERT_TRUE(RunExtensionSubtest("tab_capture", page)) << message_; ASSERT_TRUE(tracing::EndTracing(&json_events)); @@ -303,15 +290,9 @@ IN_PROC_BROWSER_TEST_P(TabCapturePerformanceTest, Performance) { // Note: First argument is optional and intentionally left blank. // (it's a prefix for the generated test cases) -INSTANTIATE_TEST_CASE_P( - , - TabCapturePerformanceTest, - testing::Values( - 0, - kUseGpu | kForceGpuComposited, - kDisableVsync, - kDisableVsync | kUseGpu | kForceGpuComposited, - kTestThroughWebRTC, - kTestThroughWebRTC | kUseGpu | kForceGpuComposited, - kTestThroughWebRTC | kDisableVsync, - kTestThroughWebRTC | kDisableVsync | kUseGpu | kForceGpuComposited)); +INSTANTIATE_TEST_CASE_P(, + TabCapturePerformanceTest, + testing::Values(0, + kUseGpu, + kTestThroughWebRTC, + kTestThroughWebRTC | kUseGpu)); diff --git a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc index 3d0bd3e606b..458fc5bdf09 100644 --- a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc +++ b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.cc @@ -7,14 +7,11 @@ #include <memory> #include <utility> -#include "base/strings/utf_string_conversions.h" -#include "base/values.h" #include "chrome/browser/extensions/api/tabs/app_base_window.h" #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/extension_tab_util.h" #include "chrome/browser/extensions/window_controller.h" #include "chrome/browser/extensions/window_controller_list.h" -#include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/common/url_constants.h" #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/native_app_window.h" @@ -46,62 +43,6 @@ std::string AppWindowController::GetWindowTypeText() const { return tabs_constants::kWindowTypeValueApp; } -std::unique_ptr<base::DictionaryValue> -AppWindowController::CreateWindowValueWithTabs( - const Extension* extension) const { - std::unique_ptr<base::DictionaryValue> result = CreateWindowValue(); - - std::unique_ptr<base::DictionaryValue> tab_value = - CreateTabObject(extension, 0)->ToValue(); - if (!tab_value) - return result; - - auto tab_list = std::make_unique<base::ListValue>(); - tab_list->Append(std::move(tab_value)); - result->Set(tabs_constants::kTabsKey, std::move(tab_list)); - - return result; -} - -std::unique_ptr<api::tabs::Tab> AppWindowController::CreateTabObject( - const extensions::Extension* extension, - int tab_index) const { - if (tab_index > 0) - return nullptr; - - content::WebContents* web_contents = app_window_->web_contents(); - if (!web_contents) - return nullptr; - - std::unique_ptr<api::tabs::Tab> tab_object(new api::tabs::Tab); - tab_object->id.reset(new int(SessionTabHelper::IdForTab(web_contents))); - tab_object->index = 0; - tab_object->window_id = - SessionTabHelper::IdForWindowContainingTab(web_contents); - tab_object->url.reset(new std::string(web_contents->GetURL().spec())); - tab_object->status.reset(new std::string( - ExtensionTabUtil::GetTabStatusText(web_contents->IsLoading()))); - tab_object->active = app_window_->GetBaseWindow()->IsActive(); - tab_object->selected = true; - tab_object->highlighted = true; - tab_object->pinned = false; - tab_object->title.reset( - new std::string(base::UTF16ToUTF8(web_contents->GetTitle()))); - tab_object->incognito = app_window_->GetBaseWindow()->IsActive(); - gfx::Rect bounds = app_window_->GetBaseWindow()->GetBounds(); - tab_object->width.reset(new int(bounds.width())); - tab_object->height.reset(new int(bounds.height())); - - const Extension* ext = app_window_->GetExtension(); - if (ext) { - std::string icon_str(chrome::kChromeUIFaviconURL); - icon_str.append(app_window_->GetExtension()->url().spec()); - tab_object->fav_icon_url.reset(new std::string(icon_str)); - } - - return tab_object; -} - bool AppWindowController::CanClose(Reason* reason) const { return true; } @@ -121,8 +62,9 @@ Browser* AppWindowController::GetBrowser() const { return nullptr; } -bool AppWindowController::IsVisibleToExtension( - const Extension* extension) const { +bool AppWindowController::IsVisibleToTabsAPIForExtension( + const Extension* extension, + bool allow_dev_tools_windows) const { DCHECK(extension); return extension->id() == app_window_->extension_id(); } diff --git a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h index 8b8511a7a65..a5fd5850302 100644 --- a/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h +++ b/chromium/chrome/browser/extensions/api/tabs/app_window_controller.h @@ -5,6 +5,7 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_TABS_APP_WINDOW_CONTROLLER_H_ #define CHROME_BROWSER_EXTENSIONS_API_TABS_APP_WINDOW_CONTROLLER_H_ +#include <memory> #include <string> #include "base/macros.h" @@ -28,17 +29,13 @@ class AppWindowController : public WindowController { // extensions::WindowController: int GetWindowId() const override; std::string GetWindowTypeText() const override; - std::unique_ptr<base::DictionaryValue> CreateWindowValueWithTabs( - const Extension* extension) const override; - std::unique_ptr<api::tabs::Tab> CreateTabObject( - const extensions::Extension* extension, - int tab_index) const override; - bool CanClose(Reason* reason) const override; void SetFullscreenMode(bool is_fullscreen, const GURL& extension_url) const override; Browser* GetBrowser() const override; - bool IsVisibleToExtension(const Extension* extension) const override; + bool IsVisibleToTabsAPIForExtension( + const Extension* extension, + bool allow_dev_tools_windows) const override; private: AppWindow* app_window_; // Owns us. diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc index e802ba0057a..1376d685bf8 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.cc @@ -95,11 +95,17 @@ #include "ui/base/ui_base_types.h" #if defined(OS_CHROMEOS) +#include "ash/public/cpp/config.h" #include "ash/public/cpp/window_pin_type.h" #include "ash/public/cpp/window_properties.h" #include "ash/public/interfaces/window_pin_type.mojom.h" +#include "chrome/browser/chromeos/ash_config.h" +#include "chrome/browser/ui/ash/chrome_screenshot_grabber.h" #include "chrome/browser/ui/browser_command_controller.h" +#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" #endif using content::BrowserThread; @@ -256,19 +262,34 @@ bool IsValidStateForWindowsCreateFunction( } #if defined(OS_CHROMEOS) -void SetWindowTrustedPinned(ui::BaseWindow* base_window, bool trusted_pinned) { - aura::Window* window = base_window->GetNativeWindow(); +bool ExtensionHasLockedFullscreenPermission(const Extension* extension) { + return extension->permissions_data()->HasAPIPermission( + APIPermission::kLockWindowFullscreenPrivate); +} + +void SetLockedFullscreenState(Browser* browser, bool locked) { + aura::Window* window = browser->window()->GetNativeWindow(); // TRUSTED_PINNED is used here because that one locks the window fullscreen // without allowing the user to exit (as opposed to regular PINNED). window->SetProperty(ash::kWindowPinTypeKey, - trusted_pinned ? ash::mojom::WindowPinType::TRUSTED_PINNED - : ash::mojom::WindowPinType::NONE); -} + locked ? ash::mojom::WindowPinType::TRUSTED_PINNED + : ash::mojom::WindowPinType::NONE); -bool ExtensionHasLockedFullscreenPermission(const Extension* extension) { - return extension->permissions_data()->HasAPIPermission( - APIPermission::kLockWindowFullscreenPrivate); + // Update the set of available browser commands. + browser->command_controller()->LockedFullscreenStateChanged(); + + // Disallow screenshots in locked fullscreen mode. + // TODO(isandrk, 816900): ChromeScreenshotGrabber isn't implemented in Mash + // yet, remove this conditional when it becomes available. + if (chromeos::GetAshConfig() != ash::Config::MASH) + ChromeScreenshotGrabber::Get()->set_screenshots_allowed(!locked); + + // Reset the clipboard and kill dev tools when entering or exiting locked + // fullscreen (security concerns). + ui::Clipboard::GetForCurrentThread()->Clear(ui::CLIPBOARD_TYPE_COPY_PASTE); + content::DevToolsAgentHost::DetachAllClients(); } + #endif // defined(OS_CHROMEOS) } // namespace @@ -304,18 +325,20 @@ ExtensionFunction::ResponseAction WindowsGetFunction::Run() { EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::Get::Params> extractor(params.get()); - WindowController* controller = nullptr; + Browser* browser = nullptr; std::string error; - if (!windows_util::GetWindowFromWindowID(this, params->window_id, - extractor.type_filters(), - &controller, &error)) { + if (!windows_util::GetBrowserFromWindowID(this, params->window_id, + extractor.type_filters(), &browser, + &error)) { return RespondNow(Error(error)); } + ExtensionTabUtil::PopulateTabBehavior populate_tab_behavior = + extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs + : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - extractor.populate_tabs() - ? controller->CreateWindowValueWithTabs(extension()) - : controller->CreateWindowValue(); + ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), + populate_tab_behavior); return RespondNow(OneArgument(std::move(windows))); } @@ -325,18 +348,20 @@ ExtensionFunction::ResponseAction WindowsGetCurrentFunction::Run() { EXTENSION_FUNCTION_VALIDATE(params.get()); ApiParameterExtractor<windows::GetCurrent::Params> extractor(params.get()); - WindowController* controller = nullptr; + Browser* browser = nullptr; std::string error; - if (!windows_util::GetWindowFromWindowID( + if (!windows_util::GetBrowserFromWindowID( this, extension_misc::kCurrentWindowId, extractor.type_filters(), - &controller, &error)) { + &browser, &error)) { return RespondNow(Error(error)); } + ExtensionTabUtil::PopulateTabBehavior populate_tab_behavior = + extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs + : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - extractor.populate_tabs() - ? controller->CreateWindowValueWithTabs(extension()) - : controller->CreateWindowValue(); + ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), + populate_tab_behavior); return RespondNow(OneArgument(std::move(windows))); } @@ -349,22 +374,28 @@ ExtensionFunction::ResponseAction WindowsGetLastFocusedFunction::Run() { params.get()); // The WindowControllerList should contain a list of application, // browser and devtools windows. - WindowController* controller = nullptr; - for (auto* iter : WindowControllerList::GetInstance()->windows()) { - if (windows_util::CanOperateOnWindow(this, iter, + Browser* browser = nullptr; + for (auto* controller : WindowControllerList::GetInstance()->windows()) { + if (controller->GetBrowser() && + windows_util::CanOperateOnWindow(this, controller, extractor.type_filters())) { - controller = iter; + // TODO(devlin): Doesn't this mean that we'll use the last window in the + // list if there is no active window? That seems wrong. + // See https://crbug.com/809822. + browser = controller->GetBrowser(); if (controller->window()->IsActive()) break; // Use focused window. } } - if (!controller) + if (!browser) return RespondNow(Error(keys::kNoLastFocusedWindowError)); + ExtensionTabUtil::PopulateTabBehavior populate_tab_behavior = + extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs + : ExtensionTabUtil::kDontPopulateTabs; std::unique_ptr<base::DictionaryValue> windows = - extractor.populate_tabs() - ? controller->CreateWindowValueWithTabs(extension()) - : controller->CreateWindowValue(); + ExtensionTabUtil::CreateWindowValueForExtension(*browser, extension(), + populate_tab_behavior); return RespondNow(OneArgument(std::move(windows))); } @@ -375,18 +406,17 @@ ExtensionFunction::ResponseAction WindowsGetAllFunction::Run() { ApiParameterExtractor<windows::GetAll::Params> extractor(params.get()); std::unique_ptr<base::ListValue> window_list(new base::ListValue()); - const WindowControllerList::ControllerList& windows = - WindowControllerList::GetInstance()->windows(); - for (WindowControllerList::ControllerList::const_iterator iter = - windows.begin(); - iter != windows.end(); ++iter) { - if (!windows_util::CanOperateOnWindow(this, *iter, - extractor.type_filters())) + ExtensionTabUtil::PopulateTabBehavior populate_tab_behavior = + extractor.populate_tabs() ? ExtensionTabUtil::kPopulateTabs + : ExtensionTabUtil::kDontPopulateTabs; + for (auto* controller : WindowControllerList::GetInstance()->windows()) { + if (!controller->GetBrowser() || + !windows_util::CanOperateOnWindow(this, controller, + extractor.type_filters())) { continue; - if (extractor.populate_tabs()) - window_list->Append((*iter)->CreateWindowValueWithTabs(extension())); - else - window_list->Append((*iter)->CreateWindowValue()); + } + window_list->Append(ExtensionTabUtil::CreateWindowValueForExtension( + *controller->GetBrowser(), extension(), populate_tab_behavior)); } return RespondNow(OneArgument(std::move(window_list))); @@ -639,8 +669,7 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { // (otherwise the tabstrip is empty). if (create_data && create_data->state == windows::WINDOW_STATE_LOCKED_FULLSCREEN) { - SetWindowTrustedPinned(new_window->window(), true); - new_window->command_controller()->LockedFullscreenStateChanged(); + SetLockedFullscreenState(new_window, true); } #endif @@ -649,8 +678,6 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { else new_window->window()->ShowInactive(); - WindowController* controller = new_window->extension_window_controller(); - std::unique_ptr<base::Value> result; if (new_window->profile()->IsOffTheRecord() && !browser_context()->IsOffTheRecord() && !include_incognito()) { @@ -658,7 +685,8 @@ ExtensionFunction::ResponseAction WindowsCreateFunction::Run() { // profile and CanCrossIncognito isn't allowed. result = std::make_unique<base::Value>(); } else { - result = controller->CreateWindowValueWithTabs(extension()); + result = ExtensionTabUtil::CreateWindowValueForExtension( + *new_window, extension(), ExtensionTabUtil::kPopulateTabs); } return RespondNow(OneArgument(std::move(result))); @@ -669,11 +697,11 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { windows::Update::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - WindowController* controller; + Browser* browser = nullptr; std::string error; - if (!windows_util::GetWindowFromWindowID( + if (!windows_util::GetBrowserFromWindowID( this, params->window_id, WindowController::GetAllWindowFilter(), - &controller, &error)) { + &browser, &error)) { return RespondNow(Error(error)); } @@ -683,7 +711,7 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { #if defined(OS_CHROMEOS) const bool is_window_trusted_pinned = - ash::IsWindowTrustedPinned(controller->window()); + ash::IsWindowTrustedPinned(browser->window()); // Don't allow locked fullscreen operations on a window without the proper // permission (also don't allow any operations on a locked window if the // extension doesn't have the permission). @@ -698,15 +726,11 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { if (is_window_trusted_pinned && params->update_info.state != windows::WINDOW_STATE_LOCKED_FULLSCREEN && params->update_info.state != windows::WINDOW_STATE_NONE) { - SetWindowTrustedPinned(controller->window(), false); - controller->GetBrowser()->command_controller()-> - LockedFullscreenStateChanged(); + SetLockedFullscreenState(browser, false); } else if (!is_window_trusted_pinned && params->update_info.state == windows::WINDOW_STATE_LOCKED_FULLSCREEN) { - SetWindowTrustedPinned(controller->window(), true); - controller->GetBrowser()->command_controller()-> - LockedFullscreenStateChanged(); + SetLockedFullscreenState(browser, true); } #endif @@ -714,34 +738,38 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { ConvertToWindowShowState(params->update_info.state); if (show_state != ui::SHOW_STATE_FULLSCREEN && - show_state != ui::SHOW_STATE_DEFAULT) - controller->SetFullscreenMode(false, extension()->url()); + show_state != ui::SHOW_STATE_DEFAULT) { + browser->extension_window_controller()->SetFullscreenMode( + false, extension()->url()); + } switch (show_state) { case ui::SHOW_STATE_MINIMIZED: - controller->window()->Minimize(); + browser->window()->Minimize(); break; case ui::SHOW_STATE_MAXIMIZED: - controller->window()->Maximize(); + browser->window()->Maximize(); break; case ui::SHOW_STATE_FULLSCREEN: - if (controller->window()->IsMinimized() || - controller->window()->IsMaximized()) - controller->window()->Restore(); - controller->SetFullscreenMode(true, extension()->url()); + if (browser->window()->IsMinimized() || + browser->window()->IsMaximized()) { + browser->window()->Restore(); + } + browser->extension_window_controller()->SetFullscreenMode( + true, extension()->url()); break; case ui::SHOW_STATE_NORMAL: - controller->window()->Restore(); + browser->window()->Restore(); break; default: break; } gfx::Rect bounds; - if (controller->window()->IsMinimized()) - bounds = controller->window()->GetRestoredBounds(); + if (browser->window()->IsMinimized()) + bounds = browser->window()->GetRestoredBounds(); else - bounds = controller->window()->GetBounds(); + bounds = browser->window()->GetBounds(); bool set_bounds = false; // Any part of the bounds can optionally be set by the caller. @@ -773,27 +801,28 @@ ExtensionFunction::ResponseAction WindowsUpdateFunction::Run() { } // TODO(varkha): Updating bounds during a drag can cause problems and a more // general solution is needed. See http://crbug.com/251813 . - controller->window()->SetBounds(bounds); + browser->window()->SetBounds(bounds); } if (params->update_info.focused) { if (*params->update_info.focused) { if (show_state == ui::SHOW_STATE_MINIMIZED) return RespondNow(Error(keys::kInvalidWindowStateError)); - controller->window()->Activate(); + browser->window()->Activate(); } else { if (show_state == ui::SHOW_STATE_MAXIMIZED || show_state == ui::SHOW_STATE_FULLSCREEN) { return RespondNow(Error(keys::kInvalidWindowStateError)); } - controller->window()->Deactivate(); + browser->window()->Deactivate(); } } if (params->update_info.draw_attention) - controller->window()->FlashFrame(*params->update_info.draw_attention); + browser->window()->FlashFrame(*params->update_info.draw_attention); - return RespondNow(OneArgument(controller->CreateWindowValue())); + return RespondNow(OneArgument(ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), ExtensionTabUtil::kDontPopulateTabs))); } ExtensionFunction::ResponseAction WindowsRemoveFunction::Run() { @@ -801,22 +830,23 @@ ExtensionFunction::ResponseAction WindowsRemoveFunction::Run() { windows::Remove::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params); - WindowController* controller = nullptr; + Browser* browser = nullptr; std::string error; - if (!windows_util::GetWindowFromWindowID(this, params->window_id, - WindowController::kNoWindowFilter, - &controller, &error)) { + if (!windows_util::GetBrowserFromWindowID(this, params->window_id, + WindowController::kNoWindowFilter, + &browser, &error)) { return RespondNow(Error(error)); } #if defined(OS_CHROMEOS) - if (ash::IsWindowTrustedPinned(controller->window()) && + if (ash::IsWindowTrustedPinned(browser->window()) && !ExtensionHasLockedFullscreenPermission(extension())) { return RespondNow( Error(keys::kMissingLockWindowFullscreenPrivatePermission)); } #endif + WindowController* controller = browser->extension_window_controller(); WindowController::Reason reason; if (!controller->CanClose(&reason)) { return RespondNow(Error(reason == WindowController::REASON_NOT_EDITABLE @@ -850,7 +880,8 @@ ExtensionFunction::ResponseAction TabsGetSelectedFunction::Run() { return RespondNow(Error(keys::kNoSelectedTabError)); return RespondNow(ArgumentList( tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, tab_strip, tab_strip->active_index(), extension())))); + contents, ExtensionTabUtil::kScrubTab, extension(), tab_strip, + tab_strip->active_index())))); } ExtensionFunction::ResponseAction TabsGetAllInWindowFunction::Run() { @@ -928,8 +959,8 @@ ExtensionFunction::ResponseAction TabsQueryFunction::Run() { if (!include_incognito() && profile != browser->profile()) continue; - if (!browser->extension_window_controller()->IsVisibleToExtension( - extension())) { + if (!browser->extension_window_controller()->IsVisibleToTabsAPIForExtension( + extension(), false /*allow_dev_tools_windows*/)) { continue; } @@ -1033,8 +1064,9 @@ ExtensionFunction::ResponseAction TabsQueryFunction::Run() { if (loading_status_set && loading != web_contents->IsLoading()) continue; - result->Append(ExtensionTabUtil::CreateTabObject(web_contents, tab_strip, - i, extension()) + result->Append(ExtensionTabUtil::CreateTabObject( + web_contents, ExtensionTabUtil::kScrubTab, extension(), + tab_strip, i) ->ToValue()); } } @@ -1101,7 +1133,8 @@ ExtensionFunction::ResponseAction TabsDuplicateFunction::Run() { return RespondNow(ArgumentList( tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - new_contents, new_tab_strip, new_tab_index, extension())))); + new_contents, ExtensionTabUtil::kScrubTab, extension(), new_tab_strip, + new_tab_index)))); } ExtensionFunction::ResponseAction TabsGetFunction::Run() { @@ -1118,9 +1151,9 @@ ExtensionFunction::ResponseAction TabsGetFunction::Run() { return RespondNow(Error(error)); } - return RespondNow(ArgumentList( - tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( - contents, tab_strip, tab_index, extension())))); + return RespondNow(ArgumentList(tabs::Get::Results::Create( + *ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, + extension(), tab_strip, tab_index)))); } ExtensionFunction::ResponseAction TabsGetCurrentFunction::Run() { @@ -1131,8 +1164,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, extension())); + results = tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( + caller_contents, ExtensionTabUtil::kScrubTab, extension())); } return RespondNow(results ? ArgumentList(std::move(results)) : NoArguments()); } @@ -1179,9 +1212,8 @@ ExtensionFunction::ResponseAction TabsHighlightFunction::Run() { selection.set_active(active_index); browser->tab_strip_model()->SetSelectionFromModel(std::move(selection)); - return RespondNow(OneArgument( - browser->extension_window_controller()->CreateWindowValueWithTabs( - extension()))); + return RespondNow(OneArgument(ExtensionTabUtil::CreateWindowValueForExtension( + *browser, extension(), ExtensionTabUtil::kPopulateTabs))); } bool TabsHighlightFunction::HighlightTab(TabStripModel* tabstrip, @@ -1215,7 +1247,7 @@ bool TabsUpdateFunction::RunAsync() { int tab_id = -1; WebContents* contents = NULL; if (!params->tab_id.get()) { - Browser* browser = GetCurrentBrowser(); + Browser* browser = ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); if (!browser) { error_ = keys::kNoCurrentWindowError; return false; @@ -1389,7 +1421,7 @@ bool TabsUpdateFunction::UpdateURL(const std::string &url_string, ScriptExecutor::SINGLE_FRAME, ExtensionApiFrameIdMap::kTopFrameId, ScriptExecutor::DONT_MATCH_ABOUT_BLANK, UserScript::DOCUMENT_IDLE, ScriptExecutor::MAIN_WORLD, ScriptExecutor::DEFAULT_PROCESS, GURL(), - GURL(), user_gesture(), ScriptExecutor::NO_RESULT, + GURL(), user_gesture(), base::nullopt, ScriptExecutor::NO_RESULT, base::Bind(&TabsUpdateFunction::OnExecuteCodeFinished, this)); *is_async = true; @@ -1423,8 +1455,8 @@ void TabsUpdateFunction::PopulateResult() { if (!has_callback()) return; - results_ = tabs::Get::Results::Create( - *ExtensionTabUtil::CreateTabObject(web_contents_, extension())); + results_ = tabs::Get::Results::Create(*ExtensionTabUtil::CreateTabObject( + web_contents_, ExtensionTabUtil::kScrubTab, extension())); } void TabsUpdateFunction::OnExecuteCodeFinished( @@ -1552,10 +1584,10 @@ bool TabsMoveFunction::MoveTab(int tab_id, *new_index, web_contents, TabStripModel::ADD_NONE); if (has_callback()) { - tab_values->Append( - ExtensionTabUtil::CreateTabObject(web_contents, target_tab_strip, - *new_index, extension()) - ->ToValue()); + tab_values->Append(ExtensionTabUtil::CreateTabObject( + web_contents, ExtensionTabUtil::kScrubTab, + extension(), target_tab_strip, *new_index) + ->ToValue()); } return true; @@ -1574,7 +1606,8 @@ bool TabsMoveFunction::MoveTab(int tab_id, if (has_callback()) { tab_values->Append(ExtensionTabUtil::CreateTabObject( - contents, source_tab_strip, *new_index, extension()) + contents, ExtensionTabUtil::kScrubTab, extension(), + source_tab_strip, *new_index) ->ToValue()); } @@ -1682,10 +1715,9 @@ bool TabsCaptureVisibleTabFunction::HasPermission() { return true; } -bool TabsCaptureVisibleTabFunction::IsScreenshotEnabled() { +bool TabsCaptureVisibleTabFunction::IsScreenshotEnabled() const { PrefService* service = chrome_details_.GetProfile()->GetPrefs(); if (service->GetBoolean(prefs::kDisableScreenshots)) { - error_ = keys::kScreenshotsDisabled; return false; } return true; @@ -1730,10 +1762,14 @@ bool TabsCaptureVisibleTabFunction::RunAsync() { WebContents* contents = GetWebContentsForID(context_id); - return CaptureAsync( + const CaptureResult capture_result = CaptureAsync( contents, image_details.get(), - base::Bind(&TabsCaptureVisibleTabFunction::CopyFromSurfaceComplete, - this)); + base::BindOnce(&TabsCaptureVisibleTabFunction::CopyFromSurfaceComplete, + this)); + if (capture_result == OK) + return true; + SetErrorMessage(capture_result); + return false; } void TabsCaptureVisibleTabFunction::OnCaptureSuccess(const SkBitmap& bitmap) { @@ -1747,11 +1783,16 @@ void TabsCaptureVisibleTabFunction::OnCaptureSuccess(const SkBitmap& bitmap) { SendResponse(true); } -void TabsCaptureVisibleTabFunction::OnCaptureFailure(FailureReason reason) { +void TabsCaptureVisibleTabFunction::OnCaptureFailure(CaptureResult result) { + SetErrorMessage(result); + SendResponse(false); +} + +void TabsCaptureVisibleTabFunction::SetErrorMessage(CaptureResult result) { const char* reason_description = "internal error"; - switch (reason) { - case FAILURE_REASON_UNKNOWN: - reason_description = "unknown error"; + switch (result) { + case FAILURE_REASON_READBACK_FAILED: + reason_description = "image readback failed"; break; case FAILURE_REASON_ENCODING_FAILED: reason_description = "encoding failed"; @@ -1759,10 +1800,16 @@ void TabsCaptureVisibleTabFunction::OnCaptureFailure(FailureReason reason) { case FAILURE_REASON_VIEW_INVISIBLE: reason_description = "view is invisible"; break; + case FAILURE_REASON_SCREEN_SHOTS_DISABLED: + error_ = keys::kScreenshotsDisabled; + return; + case OK: + NOTREACHED() + << "SetErrorMessage should not be called with a successful result"; + return; } error_ = ErrorUtils::FormatErrorMessage("Failed to capture tab: *", reason_description); - SendResponse(false); } void TabsCaptureVisibleTabFunction::RegisterProfilePrefs( @@ -1790,7 +1837,7 @@ bool TabsDetectLanguageFunction::RunAsync() { if (!browser || !contents) return false; } else { - browser = GetCurrentBrowser(); + browser = ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); if (!browser) return false; contents = browser->tab_strip_model()->GetActiveWebContents(); @@ -2020,7 +2067,7 @@ content::WebContents* ZoomAPIFunction::GetWebContents(int tab_id) { nullptr /* ignore TabStripModel* output */, &web_contents, nullptr /* ignore int tab_index output */, &error_); } else { - Browser* browser = GetCurrentBrowser(); + Browser* browser = ChromeExtensionFunctionDetails(this).GetCurrentBrowser(); if (!browser) error_ = keys::kNoCurrentWindowError; else if (!ExtensionTabUtil::GetDefaultTab(browser, &web_contents, NULL)) @@ -2177,8 +2224,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)))); + return RespondNow(ArgumentList( + tabs::Discard::Results::Create(*ExtensionTabUtil::CreateTabObject( + contents, ExtensionTabUtil::kScrubTab, extension())))); } // 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 c8e4071ec5a..7fe5521cd41 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api.h +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api.h @@ -215,10 +215,13 @@ class TabsCaptureVisibleTabFunction content::WebContents* GetWebContentsForID(int window_id); // extensions::WebContentsCaptureClient: - bool IsScreenshotEnabled() override; + bool IsScreenshotEnabled() const override; bool ClientAllowsTransparency() override; void OnCaptureSuccess(const SkBitmap& bitmap) override; - void OnCaptureFailure(FailureReason reason) override; + void OnCaptureFailure(CaptureResult result) override; + + private: + void SetErrorMessage(CaptureResult result); DECLARE_EXTENSION_FUNCTION("tabs.captureVisibleTab", TABS_CAPTUREVISIBLETAB) }; 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 d06d5513d00..220421eef7b 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_api_unittest.cc @@ -15,12 +15,12 @@ #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/test_browser_window.h" #include "content/public/browser/navigation_entry.h" -#include "content/public/common/browser_side_navigation_policy.h" #include "content/public/test/browser_side_navigation_test_utils.h" #include "content/public/test/web_contents_tester.h" #include "extensions/browser/api_test_utils.h" #include "extensions/common/constants.h" #include "extensions/common/extension_builder.h" +#include "ui/display/test/test_screen.h" namespace extensions { @@ -34,8 +34,7 @@ std::unique_ptr<base::ListValue> RunTabsQueryFunction( function->set_extension(extension); std::unique_ptr<base::Value> value( extension_function_test_utils::RunFunctionAndReturnSingleResult( - function.get(), query_info, browser, - extension_function_test_utils::NONE)); + function.get(), query_info, browser, api_test_utils::NONE)); return base::ListValue::From(std::move(value)); } @@ -57,28 +56,28 @@ class TabsApiUnitTest : public ExtensionServiceTestBase { std::unique_ptr<TestBrowserWindow> browser_window_; std::unique_ptr<Browser> browser_; + display::test::TestScreen test_screen_; + DISALLOW_COPY_AND_ASSIGN(TabsApiUnitTest); }; void TabsApiUnitTest::SetUp() { ExtensionServiceTestBase::SetUp(); InitializeEmptyExtensionService(); - - if (content::IsBrowserSideNavigationEnabled()) - content::BrowserSideNavigationSetUp(); + content::BrowserSideNavigationSetUp(); browser_window_.reset(new TestBrowserWindow()); Browser::CreateParams params(profile(), true); params.type = Browser::TYPE_TABBED; params.window = browser_window_.get(); browser_.reset(new Browser(params)); + display::Screen::SetScreenInstance(&test_screen_); } void TabsApiUnitTest::TearDown() { browser_.reset(); browser_window_.reset(); - if (content::IsBrowserSideNavigationEnabled()) - content::BrowserSideNavigationTearDown(); + content::BrowserSideNavigationTearDown(); ExtensionServiceTestBase::TearDown(); } @@ -293,7 +292,7 @@ TEST_F(TabsApiUnitTest, ExecuteScriptNoTabIsNonFatalError) { std::string error = extension_function_test_utils::RunFunctionAndReturnError( function.get(), kArgs, browser(), // browser() doesn't have any tabs. - extension_function_test_utils::NONE); + api_test_utils::NONE); EXPECT_EQ(tabs_constants::kNoTabInBrowserWindowError, error); } 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 1ab063b1ea9..af63faf2661 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_event_router.cc @@ -45,7 +45,8 @@ bool WillDispatchTabUpdatedEvent( Event* event, const base::DictionaryValue* listener_filter) { std::unique_ptr<api::tabs::Tab> tab_object = - ExtensionTabUtil::CreateTabObject(contents, extension); + ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, + extension); std::unique_ptr<base::DictionaryValue> tab_value = tab_object->ToValue(); @@ -190,7 +191,9 @@ static bool WillDispatchTabCreatedEvent( const base::DictionaryValue* listener_filter) { event->event_args->Clear(); std::unique_ptr<base::DictionaryValue> tab_value = - ExtensionTabUtil::CreateTabObject(contents, extension)->ToValue(); + ExtensionTabUtil::CreateTabObject(contents, ExtensionTabUtil::kScrubTab, + extension) + ->ToValue(); tab_value->SetBoolean(tabs_constants::kSelectedKey, active); tab_value->SetBoolean(tabs_constants::kActiveKey, active); event->event_args->Append(std::move(tab_value)); diff --git a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc index 01abcd19bea..82fa8cfe3d3 100644 --- a/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc +++ b/chromium/chrome/browser/extensions/api/tabs/tabs_test.cc @@ -225,12 +225,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_GetWindow) { // With "include_incognito". function = new WindowsGetFunction(); function->set_extension(extension.get()); - result.reset(utils::ToDictionary( - utils::RunFunctionAndReturnSingleResult( - function.get(), - base::StringPrintf("[%u]", incognito_window_id), - browser(), - utils::INCLUDE_INCOGNITO))); + result.reset(utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( + function.get(), base::StringPrintf("[%u]", incognito_window_id), + browser(), api_test_utils::INCLUDE_INCOGNITO))); EXPECT_TRUE(api_test_utils::GetBoolean(result.get(), "incognito")); // DevTools window. @@ -244,7 +241,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, MAYBE_GetWindow) { base::StringPrintf("[%u, {\"windowTypes\": [\"devtools\"]}]", ExtensionTabUtil::GetWindowId( DevToolsWindowTesting::Get(devtools)->browser())), - browser(), utils::INCLUDE_INCOGNITO))); + browser(), api_test_utils::INCLUDE_INCOGNITO))); EXPECT_EQ("devtools", api_test_utils::GetString(result.get(), "type")); DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); @@ -301,12 +298,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindows) { window_ids.insert(ExtensionTabUtil::GetWindowId(new_browser)); } - // Application windows should not be accessible, unless allWindowTypes is set - // to true. + // Application windows should not be accessible to extensions (app windows are + // only accessible to the owning item). AppWindow* app_window = CreateTestAppWindow("{}"); - // Undocked DevTools window should not be accessible, unless allWindowTypes is - // set to true. + // Undocked DevTools window should not be accessible, unless included in the + // type filter mask. DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); @@ -370,11 +367,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindowsAllTypes) { window_ids.insert(ExtensionTabUtil::GetWindowId(new_browser)); } - // Application windows should be accessible. + // Application windows should not be accessible to extensions (app windows are + // only accessible to the owning item). AppWindow* app_window = CreateTestAppWindow("{}"); - window_ids.insert(app_window->session_id().id()); - // Undocked DevTools window should be accessible too. + // Undocked DevTools window should be accessible too, since they have been + // explicitly requested as part of the type filter mask. DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); window_ids.insert(ExtensionTabUtil::GetWindowId( @@ -401,8 +399,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindowsAllTypes) { base::ListValue* tabs = nullptr; EXPECT_FALSE(result_window->GetList(keys::kTabsKey, &tabs)); } - // The returned ids should contain all the current app, browser and - // devtools instance ids. + // The returned ids should contain all the browser and devtools instance ids. EXPECT_EQ(window_ids, result_ids); result_ids.clear(); @@ -425,8 +422,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, GetAllWindowsAllTypes) { base::ListValue* tabs = nullptr; EXPECT_TRUE(result_window->GetList(keys::kTabsKey, &tabs)); } - // The returned ids should contain all the current app, browser and - // devtools instance ids. + // The returned ids should contain all the browser and devtools instance ids. EXPECT_EQ(window_ids, result_ids); DevToolsWindowTesting::CloseDevToolsWindowSync(devtools); @@ -468,7 +464,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, std::string error = extension_function_test_utils::RunFunctionAndReturnError( update_tab_function.get(), kArgsWithNonIncognitoUrl, incognito, // incognito doesn't have any tabs. - extension_function_test_utils::NONE); + api_test_utils::NONE); EXPECT_EQ(ErrorUtils::FormatErrorMessage( tabs_constants::kURLsNotAllowedInIncognitoError, "chrome://extensions/configureCommands"), @@ -496,7 +492,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DefaultToIncognitoWhenItIsForced) { std::unique_ptr<base::DictionaryValue> result( utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( function.get(), kArgsWithoutExplicitIncognitoParam, browser(), - utils::INCLUDE_INCOGNITO))); + api_test_utils::INCLUDE_INCOGNITO))); // Make sure it is a new(different) window. EXPECT_NE(ExtensionTabUtil::GetWindowId(browser()), @@ -511,12 +507,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DefaultToIncognitoWhenItIsForced) { function->SetRenderFrameHost( browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame()); function->set_extension(extension.get()); - result.reset(utils::ToDictionary( - utils::RunFunctionAndReturnSingleResult( - function.get(), - kArgsWithoutExplicitIncognitoParam, - incognito_browser, - utils::INCLUDE_INCOGNITO))); + result.reset(utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( + function.get(), kArgsWithoutExplicitIncognitoParam, incognito_browser, + api_test_utils::INCLUDE_INCOGNITO))); // Make sure it is a new(different) window. EXPECT_NE(ExtensionTabUtil::GetWindowId(incognito_browser), GetWindowId(result.get())); @@ -536,7 +529,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, function->set_extension(extension.get()); std::unique_ptr<base::DictionaryValue> result( utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( - function.get(), kEmptyArgs, browser(), utils::INCLUDE_INCOGNITO))); + function.get(), kEmptyArgs, browser(), + api_test_utils::INCLUDE_INCOGNITO))); // Make sure it is a new(different) window. EXPECT_NE(ExtensionTabUtil::GetWindowId(browser()), @@ -549,11 +543,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, // Run without an explicit "incognito" param. function = new WindowsCreateFunction(); function->set_extension(extension.get()); - result.reset(utils::ToDictionary( - utils::RunFunctionAndReturnSingleResult(function.get(), - kEmptyArgs, - incognito_browser, - utils::INCLUDE_INCOGNITO))); + result.reset(utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( + function.get(), kEmptyArgs, incognito_browser, + api_test_utils::INCLUDE_INCOGNITO))); // Make sure it is a new(different) window. EXPECT_NE(ExtensionTabUtil::GetWindowId(incognito_browser), GetWindowId(result.get())); @@ -762,55 +754,6 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, InvalidUpdateWindowState) { keys::kInvalidWindowStateError)); } -IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateAppWindowSizeConstraint) { - AppWindow* app_window = CreateTestAppWindow( - "{\"outerBounds\": " - "{\"width\": 300, \"height\": 300," - " \"minWidth\": 200, \"minHeight\": 200," - " \"maxWidth\": 400, \"maxHeight\": 400}}"); - - scoped_refptr<WindowsGetFunction> get_function = new WindowsGetFunction(); - scoped_refptr<Extension> extension(ExtensionBuilder("Test").Build().get()); - get_function->set_extension(extension.get()); - std::unique_ptr<base::DictionaryValue> result( - utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( - get_function.get(), - base::StringPrintf("[%u, {\"windowTypes\": [\"app\"]}]", - app_window->session_id().id()), - browser()))); - - EXPECT_EQ(300, api_test_utils::GetInteger(result.get(), "width")); - EXPECT_EQ(300, api_test_utils::GetInteger(result.get(), "height")); - - // Verify the min width/height of the application window are - // respected. - scoped_refptr<WindowsUpdateFunction> update_min_function = - new WindowsUpdateFunction(); - result.reset(utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( - update_min_function.get(), - base::StringPrintf("[%u, {\"width\": 100, \"height\": 100}]", - app_window->session_id().id()), - browser()))); - - EXPECT_EQ(200, api_test_utils::GetInteger(result.get(), "width")); - EXPECT_EQ(200, api_test_utils::GetInteger(result.get(), "height")); - - // Verify the max width/height of the application window are - // respected. - scoped_refptr<WindowsUpdateFunction> update_max_function = - new WindowsUpdateFunction(); - result.reset(utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( - update_max_function.get(), - base::StringPrintf("[%u, {\"width\": 500, \"height\": 500}]", - app_window->session_id().id()), - browser()))); - - EXPECT_EQ(400, api_test_utils::GetInteger(result.get(), "width")); - EXPECT_EQ(400, api_test_utils::GetInteger(result.get(), "height")); - - CloseAppWindow(app_window); -} - IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, UpdateDevToolsWindow) { DevToolsWindow* devtools = DevToolsWindowTesting::OpenDevToolsWindowSync( browser()->tab_strip_model()->GetWebContentsAt(0), false /* is_docked */); @@ -866,6 +809,8 @@ class ExtensionWindowLastFocusedTest : public ExtensionTabsTest { base::Value* RunFunction(UIThreadExtensionFunction* function, const std::string& params); + const Extension* extension() { return extension_.get(); } + private: // A helper class to wait for an views::Widget to become activated. class WidgetActivatedWaiter : public views::WidgetObserver { @@ -1083,13 +1028,12 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowLastFocusedTest, scoped_refptr<WindowsGetLastFocusedFunction> get_current_app_function = new WindowsGetLastFocusedFunction(); - std::unique_ptr<base::DictionaryValue> result(utils::ToDictionary( - RunFunction(get_current_app_function.get(), - "[{\"populate\": true, \"windowTypes\": [ \"app\" ]}]"))); - int app_window_id = app_window->session_id().id(); - EXPECT_EQ(app_window_id, api_test_utils::GetInteger(result.get(), "id")); - EXPECT_EQ(-1, GetTabId(result.get())); - EXPECT_EQ("app", api_test_utils::GetString(result.get(), "type")); + get_current_app_function->set_extension(extension()); + EXPECT_EQ( + tabs_constants::kNoLastFocusedWindowError, + extension_function_test_utils::RunFunctionAndReturnError( + get_current_app_function.get(), + "[{\"populate\": true, \"windowTypes\": [ \"app\" ]}]", browser())); } chrome::CloseWindow(normal_browser); @@ -1113,7 +1057,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowCreateTest, AcceptState) { std::unique_ptr<base::DictionaryValue> result( utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( function.get(), "[{\"state\": \"minimized\"}]", browser(), - utils::INCLUDE_INCOGNITO))); + api_test_utils::INCLUDE_INCOGNITO))); int window_id = GetWindowId(result.get()); std::string error; Browser* new_window = ExtensionTabUtil::GetBrowserFromWindowID( @@ -1129,7 +1073,7 @@ IN_PROC_BROWSER_TEST_F(ExtensionWindowCreateTest, AcceptState) { function->set_extension(extension.get()); result.reset(utils::ToDictionary(utils::RunFunctionAndReturnSingleResult( function.get(), "[{\"state\": \"fullscreen\"}]", browser(), - utils::INCLUDE_INCOGNITO))); + api_test_utils::INCLUDE_INCOGNITO))); window_id = GetWindowId(result.get()); new_window = ExtensionTabUtil::GetBrowserFromWindowID( ChromeExtensionFunctionDetails(function.get()), window_id, &error); @@ -1406,7 +1350,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { // Creates Tab object to ensure the property is correct for the extension. std::unique_ptr<api::tabs::Tab> tab_object_a = - ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + ExtensionTabUtil::CreateTabObject(web_contents_a, + ExtensionTabUtil::kDontScrubTab, + nullptr, tab_strip_model, 0); EXPECT_FALSE(tab_object_a->discarded); // Discards one tab. @@ -1414,8 +1360,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardedProperty) { web_contents_a = tab_strip_model->GetWebContentsAt(1); // Make sure the property is changed accordingly after discarding the tab. - tab_object_a = - ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + tab_object_a = ExtensionTabUtil::CreateTabObject( + web_contents_a, ExtensionTabUtil::kDontScrubTab, nullptr, tab_strip_model, + 0); EXPECT_TRUE(tab_object_a->discarded); // Get non-discarded tabs after discarding one tab. @@ -1520,6 +1467,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithId) { tab_id = ExtensionTabUtil::GetTabId(web_contents); EXPECT_EQ(tab_id, api_test_utils::GetInteger(result.get(), "id")); EXPECT_TRUE(api_test_utils::GetBoolean(result.get(), "discarded")); + // The result should be scrubbed. + EXPECT_FALSE(result->FindKey("url")); // Tests chrome.tabs.discard(tabId) with an already discarded tab. It has to // return the error stating that the tab couldn't be discarded. @@ -1592,6 +1541,8 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, DiscardWithoutId) { EXPECT_EQ(ExtensionTabUtil::GetTabId(web_contents), api_test_utils::GetInteger(result.get(), "id")); EXPECT_TRUE(api_test_utils::GetBoolean(result.get(), "discarded")); + // The result should be scrubbed. + EXPECT_FALSE(result->FindKey("url")); } // Tests chrome.tabs.discard() without disabling protection time. @@ -1633,7 +1584,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { // Creates Tab object to ensure the property is correct for the extension. TabStripModel* tab_strip_model = browser()->tab_strip_model(); std::unique_ptr<api::tabs::Tab> tab_object_a = - ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + ExtensionTabUtil::CreateTabObject(web_contents_a, + ExtensionTabUtil::kDontScrubTab, + nullptr, tab_strip_model, 0); EXPECT_TRUE(tab_object_a->auto_discardable); // Set up query and update functions with the extension. @@ -1675,8 +1628,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionTabsTest, AutoDiscardableProperty) { api_test_utils::GetBoolean(update_result.get(), "autoDiscardable")); // Make sure the property is changed accordingly after updating the tab. - tab_object_a = - ExtensionTabUtil::CreateTabObject(web_contents_a, tab_strip_model, 0); + tab_object_a = ExtensionTabUtil::CreateTabObject( + web_contents_a, ExtensionTabUtil::kDontScrubTab, nullptr, tab_strip_model, + 0); EXPECT_FALSE(tab_object_a->auto_discardable); // Get auto-discardable tabs after changing the status of web contents A. @@ -1786,7 +1740,7 @@ bool ExtensionTabsZoomTest::RunSetZoom(int tab_id, double zoom_factor) { return utils::RunFunction( set_zoom_function.get(), base::StringPrintf("[%u, %lf]", tab_id, zoom_factor), browser(), - extension_function_test_utils::NONE); + api_test_utils::NONE); } testing::AssertionResult ExtensionTabsZoomTest::RunGetZoom( @@ -1825,10 +1779,8 @@ bool ExtensionTabsZoomTest::RunSetZoomSettings(int tab_id, args = base::StringPrintf("[%u, {\"mode\": \"%s\"}]", tab_id, mode); } - return utils::RunFunction(set_zoom_settings_function.get(), - args, - browser(), - extension_function_test_utils::NONE); + return utils::RunFunction(set_zoom_settings_function.get(), args, browser(), + api_test_utils::NONE); } testing::AssertionResult ExtensionTabsZoomTest::RunGetZoomSettings( 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 0ef3e6f98d1..7e4412108a2 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_event_router.cc @@ -14,6 +14,7 @@ #include "chrome/browser/extensions/api/tabs/tabs_constants.h" #include "chrome/browser/extensions/api/tabs/windows_util.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/window_controller.h" #include "chrome/browser/extensions/window_controller_list.h" @@ -42,14 +43,19 @@ bool ControllerVisibleToListener(WindowController* window_controller, // If there is no filter the visibility is based on the extension. const base::ListValue* filter_value = nullptr; - if (!listener_filter || - !listener_filter->GetList(keys::kWindowTypesKey, &filter_value)) - return window_controller->IsVisibleToExtension(extension); - - // Otherwise it's based on the type filter. - WindowController::TypeFilter filter = - WindowController::GetFilterFromWindowTypesValues(filter_value); - return window_controller->MatchesFilter(filter); + if (listener_filter) + listener_filter->GetList(keys::kWindowTypesKey, &filter_value); + + // TODO(https://crbug.com/807313): Remove this. + bool allow_dev_tools_windows = !!filter_value; + if (!window_controller->IsVisibleToTabsAPIForExtension( + extension, allow_dev_tools_windows)) { + return false; + } + + return !filter_value || + window_controller->MatchesFilter( + WindowController::GetFilterFromWindowTypesValues(filter_value)); } bool WillDispatchWindowEvent(WindowController* window_controller, @@ -59,6 +65,13 @@ bool WillDispatchWindowEvent(WindowController* window_controller, const base::DictionaryValue* listener_filter) { bool has_filter = listener_filter && listener_filter->HasKey(keys::kWindowTypesKey); + // TODO(https://crbug.com/807313): Remove this. + bool allow_dev_tools_windows = has_filter; + if (!window_controller->IsVisibleToTabsAPIForExtension( + extension, allow_dev_tools_windows)) { + return false; + } + // Cleanup previous values. event->filter_info = EventFilteringInfo(); // Only set the window type if the listener has set a filter. @@ -66,8 +79,7 @@ bool WillDispatchWindowEvent(WindowController* window_controller, if (has_filter) { event->filter_info.window_type = window_controller->GetWindowTypeText(); } else { - event->filter_info.window_exposed_by_default = - window_controller->IsVisibleToExtension(extension); + event->filter_info.window_exposed_by_default = true; } return true; } @@ -194,9 +206,14 @@ void WindowsEventRouter::OnWindowControllerAdded( return; if (!profile_->IsSameProfile(window_controller->profile())) return; + // Ignore any windows without an associated browser (e.g., AppWindows). + if (!window_controller->GetBrowser()) + return; std::unique_ptr<base::ListValue> args(new base::ListValue()); - args->Append(window_controller->CreateWindowValue()); + args->Append(ExtensionTabUtil::CreateWindowValueForExtension( + *window_controller->GetBrowser(), nullptr, + ExtensionTabUtil::kDontPopulateTabs)); DispatchEvent(events::WINDOWS_ON_CREATED, windows::OnCreated::kEventName, window_controller, std::move(args)); } @@ -207,6 +224,9 @@ void WindowsEventRouter::OnWindowControllerRemoved( return; if (!profile_->IsSameProfile(window_controller->profile())) return; + // Ignore any windows without an associated browser (e.g., AppWindows). + if (!window_controller->GetBrowser()) + return; int window_id = window_controller->GetWindowId(); std::unique_ptr<base::ListValue> args(new base::ListValue()); diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc index e7179e62225..3d75225bf78 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.cc +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.cc @@ -23,38 +23,48 @@ namespace windows_util { -bool GetWindowFromWindowID(UIThreadExtensionFunction* function, - int window_id, - extensions::WindowController::TypeFilter filter, - extensions::WindowController** controller, - std::string* error) { +bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, + int window_id, + extensions::WindowController::TypeFilter filter, + Browser** browser, + std::string* error) { + DCHECK(browser); DCHECK(error); + + *browser = nullptr; if (window_id == extension_misc::kCurrentWindowId) { - extensions::WindowController* extension_window_controller = - function->dispatcher()->GetExtensionWindowController(); // If there is a window controller associated with this extension, use that. - if (extension_window_controller) { - *controller = extension_window_controller; - } else { + extensions::WindowController* window_controller = + function->dispatcher()->GetExtensionWindowController(); + if (!window_controller) { // Otherwise get the focused or most recently added window. - *controller = extensions::WindowControllerList::GetInstance() - ->CurrentWindowForFunctionWithFilter(function, filter); + window_controller = + extensions::WindowControllerList::GetInstance() + ->CurrentWindowForFunctionWithFilter(function, filter); } - if (!(*controller)) { + + if (window_controller) + *browser = window_controller->GetBrowser(); + + if (!(*browser)) { *error = extensions::tabs_constants::kNoCurrentWindowError; return false; } } else { - *controller = + extensions::WindowController* window_controller = extensions::WindowControllerList::GetInstance() ->FindWindowForFunctionByIdWithFilter(function, window_id, filter); - if (!(*controller)) { + if (window_controller) + *browser = window_controller->GetBrowser(); + + if (!(*browser)) { *error = extensions::ErrorUtils::FormatErrorMessage( extensions::tabs_constants::kWindowNotFoundError, base::IntToString(window_id)); return false; } } + DCHECK(*browser); return true; } @@ -64,9 +74,13 @@ bool CanOperateOnWindow(const UIThreadExtensionFunction* function, if (filter && !controller->MatchesFilter(filter)) return false; - if (!filter && function->extension() && - !controller->IsVisibleToExtension(function->extension())) + // TODO(https://crbug.com/807313): Remove this. + bool allow_dev_tools_windows = !!filter; + if (function->extension() && + !controller->IsVisibleToTabsAPIForExtension(function->extension(), + allow_dev_tools_windows)) { return false; + } if (function->browser_context() == controller->profile()) return true; diff --git a/chromium/chrome/browser/extensions/api/tabs/windows_util.h b/chromium/chrome/browser/extensions/api/tabs/windows_util.h index d5526e10c30..f080d068c72 100644 --- a/chromium/chrome/browser/extensions/api/tabs/windows_util.h +++ b/chromium/chrome/browser/extensions/api/tabs/windows_util.h @@ -5,6 +5,8 @@ #ifndef CHROME_BROWSER_EXTENSIONS_API_TABS_WINDOWS_UTIL_H__ #define CHROME_BROWSER_EXTENSIONS_API_TABS_WINDOWS_UTIL_H__ +#include <string> + #include "chrome/browser/extensions/window_controller_list.h" class UIThreadExtensionFunction; @@ -15,13 +17,13 @@ class WindowController; namespace windows_util { -// Populates |controller| for given |window_id|. If the window is not found, +// Populates |browser| for given |window_id|. If the window is not found, // returns false and sets |error|. -bool GetWindowFromWindowID(UIThreadExtensionFunction* function, - int window_id, - extensions::WindowController::TypeFilter filter, - extensions::WindowController** controller, - std::string* error); +bool GetBrowserFromWindowID(UIThreadExtensionFunction* function, + int window_id, + extensions::WindowController::TypeFilter filter, + Browser** browser, + std::string* error); // Returns true if |function| (and the profile and extension that it was // invoked from) can operate on the window wrapped by |window_controller|. 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 ee44ebfbdde..6a0a795e8bb 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.cc @@ -6,6 +6,7 @@ #include <memory> #include <utility> +#include <vector> #include "base/bind.h" #include "base/command_line.h" @@ -25,6 +26,7 @@ #include "extensions/browser/app_window/app_window.h" #include "extensions/browser/app_window/app_window_registry.h" #include "extensions/browser/event_router.h" +#include "extensions/browser/extensions_browser_client.h" namespace terminal_private = extensions::api::terminal_private; namespace OnTerminalResize = @@ -43,6 +45,9 @@ const char kCroshCommand[] = "/usr/bin/crosh"; // We make stubbed crosh just echo back input. 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)) @@ -54,13 +59,24 @@ std::string GetCroshPath() { 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(); } +// Whether the program accepts arbitrary command line arguments. +bool CommandSupportsArguments(const std::string& name) { + if (name == kVmShellName) + return true; + + return false; +} + void NotifyProcessOutput(content::BrowserContext* browser_context, const std::string& extension_id, int tab_id, @@ -119,10 +135,24 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { OpenTerminalProcess::Params::Create(*args_)); EXTENSION_FUNCTION_VALIDATE(params.get()); - command_ = GetProcessCommandForName(params->process_name); - if (command_.empty()) + 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); + } + + if (arguments.size() > 1 && !CommandSupportsArguments(params->process_name)) + return RespondNow(Error("Specified command does not support arguments.")); + content::WebContents* caller_contents = GetSenderWebContents(); if (!caller_contents) return RespondNow(Error("No web contents.")); @@ -151,19 +181,23 @@ TerminalPrivateOpenTerminalProcessFunction::Run() { tab_id), base::Bind( &TerminalPrivateOpenTerminalProcessFunction::RespondOnUIThread, - this))); + this), + arguments, + user_id_hash)); return RespondLater(); } void TerminalPrivateOpenTerminalProcessFunction::OpenOnRegistryTaskRunner( const ProcessOutputCallback& output_callback, - const OpenProcessCallback& callback) { - DCHECK(!command_.empty()); - + const OpenProcessCallback& callback, + const std::vector<std::string>& arguments, + const std::string& user_id_hash) { chromeos::ProcessProxyRegistry* registry = chromeos::ProcessProxyRegistry::Get(); + const base::CommandLine cmdline{arguments}; - int terminal_id = registry->OpenProcess(command_.c_str(), output_callback); + int terminal_id = + registry->OpenProcess(cmdline, user_id_hash, output_callback); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::BindOnce(callback, terminal_id)); 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 c6455784059..cd7018fb2e4 100644 --- a/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h +++ b/chromium/chrome/browser/extensions/api/terminal/terminal_private_api.h @@ -6,6 +6,7 @@ #define CHROME_BROWSER_EXTENSIONS_API_TERMINAL_TERMINAL_PRIVATE_API_H_ #include <string> +#include <vector> #include "extensions/browser/extension_function.h" @@ -33,10 +34,10 @@ class TerminalPrivateOpenTerminalProcessFunction using OpenProcessCallback = base::Callback<void(int terminal_id)>; void OpenOnRegistryTaskRunner(const ProcessOutputCallback& output_callback, - const OpenProcessCallback& callback); + const OpenProcessCallback& callback, + const std::vector<std::string>& arguments, + const std::string& user_id_hash); void RespondOnUIThread(int terminal_id); - - std::string command_; }; // Send input to the terminal process specified by the terminal ID, which is set diff --git a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/DEPS b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/DEPS index fee9b1012b1..381dab83266 100644 --- a/chromium/chrome/browser/extensions/api/virtual_keyboard_private/DEPS +++ b/chromium/chrome/browser/extensions/api/virtual_keyboard_private/DEPS @@ -2,4 +2,5 @@ include_rules = [ # TODO(mash): Remove. http://crbug.com/678705 "+ash/shell.h", "+media/audio" + "+services/audio/public/cpp" ] 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 02d77771c79..7e58654da56 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 @@ -21,10 +21,13 @@ #include "chrome/browser/ui/chrome_pages.h" #include "chrome/common/url_constants.h" #include "components/user_manager/user_manager.h" +#include "content/public/common/service_manager_connection.h" #include "extensions/browser/event_router.h" #include "extensions/common/api/virtual_keyboard.h" #include "extensions/common/api/virtual_keyboard_private.h" #include "media/audio/audio_system.h" +#include "services/audio/public/cpp/audio_system_factory.h" +#include "services/service_manager/public/cpp/connector.h" #include "ui/aura/window_tree_host.h" #include "ui/keyboard/keyboard_controller.h" #include "ui/keyboard/keyboard_switches.h" @@ -74,7 +77,10 @@ void ChromeVirtualKeyboardDelegate::GetKeyboardConfig( OnKeyboardSettingsCallback on_settings_callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!audio_system_) - audio_system_ = media::AudioSystem::CreateInstance(); + audio_system_ = audio::CreateAudioSystem( + content::ServiceManagerConnection::GetForProcess() + ->GetConnector() + ->Clone()); audio_system_->HasInputDevices( base::BindOnce(&ChromeVirtualKeyboardDelegate::OnHasInputDevices, weak_this_, std::move(on_settings_callback))); @@ -152,24 +158,31 @@ bool ChromeVirtualKeyboardDelegate::ShowLanguageSettings() { return true; } -bool ChromeVirtualKeyboardDelegate::SetVirtualKeyboardMode(int mode_enum) { +bool ChromeVirtualKeyboardDelegate::SetVirtualKeyboardMode( + int mode_enum, + OnSetModeCallback on_set_mode_callback) { keyboard::KeyboardController* controller = keyboard::KeyboardController::GetInstance(); if (!controller) return false; - switch (mode_enum) { + controller->SetContainerType(ConvertKeyboardModeToContainerType(mode_enum), + std::move(on_set_mode_callback)); + return true; +} + +keyboard::ContainerType +ChromeVirtualKeyboardDelegate::ConvertKeyboardModeToContainerType( + int mode) const { + switch (mode) { case keyboard_api::KEYBOARD_MODE_FULL_WIDTH: - controller->SetContainerType(keyboard::ContainerType::FULL_WIDTH); - break; + return keyboard::ContainerType::FULL_WIDTH; case keyboard_api::KEYBOARD_MODE_FLOATING: - controller->SetContainerType(keyboard::ContainerType::FLOATING); - break; - default: - NOTREACHED(); - break; + return keyboard::ContainerType::FLOATING; } - return true; + + NOTREACHED(); + return keyboard::ContainerType::FULL_WIDTH; } bool ChromeVirtualKeyboardDelegate::SetDraggableArea( 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 1ec4b52b068..d0af47f0095 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 @@ -13,6 +13,7 @@ #include "content/public/browser/browser_context.h" #include "extensions/browser/api/virtual_keyboard_private/virtual_keyboard_delegate.h" #include "extensions/common/api/virtual_keyboard.h" +#include "ui/keyboard/container_type.h" namespace media { class AudioSystem; @@ -44,7 +45,8 @@ class ChromeVirtualKeyboardDelegate : public VirtualKeyboardDelegate { int modifiers) override; bool ShowLanguageSettings() override; bool IsLanguageSettingsEnabled() override; - bool SetVirtualKeyboardMode(int mode_enum) override; + bool SetVirtualKeyboardMode(int mode_enum, + OnSetModeCallback on_set_mode_callback) override; bool SetDraggableArea( const api::virtual_keyboard_private::Bounds& rect) override; bool SetRequestedKeyboardState(int state_enum) override; @@ -57,6 +59,7 @@ class ChromeVirtualKeyboardDelegate : public VirtualKeyboardDelegate { bool has_audio_input_devices); void DispatchConfigChangeEvent( std::unique_ptr<base::DictionaryValue> settings); + keyboard::ContainerType ConvertKeyboardModeToContainerType(int mode) const; content::BrowserContext* browser_context_; std::unique_ptr<media::AudioSystem> audio_system_; diff --git a/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc b/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc index 43798f375e0..cd090aab65c 100644 --- a/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc +++ b/chromium/chrome/browser/extensions/api/vpn_provider/vpn_provider_apitest.cc @@ -197,8 +197,8 @@ class VpnProviderApiTest : public ExtensionApiTest, void TriggerInternalRemove() { NetworkHandler::Get()->network_configuration_handler()->RemoveConfiguration( GetSingleServicePath(), - NetworkConfigurationObserver::SOURCE_USER_ACTION, - base::Bind(base::DoNothing), base::Bind(DoNothingFailureCallback)); + NetworkConfigurationObserver::SOURCE_USER_ACTION, base::DoNothing(), + base::Bind(DoNothingFailureCallback)); } // NetworkConfigurationObserver: 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 28dbc774e12..747efc84c3b 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 @@ -37,7 +37,6 @@ #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/web_contents.h" -#include "content/public/common/browser_side_navigation_policy.h" #include "content/public/common/context_menu_params.h" #include "content/public/common/resource_type.h" #include "content/public/common/url_constants.h" @@ -276,8 +275,6 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ServerRedirectSingleProcess) { } IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, ForwardBack) { - if (content::IsBrowserSideNavigationEnabled()) - return; // TODO(jam): investigate ASSERT_TRUE(RunExtensionTest("webnavigation/forwardBack")) << message_; } @@ -384,9 +381,9 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, RequestOpenTab) { ui_test_utils::NavigateToURL(browser(), url); // There's a link on a.html. Middle-click on it to open it in a new tab. - blink::WebMouseEvent mouse_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); + blink::WebMouseEvent mouse_event( + blink::WebInputEvent::kMouseDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = blink::WebMouseEvent::Button::kMiddle; mouse_event.SetPositionInWidget(7, 7); mouse_event.click_count = 1; @@ -416,9 +413,9 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlank) { // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. - blink::WebMouseEvent mouse_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); + blink::WebMouseEvent mouse_event( + blink::WebInputEvent::kMouseDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = blink::WebMouseEvent::Button::kLeft; mouse_event.SetPositionInWidget(7, 7); mouse_event.click_count = 1; @@ -446,9 +443,9 @@ IN_PROC_BROWSER_TEST_F(WebNavigationApiTest, TargetBlankIncognito) { // There's a link with target=_blank on a.html. Click on it to open it in a // new tab. - blink::WebMouseEvent mouse_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); + blink::WebMouseEvent mouse_event( + blink::WebInputEvent::kMouseDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = blink::WebMouseEvent::Button::kLeft; mouse_event.SetPositionInWidget(7, 7); mouse_event.click_count = 1; 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 dd86f9b6972..b43a05f9a61 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 @@ -139,6 +139,19 @@ void GetPartOfMessageArguments(IPC::Message* message, ASSERT_TRUE(list.GetDictionary(0, out)); } +base::Value FormBinaryValue(base::StringPiece str) { + base::Value list(base::Value::Type::LIST); + list.GetList().emplace_back(base::Value( + base::Value::BlobStorage(str.data(), str.data() + str.size()))); + return list; +} + +base::Value FormStringValue(base::StringPiece str) { + base::Value list(base::Value::Type::LIST); + list.GetList().emplace_back(base::Value(str)); + return list; +} + } // namespace // A mock event router that responds to events with a pre-arranged queue of @@ -566,7 +579,7 @@ void ExtensionWebRequestTest::FireURLRequestWithData( &(bytes_2[0]), bytes_2.size())); request->set_upload(std::make_unique<net::ElementsUploadDataStream>( std::move(element_readers), 0)); - ipc_sender_.PushTask(base::Bind(&base::DoNothing)); + ipc_sender_.PushTask(base::DoNothing()); request->Start(); } @@ -592,17 +605,26 @@ TEST_F(ExtensionWebRequestTest, AccessRequestBodyData) { const size_t kPlainBlock2Length = sizeof(kPlainBlock2) - 1; std::vector<char> plain_2(kPlainBlock2, kPlainBlock2 + kPlainBlock2Length); #define kBoundary "THIS_IS_A_BOUNDARY" - const char kFormBlock1[] = "--" kBoundary "\r\n" + const char kFormBlock1[] = + "--" kBoundary + "\r\n" "Content-Disposition: form-data; name=\"A\"\r\n" "\r\n" "test text\r\n" - "--" kBoundary "\r\n" + "--" kBoundary + "\r\n" "Content-Disposition: form-data; name=\"B\"; filename=\"\"\r\n" "Content-Type: application/octet-stream\r\n" - "\r\n"; + "\r\n" + "--" kBoundary + "\r\n" + "Content-Disposition: form-data; name=\"B_content\"\r\n" + "Content-Type: application/octet-stream\r\n" + "\r\n" + "\uffff\uffff\uffff\uffff\r\n" + "--" kBoundary "\r\n"; std::vector<char> form_1(kFormBlock1, kFormBlock1 + sizeof(kFormBlock1) - 1); - const char kFormBlock2[] = "\r\n" - "--" kBoundary "\r\n" + const char kFormBlock2[] = "Content-Disposition: form-data; name=\"C\"\r\n" "\r\n" "test password\r\n" @@ -623,10 +645,21 @@ TEST_F(ExtensionWebRequestTest, AccessRequestBodyData) { &kRawPath }; // Contents of formData. - const char kFormData[] = - "{\"A\":[\"test text\"],\"B\":[\"\"],\"C\":[\"test password\"]}"; - std::unique_ptr<const base::Value> form_data = - base::JSONReader::Read(kFormData); + struct KeyValuePairs { + const char* key; + base::Value value; + }; + KeyValuePairs kFormDataPairs[] = { + {"A", FormStringValue("test text")}, + {"B", FormStringValue("")}, + {"B_content", FormBinaryValue("\uffff\uffff\uffff\uffff")}, + {"C", FormStringValue("test password")}}; + std::unique_ptr<base::Value> form_data = + std::make_unique<base::Value>(base::Value::Type::DICTIONARY); + for (auto& pair : kFormDataPairs) { + form_data->SetKey(pair.key, std::move(pair.value)); + } + ASSERT_TRUE(form_data.get() != NULL); ASSERT_TRUE(form_data->type() == base::Value::Type::DICTIONARY); // Contents of raw. @@ -782,7 +815,7 @@ TEST_F(ExtensionWebRequestTest, MinimalAccessRequestBodyData) { // Only one request is sent, but more than one event will be triggered. for (size_t i = 1; i < arraysize(kExpected); ++i) - ipc_sender_.PushTask(base::Bind(&base::DoNothing)); + ipc_sender_.PushTask(base::DoNothing()); const std::vector<char> part_of_body(1); FireURLRequestWithData("POST", nullptr, part_of_body, part_of_body); @@ -855,7 +888,7 @@ TEST_F(ExtensionWebRequestTest, ProperFilteringInPublicSession) { // Only one request is sent, but more than one event will be triggered. for (size_t i = 1; i < arraysize(kExpected); ++i) - ipc_sender_.PushTask(base::Bind(&base::DoNothing)); + ipc_sender_.PushTask(base::DoNothing()); const std::vector<char> part_of_body(1); FireURLRequestWithData("POST", nullptr, part_of_body, part_of_body); @@ -920,7 +953,7 @@ TEST_F(ExtensionWebRequestTest, NoAccessRequestBodyData) { context_->CreateRequest(request_url, net::DEFAULT_PRIORITY, &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS)); request->set_method(kMethods[i]); - ipc_sender_.PushTask(base::Bind(&base::DoNothing)); + ipc_sender_.PushTask(base::DoNothing()); request->Start(); } @@ -1195,7 +1228,7 @@ TEST_P(ExtensionWebRequestHeaderModificationTest, TestModifications) { } // Don't do anything for the onSendHeaders message. - ipc_sender_.PushTask(base::Bind(&base::DoNothing)); + ipc_sender_.PushTask(base::DoNothing()); // Note that we mess up the headers slightly: // request->Start() will first add additional headers (e.g. the User-Agent) 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 e0b875c7d40..bd3b124bbf5 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 @@ -21,7 +21,6 @@ #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_with_management_policy_apitest.h" #include "chrome/browser/extensions/tab_helper.h" -#include "chrome/browser/extensions/test_extension_dir.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" @@ -48,6 +47,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/common/page_type.h" #include "content/public/test/browser_test_utils.h" +#include "content/public/test/url_loader_interceptor.h" #include "extensions/browser/api/web_request/web_request_api.h" #include "extensions/browser/blocked_action_type.h" #include "extensions/browser/extension_system.h" @@ -55,6 +55,7 @@ #include "extensions/common/features/feature.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" +#include "extensions/test/test_extension_dir.h" #include "google_apis/gaia/gaia_switches.h" #include "net/dns/mock_host_resolver.h" #include "net/http/http_util.h" @@ -69,6 +70,7 @@ #include "net/url_request/url_request_context_getter.h" #include "net/url_request/url_request_filter.h" #include "net/url_request/url_request_interceptor.h" +#include "services/network/public/cpp/features.h" #include "third_party/WebKit/public/platform/WebInputEvent.h" #if defined(OS_CHROMEOS) @@ -283,22 +285,33 @@ class DevToolsFrontendInWebRequestApiTest : public ExtensionApiTest { host_resolver()->AddRule("*", "127.0.0.1"); int port = embedded_test_server()->port(); - base::RunLoop run_loop; - content::BrowserThread::PostTaskAndReply( - content::BrowserThread::IO, FROM_HERE, - base::BindOnce(&SetUpDevToolsFrontendInterceptorOnIO, port, - test_root_dir_), - run_loop.QuitClosure()); - run_loop.Run(); + + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + url_loader_interceptor_ = std::make_unique<content::URLLoaderInterceptor>( + base::BindRepeating(&DevToolsFrontendInWebRequestApiTest::OnIntercept, + base::Unretained(this), port)); + } else { + base::RunLoop run_loop; + content::BrowserThread::PostTaskAndReply( + content::BrowserThread::IO, FROM_HERE, + base::BindOnce(&SetUpDevToolsFrontendInterceptorOnIO, port, + test_root_dir_), + run_loop.QuitClosure()); + run_loop.Run(); + } } void TearDownOnMainThread() override { - base::RunLoop run_loop; - content::BrowserThread::PostTaskAndReply( - content::BrowserThread::IO, FROM_HERE, - base::BindOnce(&TearDownDevToolsFrontendInterceptorOnIO), - run_loop.QuitClosure()); - run_loop.Run(); + if (base::FeatureList::IsEnabled(network::features::kNetworkService)) { + url_loader_interceptor_.reset(); + } else { + base::RunLoop run_loop; + content::BrowserThread::PostTaskAndReply( + content::BrowserThread::IO, FROM_HERE, + base::BindOnce(&TearDownDevToolsFrontendInterceptorOnIO), + run_loop.QuitClosure()); + run_loop.Run(); + } ExtensionApiTest::TearDownOnMainThread(); } @@ -317,7 +330,49 @@ class DevToolsFrontendInWebRequestApiTest : public ExtensionApiTest { } private: + bool OnIntercept(int test_server_port, + content::URLLoaderInterceptor::RequestParams* params) { + // See comments in DevToolsFrontendInterceptor above. The devtools remote + // frontend URLs are hardcoded into Chrome and are requested by some of the + // tests here to exercise their behavior with respect to WebRequest. + // + // We treat any URL request not targeting the test server as targeting the + // remote frontend, and we intercept them to fulfill from test data rather + // than hitting the network. + if (params->url_request.url.EffectiveIntPort() == test_server_port) + return false; + + std::string status_line; + std::string contents; + GetFileContents( + test_root_dir_.AppendASCII(params->url_request.url.path().substr(1)), + &status_line, &contents); + content::URLLoaderInterceptor::WriteResponse(status_line, contents, + params->client.get()); + return true; + } + + static void GetFileContents(const base::FilePath& path, + std::string* status_line, + std::string* contents) { + base::ScopedAllowBlockingForTesting allow_io; + if (!base::ReadFileToString(path, contents)) { + *status_line = "HTTP/1.0 404 Not Found\n\n"; + return; + } + + std::string content_type; + if (path.Extension() == FILE_PATH_LITERAL(".html")) + content_type = "Content-type: text/html\n"; + else if (path.Extension() == FILE_PATH_LITERAL(".js")) + content_type = "Content-type: application/javascript\n"; + + *status_line = + base::StringPrintf("HTTP/1.0 200 OK\n%s\n", content_type.c_str()); + } + base::FilePath test_root_dir_; + std::unique_ptr<content::URLLoaderInterceptor> url_loader_interceptor_; }; IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, WebRequestApi) { @@ -467,9 +522,9 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MAYBE_WebRequestNewTab) { // There's a link on a.html with target=_blank. Click on it to open it in a // new tab. - blink::WebMouseEvent mouse_event(blink::WebInputEvent::kMouseDown, - blink::WebInputEvent::kNoModifiers, - blink::WebInputEvent::kTimeStampForTesting); + blink::WebMouseEvent mouse_event( + blink::WebInputEvent::kMouseDown, blink::WebInputEvent::kNoModifiers, + blink::WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = blink::WebMouseEvent::Button::kLeft; mouse_event.SetPositionInWidget(7, 7); mouse_event.click_count = 1; @@ -1297,7 +1352,21 @@ IN_PROC_BROWSER_TEST_F(ExtensionWebRequestApiTest, MinimumAccessInitiator) { // Ensure that devtools frontend requests are hidden from the webRequest API. IN_PROC_BROWSER_TEST_F(DevToolsFrontendInWebRequestApiTest, HiddenRequests) { - ASSERT_TRUE(RunExtensionSubtest("webrequest", "test_devtools.html")) + // Test expectations differ with the Network Service because of the way + // request interception is done for the test. In the legacy networking path a + // URLRequestMockHTTPJob is used, which does not generate + // |onBeforeHeadersSent| events. With the Network Service enabled, requests + // issued to HTTP URLs by these tests look like real HTTP requests and + // therefore do generate |onBeforeHeadersSent| events. + // + // These tests adjust their expectations accordingly based on whether or not + // the Network Service is enabled. + const char* network_service_arg = + base::FeatureList::IsEnabled(network::features::kNetworkService) + ? "NetworkServiceEnabled" + : "NetworkServiceDisabled"; + ASSERT_TRUE(RunExtensionSubtestWithArg("webrequest", "test_devtools.html", + network_service_arg)) << message_; } 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 8bcd3345fe3..b2723a15ed6 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 @@ -193,6 +193,7 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, TestHideRequestForURL) { TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, TestCanExtensionAccessURL_HostPermissions) { + // Request with empty initiator. std::unique_ptr<net::URLRequest> request( context.CreateRequest(GURL("http://example.com"), net::DEFAULT_PRIORITY, NULL, TRAFFIC_ANNOTATION_FOR_TESTS)); @@ -211,15 +212,23 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, request->url(), -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::REQUIRE_HOST_PERMISSION, + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, request->initiator())); EXPECT_EQ(PermissionsData::ACCESS_ALLOWED, WebRequestPermissions::CanExtensionAccessURL( extension_info_map_.get(), com_extension_->id(), request->url(), -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::REQUIRE_HOST_PERMISSION, + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, request->initiator())); + EXPECT_EQ( + PermissionsData::ACCESS_ALLOWED, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), com_extension_->id(), request->url(), + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR, + request->initiator())); EXPECT_EQ(PermissionsData::ACCESS_DENIED, WebRequestPermissions::CanExtensionAccessURL( extension_info_map_.get(), com_extension_->id(), request->url(), @@ -227,6 +236,54 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, false, // crosses_incognito WebRequestPermissions::REQUIRE_ALL_URLS, request->initiator())); + std::unique_ptr<net::URLRequest> request_with_initiator( + context.CreateRequest(GURL("http://example.com"), net::DEFAULT_PRIORITY, + nullptr, TRAFFIC_ANNOTATION_FOR_TESTS)); + request_with_initiator->set_initiator( + url::Origin::Create(GURL("http://www.example.org"))); + + EXPECT_EQ(PermissionsData::ACCESS_ALLOWED, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), permissionless_extension_->id(), + request_with_initiator->url(), + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::DO_NOT_CHECK_HOST, + request_with_initiator->initiator())); + EXPECT_EQ(PermissionsData::ACCESS_DENIED, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), permissionless_extension_->id(), + request_with_initiator->url(), + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, + request_with_initiator->initiator())); + EXPECT_EQ(PermissionsData::ACCESS_ALLOWED, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), com_extension_->id(), + request_with_initiator->url(), + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, + request_with_initiator->initiator())); + EXPECT_EQ( + PermissionsData::ACCESS_DENIED, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), com_extension_->id(), + request_with_initiator->url(), + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL_AND_INITIATOR, + request_with_initiator->initiator())); + EXPECT_EQ(PermissionsData::ACCESS_DENIED, + WebRequestPermissions::CanExtensionAccessURL( + extension_info_map_.get(), com_extension_->id(), + request_with_initiator->url(), + -1, // No tab id. + false, // crosses_incognito + WebRequestPermissions::REQUIRE_ALL_URLS, + request_with_initiator->initiator())); + // Public Sessions tests. #if defined(OS_CHROMEOS) std::unique_ptr<net::URLRequest> org_request(context.CreateRequest( @@ -239,7 +296,7 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, org_request->url(), -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::REQUIRE_HOST_PERMISSION, + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, org_request->initiator())); chromeos::ScopedTestPublicSessionLoginState login_state; @@ -252,7 +309,7 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, org_request->url(), -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::REQUIRE_HOST_PERMISSION, + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, org_request->initiator())); EXPECT_EQ( @@ -275,7 +332,7 @@ TEST_F(ExtensionWebRequestHelpersTestWithThreadsTest, chrome_request->url(), -1, // No tab id. false, // crosses_incognito - WebRequestPermissions::REQUIRE_HOST_PERMISSION, + WebRequestPermissions::REQUIRE_HOST_PERMISSION_FOR_URL, chrome_request->initiator())); #endif } diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/DEPS b/chromium/chrome/browser/extensions/api/webrtc_audio_private/DEPS index 67c01d06986..287341aed80 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/DEPS +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/DEPS @@ -1,3 +1,4 @@ include_rules = [ "+media/audio" + "services/audio/public/cpp" ] diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc index fa1e2bdda32..22301de62d9 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.cc @@ -18,11 +18,14 @@ #include "content/public/browser/media_device_id.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/service_manager_connection.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/error_utils.h" #include "extensions/common/permissions/permissions_data.h" #include "media/audio/audio_system.h" +#include "services/audio/public/cpp/audio_system_factory.h" +#include "services/service_manager/public/cpp/connector.h" #include "url/gurl.h" #include "url/origin.h" @@ -106,7 +109,7 @@ WebrtcAudioPrivateFunction::~WebrtcAudioPrivateFunction() {} std::string WebrtcAudioPrivateFunction::CalculateHMAC( const std::string& raw_id) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CURRENTLY_ON(BrowserThread::UI); // We don't hash the default device description, and we always return // "default" for the default device. There is code in SetActiveSink @@ -130,9 +133,13 @@ std::string WebrtcAudioPrivateFunction::device_id_salt() const { } media::AudioSystem* WebrtcAudioPrivateFunction::GetAudioSystem() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); - if (!audio_system_) - audio_system_ = media::AudioSystem::CreateInstance(); + DCHECK_CURRENTLY_ON(BrowserThread::UI); + if (!audio_system_) { + audio_system_ = audio::CreateAudioSystem( + content::ServiceManagerConnection::GetForProcess() + ->GetConnector() + ->Clone()); + } return audio_system_.get(); } @@ -176,27 +183,17 @@ WebrtcAudioPrivateFunction::GetRenderProcessHostFromRequest( bool WebrtcAudioPrivateGetSinksFunction::RunAsync() { DCHECK_CURRENTLY_ON(BrowserThread::UI); InitDeviceIDSalt(); - BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::BindOnce(&WebrtcAudioPrivateGetSinksFunction:: - GetOutputDeviceDescriptionsOnIOThread, - this)); - return true; -} - -void WebrtcAudioPrivateGetSinksFunction:: - GetOutputDeviceDescriptionsOnIOThread() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); GetAudioSystem()->GetDeviceDescriptions( - false, base::BindOnce(&WebrtcAudioPrivateGetSinksFunction:: - ReceiveOutputDeviceDescriptionsOnIOThread, - this)); + false, + base::BindOnce( + &WebrtcAudioPrivateGetSinksFunction::ReceiveOutputDeviceDescriptions, + this)); + return true; } -void WebrtcAudioPrivateGetSinksFunction:: - ReceiveOutputDeviceDescriptionsOnIOThread( - media::AudioDeviceDescriptions sink_devices) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); +void WebrtcAudioPrivateGetSinksFunction::ReceiveOutputDeviceDescriptions( + media::AudioDeviceDescriptions sink_devices) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); auto results = std::make_unique<SinkInfoVector>(); for (const media::AudioDeviceDescription& description : sink_devices) { wap::SinkInfo info; @@ -205,15 +202,6 @@ void WebrtcAudioPrivateGetSinksFunction:: // TODO(joi): Add other parameters. results->push_back(std::move(info)); } - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::BindOnce(&WebrtcAudioPrivateGetSinksFunction::DoneOnUIThread, this, - base::Passed(&results))); -} - -void WebrtcAudioPrivateGetSinksFunction::DoneOnUIThread( - std::unique_ptr<SinkInfoVector> results) { - DCHECK_CURRENTLY_ON(BrowserThread::UI); results_ = wap::GetSinks::Results::Create(*results); SendResponse(true); } @@ -230,28 +218,17 @@ bool WebrtcAudioPrivateGetAssociatedSinkFunction::RunAsync() { EXTENSION_FUNCTION_VALIDATE(params_.get()); InitDeviceIDSalt(); - BrowserThread::PostTask( - BrowserThread::IO, FROM_HERE, - base::BindOnce(&WebrtcAudioPrivateGetAssociatedSinkFunction:: - GetInputDeviceDescriptionsOnIOThread, - this)); - - return true; -} - -void WebrtcAudioPrivateGetAssociatedSinkFunction:: - GetInputDeviceDescriptionsOnIOThread() { - DCHECK_CURRENTLY_ON(BrowserThread::IO); GetAudioSystem()->GetDeviceDescriptions( true, base::BindOnce(&WebrtcAudioPrivateGetAssociatedSinkFunction:: - ReceiveInputDeviceDescriptionsOnIOThread, + ReceiveInputDeviceDescriptions, this)); + return true; } void WebrtcAudioPrivateGetAssociatedSinkFunction:: - ReceiveInputDeviceDescriptionsOnIOThread( + ReceiveInputDeviceDescriptions( media::AudioDeviceDescriptions source_devices) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CURRENTLY_ON(BrowserThread::UI); url::Origin security_origin = url::Origin::Create(GURL(params_->security_origin)); std::string source_id_in_origin(params_->source_id_in_origin); @@ -269,29 +246,25 @@ void WebrtcAudioPrivateGetAssociatedSinkFunction:: } } if (raw_source_id.empty()) { - CalculateHMACOnIOThread(std::string()); + CalculateHMACAndReply(base::nullopt); return; } GetAudioSystem()->GetAssociatedOutputDeviceID( raw_source_id, base::BindOnce( - &WebrtcAudioPrivateGetAssociatedSinkFunction::CalculateHMACOnIOThread, + &WebrtcAudioPrivateGetAssociatedSinkFunction::CalculateHMACAndReply, this)); } -void WebrtcAudioPrivateGetAssociatedSinkFunction::CalculateHMACOnIOThread( +void WebrtcAudioPrivateGetAssociatedSinkFunction::CalculateHMACAndReply( const base::Optional<std::string>& raw_sink_id) { - DCHECK_CURRENTLY_ON(BrowserThread::IO); + DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!raw_sink_id || !raw_sink_id->empty()); // If no |raw_sink_id| is provided, the default device is used. - BrowserThread::PostTask( - BrowserThread::UI, FROM_HERE, - base::BindOnce( - &WebrtcAudioPrivateGetAssociatedSinkFunction::ReceiveHMACOnUIThread, - this, CalculateHMAC(raw_sink_id.value_or(std::string())))); + Reply(CalculateHMAC(raw_sink_id.value_or(std::string()))); } -void WebrtcAudioPrivateGetAssociatedSinkFunction::ReceiveHMACOnUIThread( +void WebrtcAudioPrivateGetAssociatedSinkFunction::Reply( const std::string& associated_sink_id) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (associated_sink_id == media::AudioDeviceDescription::kDefaultDeviceId) { diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h index 9f022383542..7e85f87df1b 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_api.h @@ -59,7 +59,6 @@ class WebrtcAudioPrivateFunction : public ChromeAsyncExtensionFunction { protected: // Calculates a single HMAC, using the extension ID as the security origin. - // Call only on IO thread. std::string CalculateHMAC(const std::string& raw_id); // Initializes |device_id_salt_|. Must be called on the UI thread, @@ -98,16 +97,10 @@ class WebrtcAudioPrivateGetSinksFunction : public WebrtcAudioPrivateFunction { bool RunAsync() override; - // Requests output device descriptions. - void GetOutputDeviceDescriptionsOnIOThread(); - - // Receives output device descriptions, calculates HMACs for them and replies - // to UI thread with DoneOnUIThread(). - void ReceiveOutputDeviceDescriptionsOnIOThread( + // Receives output device descriptions, calculates HMACs for them and sends + // the response. + void ReceiveOutputDeviceDescriptions( media::AudioDeviceDescriptions sink_devices); - - // Sends the response. - void DoneOnUIThread(std::unique_ptr<SinkInfoVector> results); }; class WebrtcAudioPrivateGetAssociatedSinkFunction @@ -125,23 +118,17 @@ class WebrtcAudioPrivateGetAssociatedSinkFunction // UI thread: Entry point, posts GetInputDeviceDescriptions() to IO thread. bool RunAsync() override; - // Enumerates input devices. - void GetInputDeviceDescriptionsOnIOThread(); - // Receives the input device descriptions, looks up the raw source device ID // basing on |params|, and requests the associated raw sink ID for it. - void ReceiveInputDeviceDescriptionsOnIOThread( + void ReceiveInputDeviceDescriptions( media::AudioDeviceDescriptions source_devices); - // IO thread: Receives the raw sink ID, calculates HMAC and replies to IO - // thread with ReceiveHMACOnUIThread(). - void CalculateHMACOnIOThread(const base::Optional<std::string>& raw_sink_id); + // Receives the raw sink ID, calculates HMAC and calls Reply(). + void CalculateHMACAndReply(const base::Optional<std::string>& raw_sink_id); // Receives the associated sink ID as HMAC and sends the response. - void ReceiveHMACOnUIThread(const std::string& hmac); + void Reply(const std::string& hmac); - // Initialized on UI thread in RunAsync(), read-only access on IO thread - no - // locking needed. std::unique_ptr<api::webrtc_audio_private::GetAssociatedSink::Params> params_; }; diff --git a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc index b09a14d684f..5b8a78852b1 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_audio_private/webrtc_audio_private_browsertest.cc @@ -25,12 +25,13 @@ #include "chrome/browser/media/webrtc/webrtc_log_uploader.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" -#include "chrome/common/features.h" +#include "chrome/common/buildflags.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/media_device_id.h" #include "content/public/browser/web_contents.h" +#include "content/public/common/service_manager_connection.h" #include "content/public/test/browser_test_utils.h" #include "extensions/common/permissions/permission_set.h" #include "extensions/common/permissions/permissions_data.h" @@ -38,6 +39,8 @@ #include "media/audio/audio_system.h" #include "media/base/media_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" +#include "services/audio/public/cpp/audio_system_factory.h" +#include "services/service_manager/public/cpp/connector.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) @@ -63,8 +66,10 @@ namespace { void GetAudioDeviceDescriptions(bool for_input, AudioDeviceDescriptions* device_descriptions) { base::RunLoop run_loop; - std::unique_ptr<media::AudioSystem> audio_system = - media::AudioSystem::CreateInstance(); + std::unique_ptr<media::AudioSystem> audio_system = audio::CreateAudioSystem( + content::ServiceManagerConnection::GetForProcess() + ->GetConnector() + ->Clone()); audio_system->GetDeviceDescriptions( for_input, base::BindOnce( @@ -73,7 +78,7 @@ void GetAudioDeviceDescriptions(bool for_input, *result = std::move(received); finished_callback.Run(); }, - base::Passed(run_loop.QuitClosure()), device_descriptions)); + run_loop.QuitClosure(), device_descriptions)); run_loop.Run(); } 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 233fb3e34d2..af8a700f354 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 @@ -238,7 +238,7 @@ bool WebrtcLoggingPrivateSetMetaDataFunction::RunAsync() { BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::BindOnce(&WebRtcLoggingHandlerHost::SetMetaData, webrtc_logging_handler_host, - base::Passed(&meta_data), callback)); + std::move(meta_data), callback)); return true; } diff --git a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc index c1a9c2fd7ae..07b4d99c5b0 100644 --- a/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc +++ b/chromium/chrome/browser/extensions/api/webrtc_logging_private/webrtc_logging_private_browsertest.cc @@ -7,8 +7,8 @@ #include "base/threading/thread_restrictions.h" #include "build/build_config.h" #include "chrome/browser/apps/app_browsertest_util.h" -#include "chrome/browser/media/webrtc/webrtc_log_list.h" #include "chrome/common/chrome_switches.h" +#include "components/webrtc_logging/browser/log_list.h" class WebrtcLoggingPrivateApiBrowserTest : public extensions::PlatformAppBrowserTest { @@ -17,7 +17,7 @@ class WebrtcLoggingPrivateApiBrowserTest ~WebrtcLoggingPrivateApiBrowserTest() override = default; base::FilePath webrtc_logs_path() { - return WebRtcLogList::GetWebRtcLogDirectoryForBrowserContextPath( + return webrtc_logging::LogList::GetWebRtcLogDirectoryForBrowserContextPath( profile()->GetPath()); } 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 1b82d5446c9..71f464d8fb9 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 @@ -221,7 +221,8 @@ WebstorePrivateBeginInstallWithManifest3Function::Run() { if (!icon_url.is_empty()) { loader_factory = content::BrowserContext::GetDefaultStoragePartition(browser_context()) - ->GetURLLoaderFactoryForBrowserProcess(); + ->GetURLLoaderFactoryForBrowserProcess() + .get(); } scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper( 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 85228f0e23a..620a8b9b3a3 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 @@ -22,9 +22,9 @@ #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "chrome/common/buildflags.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension_test_util.h" -#include "chrome/common/features.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/gpu_data_manager.h" #include "content/public/browser/notification_observer.h" |