blob: 9fddbbecc21ebba98f9ba4eb8f1e5d0c43910faf [file] [log] [blame]
annekao38685502015-07-14 17:46:391// Copyright 2015 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
avia2f4804a2015-12-24 23:11:135#include <stdint.h>
6
Sylvain Defresne4fdc727fd2018-10-04 11:09:467#include "base/bind.h"
kalman6f984ae2015-09-18 17:21:588#include "base/bind_helpers.h"
Istiaque Ahmeda14ec482018-08-25 01:02:189#include "base/json/json_reader.h"
avia2f4804a2015-12-24 23:11:1310#include "base/macros.h"
Istiaque Ahmedd4b67ee2019-03-02 10:53:2011#include "base/optional.h"
Gabriel Charette078e3662017-08-28 22:59:0412#include "base/run_loop.h"
kalman6f984ae2015-09-18 17:21:5813#include "base/strings/stringprintf.h"
horo1eeddde2015-11-19 05:59:2514#include "base/strings/utf_string_conversions.h"
David Bertoni1d646a152019-04-25 02:09:2215#include "base/test/bind_test_util.h"
jam3f2d3932017-04-26 20:28:5116#include "base/threading/thread_restrictions.h"
Olga Sharonova3e13cd92018-02-08 16:43:5617#include "build/build_config.h"
Istiaque Ahmed3dd604232019-08-02 19:22:2118#include "chrome/browser/extensions/api/permissions/permissions_api.h"
Istiaque Ahmed3f692562019-07-26 22:59:2619#include "chrome/browser/extensions/browsertest_util.h"
David Bertoni98a5da72019-08-23 23:38:2220#include "chrome/browser/extensions/chrome_test_extension_loader.h"
David Bertoni9026eff2019-05-01 18:04:3121#include "chrome/browser/extensions/crx_installer.h"
Istiaque Ahmed91d6987c2019-06-25 00:09:3322#include "chrome/browser/extensions/extension_action_runner.h"
annekao38685502015-07-14 17:46:3923#include "chrome/browser/extensions/extension_apitest.h"
rdevlin.croninf5863da2015-09-10 19:21:4524#include "chrome/browser/extensions/extension_service.h"
Istiaque Ahmed805f6a83b2017-10-05 01:23:2625#include "chrome/browser/extensions/lazy_background_page_test_util.h"
David Bertoni1d646a152019-04-25 02:09:2226#include "chrome/browser/extensions/unpacked_installer.h"
peter9f4490a2017-01-27 00:58:3627#include "chrome/browser/gcm/gcm_profile_service_factory.h"
miguelg9b502862017-04-24 18:13:5328#include "chrome/browser/notifications/notification_display_service_factory.h"
Istiaque Ahmed242a4102019-06-25 01:47:5729#include "chrome/browser/notifications/notification_display_service_tester.h"
Peter Beverloodd4ef1e2018-06-21 15:41:0430#include "chrome/browser/notifications/notification_permission_context.h"
miguelg9b502862017-04-24 18:13:5331#include "chrome/browser/notifications/stub_notification_display_service.h"
lshang106c1772016-06-06 01:43:2332#include "chrome/browser/permissions/permission_manager.h"
timlohc6911802017-03-01 05:37:0333#include "chrome/browser/permissions/permission_result.h"
lazyboy561b7de2015-11-19 19:27:3034#include "chrome/browser/push_messaging/push_messaging_app_identifier.h"
35#include "chrome/browser/push_messaging/push_messaging_service_factory.h"
36#include "chrome/browser/push_messaging/push_messaging_service_impl.h"
Istiaque Ahmed91d6987c2019-06-25 00:09:3337#include "chrome/browser/ui/extensions/browser_action_test_util.h"
annekao1db36fd2015-07-29 17:09:1638#include "chrome/browser/ui/tabs/tab_strip_model.h"
Trent Apted4267b942017-10-27 03:25:3639#include "chrome/common/chrome_switches.h"
Istiaque Ahmeda14ec482018-08-25 01:02:1840#include "chrome/common/extensions/api/web_navigation.h"
rdevlin.croninf5863da2015-09-10 19:21:4541#include "chrome/test/base/ui_test_utils.h"
timloh9a180ad2017-02-20 07:15:2342#include "components/content_settings/core/common/content_settings_types.h"
Peter Beverloo34139462018-04-10 14:18:0643#include "components/gcm_driver/fake_gcm_profile_service.h"
johnmea5045732016-09-08 17:23:2944#include "components/gcm_driver/instance_id/fake_gcm_driver_for_instance_id.h"
sdefresne9fb67692015-08-03 18:48:2245#include "components/version_info/version_info.h"
Devlin Cronin59551d82019-03-05 01:28:5946#include "content/public/browser/console_message.h"
kalman6f984ae2015-09-18 17:21:5847#include "content/public/browser/navigation_controller.h"
rdevlin.croninf5863da2015-09-10 19:21:4548#include "content/public/browser/navigation_entry.h"
Istiaque Ahmedd4b67ee2019-03-02 10:53:2049#include "content/public/browser/render_process_host.h"
lazyboy4c82177a2016-10-18 00:04:0950#include "content/public/browser/service_worker_context.h"
Devlin Cronin59551d82019-03-05 01:28:5951#include "content/public/browser/service_worker_context_observer.h"
lazyboy4c82177a2016-10-18 00:04:0952#include "content/public/browser/storage_partition.h"
kalman6f984ae2015-09-18 17:21:5853#include "content/public/browser/web_contents.h"
lazyboybd325ae2015-11-18 21:35:2654#include "content/public/common/content_switches.h"
falkenad185092016-06-16 06:10:0255#include "content/public/common/origin_util.h"
kalman6f984ae2015-09-18 17:21:5856#include "content/public/common/page_type.h"
Istiaque Ahmedd4b67ee2019-03-02 10:53:2057#include "content/public/common/result_codes.h"
lazyboybd325ae2015-11-18 21:35:2658#include "content/public/test/background_sync_test_util.h"
annekao1db36fd2015-07-29 17:09:1659#include "content/public/test/browser_test_utils.h"
lazyboy63b994a2017-06-30 21:20:2360#include "content/public/test/service_worker_test_helpers.h"
Istiaque Ahmed771aa8a22018-06-20 23:40:5361#include "extensions/browser/event_router.h"
kalman6f984ae2015-09-18 17:21:5862#include "extensions/browser/extension_host.h"
lazyboyc3e763a2015-12-09 23:09:5863#include "extensions/browser/extension_registry.h"
kalman6f984ae2015-09-18 17:21:5864#include "extensions/browser/process_manager.h"
Istiaque Ahmed70f76ac2018-11-02 02:59:5565#include "extensions/browser/service_worker_task_queue.h"
Istiaque Ahmeda14ec482018-08-25 01:02:1866#include "extensions/common/api/test.h"
David Bertoni98a5da72019-08-23 23:38:2267#include "extensions/common/extensions_client.h"
68#include "extensions/common/manifest_handlers/background_info.h"
Istiaque Ahmed3dd604232019-08-02 19:22:2169#include "extensions/common/permissions/permissions_data.h"
Istiaque Ahmed771aa8a22018-06-20 23:40:5370#include "extensions/common/value_builder.h"
David Bertoni9026eff2019-05-01 18:04:3171#include "extensions/common/verifier_formats.h"
kalman6f984ae2015-09-18 17:21:5872#include "extensions/test/background_page_watcher.h"
annekao38685502015-07-14 17:46:3973#include "extensions/test/extension_test_message_listener.h"
Istiaque Ahmed805f6a83b2017-10-05 01:23:2674#include "extensions/test/result_catcher.h"
Devlin Cronin59551d82019-03-05 01:28:5975#include "extensions/test/test_extension_dir.h"
falkenad185092016-06-16 06:10:0276#include "net/dns/mock_host_resolver.h"
horo1eeddde2015-11-19 05:59:2577#include "net/test/embedded_test_server/embedded_test_server.h"
Istiaque Ahmed242a4102019-06-25 01:47:5778#include "ui/message_center/public/cpp/notification.h"
lazyboy63b994a2017-06-30 21:20:2379#include "url/url_constants.h"
annekao38685502015-07-14 17:46:3980
81namespace extensions {
82
kalman6f984ae2015-09-18 17:21:5883namespace {
84
lazyboy22eddc712015-12-10 21:16:2685class WebContentsLoadStopObserver : content::WebContentsObserver {
86 public:
87 explicit WebContentsLoadStopObserver(content::WebContents* web_contents)
88 : content::WebContentsObserver(web_contents),
89 load_stop_observed_(false) {}
90
91 void WaitForLoadStop() {
92 if (load_stop_observed_)
93 return;
94 message_loop_runner_ = new content::MessageLoopRunner;
95 message_loop_runner_->Run();
96 }
97
98 private:
99 void DidStopLoading() override {
100 load_stop_observed_ = true;
101 if (message_loop_runner_)
102 message_loop_runner_->Quit();
103 }
104
105 bool load_stop_observed_;
106 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
107
108 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadStopObserver);
109};
110
David Bertoni4d9cf41d2019-06-04 00:06:22111// A known extension ID for tests that specify the key in their
112// manifests.
113constexpr char kTestExtensionId[] = "knldjmfmopnpolahpmmgbagdohdnhkik";
114
kalman6f984ae2015-09-18 17:21:58115} // namespace
116
Devlin Cronin242d19d22019-03-12 18:08:48117class ServiceWorkerTest : public ExtensionApiTest {
annekao38685502015-07-14 17:46:39118 public:
lazyboy20167c22016-05-18 00:59:30119 ServiceWorkerTest() : current_channel_(version_info::Channel::STABLE) {}
Istiaque Ahmed7105f2a2017-10-07 01:11:59120 explicit ServiceWorkerTest(version_info::Channel channel)
121 : current_channel_(channel) {}
annekao38685502015-07-14 17:46:39122
123 ~ServiceWorkerTest() override {}
124
jam1a5b5582017-05-01 16:50:10125 void SetUpOnMainThread() override {
126 ExtensionApiTest::SetUpOnMainThread();
David Bertoni3929f552019-03-28 22:10:36127 host_resolver()->AddRule("*", "127.0.0.1");
jam1a5b5582017-05-01 16:50:10128 }
129
kalman6f984ae2015-09-18 17:21:58130 protected:
131 // Returns the ProcessManager for the test's profile.
132 ProcessManager* process_manager() { return ProcessManager::Get(profile()); }
133
134 // Starts running a test from the background page test extension.
135 //
136 // This registers a service worker with |script_name|, and fetches the
137 // registration result.
Istiaque Ahmed93ff7f42018-08-31 01:42:22138 const Extension* StartTestFromBackgroundPage(const char* script_name) {
Istiaque Ahmed6475f542018-08-28 04:20:21139 ExtensionTestMessageListener ready_listener("ready", false);
kalman6f984ae2015-09-18 17:21:58140 const Extension* extension =
141 LoadExtension(test_data_dir_.AppendASCII("service_worker/background"));
142 CHECK(extension);
Istiaque Ahmed6475f542018-08-28 04:20:21143 CHECK(ready_listener.WaitUntilSatisfied());
144
kalman6f984ae2015-09-18 17:21:58145 ExtensionHost* background_host =
146 process_manager()->GetBackgroundHostForExtension(extension->id());
147 CHECK(background_host);
Istiaque Ahmed6475f542018-08-28 04:20:21148
kalman6f984ae2015-09-18 17:21:58149 std::string error;
150 CHECK(content::ExecuteScriptAndExtractString(
151 background_host->host_contents(),
152 base::StringPrintf("test.registerServiceWorker('%s')", script_name),
153 &error));
Istiaque Ahmed93ff7f42018-08-31 01:42:22154 if (!error.empty())
kalman6f984ae2015-09-18 17:21:58155 ADD_FAILURE() << "Got unexpected error " << error;
156 return extension;
157 }
158
159 // Navigates the browser to a new tab at |url|, waits for it to load, then
160 // returns it.
161 content::WebContents* Navigate(const GURL& url) {
162 ui_test_utils::NavigateToURLWithDisposition(
nick3b04f322016-08-31 19:29:19163 browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
kalman6f984ae2015-09-18 17:21:58164 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
165 content::WebContents* web_contents =
166 browser()->tab_strip_model()->GetActiveWebContents();
167 content::WaitForLoadStop(web_contents);
168 return web_contents;
169 }
170
171 // Navigates the browser to |url| and returns the new tab's page type.
172 content::PageType NavigateAndGetPageType(const GURL& url) {
clamy1d7a4112018-06-15 15:47:16173 return Navigate(url)
174 ->GetController()
175 .GetLastCommittedEntry()
176 ->GetPageType();
kalman6f984ae2015-09-18 17:21:58177 }
178
179 // Extracts the innerText from |contents|.
180 std::string ExtractInnerText(content::WebContents* contents) {
181 std::string inner_text;
182 if (!content::ExecuteScriptAndExtractString(
183 contents,
184 "window.domAutomationController.send(document.body.innerText)",
185 &inner_text)) {
186 ADD_FAILURE() << "Failed to get inner text for "
187 << contents->GetVisibleURL();
188 }
189 return inner_text;
190 }
191
192 // Navigates the browser to |url|, then returns the innerText of the new
193 // tab's WebContents' main frame.
194 std::string NavigateAndExtractInnerText(const GURL& url) {
195 return ExtractInnerText(Navigate(url));
196 }
197
lazyboy4c82177a2016-10-18 00:04:09198 size_t GetWorkerRefCount(const GURL& origin) {
199 content::ServiceWorkerContext* sw_context =
200 content::BrowserContext::GetDefaultStoragePartition(
201 browser()->profile())
202 ->GetServiceWorkerContext();
203 base::RunLoop run_loop;
204 size_t ref_count = 0;
205 auto set_ref_count = [](size_t* ref_count, base::RunLoop* run_loop,
206 size_t external_request_count) {
207 *ref_count = external_request_count;
208 run_loop->Quit();
209 };
210 sw_context->CountExternalRequestsForTest(
Matt Falkenhagenc5cb4282017-09-07 08:43:42211 origin, base::BindOnce(set_ref_count, &ref_count, &run_loop));
lazyboy4c82177a2016-10-18 00:04:09212 run_loop.Run();
213 return ref_count;
214 }
215
annekao38685502015-07-14 17:46:39216 private:
lazyboy20167c22016-05-18 00:59:30217 // Sets the channel to "stable".
218 // Not useful after we've opened extension Service Workers to stable
219 // channel.
220 // TODO(lazyboy): Remove this when ExtensionServiceWorkersEnabled() is
221 // removed.
annekao38685502015-07-14 17:46:39222 ScopedCurrentChannel current_channel_;
kalman6f984ae2015-09-18 17:21:58223
annekao38685502015-07-14 17:46:39224 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerTest);
225};
226
Istiaque Ahmedccb444022018-06-19 02:11:12227class ServiceWorkerBasedBackgroundTest : public ServiceWorkerTest {
228 public:
229 ServiceWorkerBasedBackgroundTest()
230 : ServiceWorkerTest(
231 // Extensions APIs from SW are only enabled on trunk.
232 // It is important to set the channel early so that this change is
233 // visible in renderers running with service workers (and no
234 // extension).
235 version_info::Channel::UNKNOWN) {}
236 ~ServiceWorkerBasedBackgroundTest() override {}
237
238 void SetUpOnMainThread() override {
239 host_resolver()->AddRule("*", "127.0.0.1");
240 ASSERT_TRUE(embedded_test_server()->Start());
241 ServiceWorkerTest::SetUpOnMainThread();
242 }
243
Istiaque Ahmedd4b67ee2019-03-02 10:53:20244 // Returns the only running worker id for |extension_id|.
245 // Returns base::nullopt if there isn't any worker running or more than one
246 // worker is running for |extension_id|.
247 base::Optional<WorkerId> GetUniqueRunningWorkerId(
248 const ExtensionId& extension_id) {
249 ProcessManager* process_manager = ProcessManager::Get(profile());
250 std::vector<WorkerId> all_workers =
251 process_manager->GetAllWorkersIdsForTesting();
252 base::Optional<WorkerId> running_worker_id;
253 for (const WorkerId& worker_id : all_workers) {
254 if (worker_id.extension_id == extension_id) {
255 if (running_worker_id) // More than one worker present.
256 return base::nullopt;
257 running_worker_id = worker_id;
258 }
259 }
260 return running_worker_id;
261 }
262
David Bertoni023e0ec2019-06-10 17:28:22263 bool ExtensionHasRenderProcessHost(const ExtensionId& extension_id) {
264 ProcessMap* process_map = ProcessMap::Get(browser()->profile());
265 content::RenderProcessHost::iterator it =
266 content::RenderProcessHost::AllHostsIterator();
267 while (!it.IsAtEnd()) {
268 if (process_map->Contains(extension_id, it.GetCurrentValue()->GetID())) {
269 return true;
270 }
271 it.Advance();
272 }
273 return false;
274 }
275
Istiaque Ahmedccb444022018-06-19 02:11:12276 private:
277 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerBasedBackgroundTest);
278};
279
Istiaque Ahmed242a4102019-06-25 01:47:57280class ServiceWorkerBasedBackgroundTestWithNotification
281 : public ServiceWorkerBasedBackgroundTest {
282 public:
283 ServiceWorkerBasedBackgroundTestWithNotification() {}
284 ~ServiceWorkerBasedBackgroundTestWithNotification() override = default;
285
286 void SetUpOnMainThread() override {
287 ServiceWorkerBasedBackgroundTest::SetUpOnMainThread();
288 display_service_tester_ =
289 std::make_unique<NotificationDisplayServiceTester>(
290 browser()->profile());
291 }
292
293 void TearDownOnMainThread() override {
294 display_service_tester_.reset();
295 ServiceWorkerBasedBackgroundTest::TearDownOnMainThread();
296 }
297
298 protected:
299 // Returns a vector with the Notification objects that are being displayed
300 // by the notification display service. Synchronous.
301 std::vector<message_center::Notification> GetDisplayedNotifications() const {
302 return display_service_tester_->GetDisplayedNotificationsForType(
303 NotificationHandler::Type::WEB_PERSISTENT);
304 }
305
306 std::unique_ptr<NotificationDisplayServiceTester> display_service_tester_;
307
308 private:
309 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerBasedBackgroundTestWithNotification);
310};
311
Istiaque Ahmedccb444022018-06-19 02:11:12312// Tests that Service Worker based background pages can be loaded and they can
313// receive extension events.
314// The extension is installed and loaded during this step and it registers
315// an event listener for tabs.onCreated event. The step also verifies that tab
316// creation correctly fires the listener.
Devlin Cronin242d19d22019-03-12 18:08:48317IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, PRE_Basic) {
Istiaque Ahmedccb444022018-06-19 02:11:12318 ExtensionTestMessageListener newtab_listener("CREATED", false);
319 newtab_listener.set_failure_message("CREATE_FAILED");
320 ExtensionTestMessageListener worker_listener("WORKER_RUNNING", false);
321 worker_listener.set_failure_message("NON_WORKER_SCOPE");
322 const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(
323 "service_worker/worker_based_background/basic"));
324 ASSERT_TRUE(extension);
325 const ExtensionId extension_id = extension->id();
326 EXPECT_TRUE(worker_listener.WaitUntilSatisfied());
327
328 const GURL url = embedded_test_server()->GetURL("/extensions/test_file.html");
Istiaque Ahmed3f692562019-07-26 22:59:26329 content::WebContents* new_web_contents =
330 browsertest_util::AddTab(browser(), url);
Istiaque Ahmedccb444022018-06-19 02:11:12331 EXPECT_TRUE(new_web_contents);
332 EXPECT_TRUE(newtab_listener.WaitUntilSatisfied());
333
334 // Service Worker extension does not have ExtensionHost.
335 EXPECT_FALSE(process_manager()->GetBackgroundHostForExtension(extension_id));
336}
337
338// After browser restarts, this test step ensures that opening a tab fires
339// tabs.onCreated event listener to the extension without explicitly loading the
340// extension. This is because the extension registered a listener before browser
341// restarted in PRE_Basic.
Devlin Cronin242d19d22019-03-12 18:08:48342IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, Basic) {
Istiaque Ahmedccb444022018-06-19 02:11:12343 ExtensionTestMessageListener newtab_listener("CREATED", false);
344 newtab_listener.set_failure_message("CREATE_FAILED");
345 const GURL url = embedded_test_server()->GetURL("/extensions/test_file.html");
Istiaque Ahmed3f692562019-07-26 22:59:26346 content::WebContents* new_web_contents =
347 browsertest_util::AddTab(browser(), url);
Istiaque Ahmedccb444022018-06-19 02:11:12348 EXPECT_TRUE(new_web_contents);
349 EXPECT_TRUE(newtab_listener.WaitUntilSatisfied());
350}
351
Istiaque Ahmedbf08f952018-10-02 01:22:04352// Tests chrome.runtime.onInstalled fires for extension service workers.
Devlin Cronin242d19d22019-03-12 18:08:48353IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, OnInstalledEvent) {
Istiaque Ahmedbf08f952018-10-02 01:22:04354 ASSERT_TRUE(RunExtensionTest(
355 "service_worker/worker_based_background/events_on_installed"))
356 << message_;
357}
358
Istiaque Ahmedba8d0652019-05-14 15:17:34359// Tests chrome.runtime.id and chrome.runtime.getURL().
360IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, RuntimeMisc) {
361 ASSERT_TRUE(
362 RunExtensionTest("service_worker/worker_based_background/runtime_misc"))
363 << message_;
364}
365
David Bertoni69982832019-02-13 21:24:21366// Tests chrome.storage APIs.
Devlin Cronin242d19d22019-03-12 18:08:48367IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, StorageSetAndGet) {
David Bertoni69982832019-02-13 21:24:21368 ASSERT_TRUE(
369 RunExtensionTest("service_worker/worker_based_background/storage"))
370 << message_;
371}
372
David Bertoni0665c892019-02-14 00:27:26373// Tests chrome.storage.local and chrome.storage.local APIs.
Devlin Cronin242d19d22019-03-12 18:08:48374IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, StorageNoPermissions) {
David Bertoni0665c892019-02-14 00:27:26375 ASSERT_TRUE(RunExtensionTest(
376 "service_worker/worker_based_background/storage_no_permissions"))
377 << message_;
378}
379
David Bertoni30809312019-02-28 22:56:05380// Tests chrome.tabs APIs.
Devlin Cronin242d19d22019-03-12 18:08:48381IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, TabsBasic) {
David Bertoni30809312019-02-28 22:56:05382 ASSERT_TRUE(
383 RunExtensionTest("service_worker/worker_based_background/tabs_basic"))
384 << message_;
385}
386
David Bertoni46d698892019-02-26 00:29:10387// Tests chrome.tabs events.
Devlin Cronin242d19d22019-03-12 18:08:48388IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, TabsEvents) {
David Bertoni46d698892019-02-26 00:29:10389 ASSERT_TRUE(
390 RunExtensionTest("service_worker/worker_based_background/tabs_events"))
391 << message_;
392}
393
David Bertoni4c7dfcc2019-03-27 23:49:34394// Tests chrome.tabs APIs.
395IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, TabsExecuteScript) {
396 ASSERT_TRUE(RunExtensionTest(
397 "service_worker/worker_based_background/tabs_execute_script"))
398 << message_;
399}
400
David Bertoni37ae0222019-04-04 01:30:54401// Tests chrome.webRequest APIs.
David Bertoni3929f552019-03-28 22:10:36402IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, WebRequest) {
403 ASSERT_TRUE(
404 RunExtensionTest("service_worker/worker_based_background/web_request"))
405 << message_;
406}
407
David Bertoni37ae0222019-04-04 01:30:54408// Tests chrome.webRequest APIs in blocking mode.
409IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, WebRequestBlocking) {
410 // Try to load the page before installing the extension, which should work.
411 const GURL url = embedded_test_server()->GetURL("/extensions/test_file.html");
412 EXPECT_EQ(content::PAGE_TYPE_NORMAL, NavigateAndGetPageType(url));
413
414 // Install the extension and navigate again to the page.
415 ExtensionTestMessageListener ready_listener("ready", false);
416 ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII(
417 "service_worker/worker_based_background/web_request_blocking")));
418 ASSERT_TRUE(ready_listener.WaitUntilSatisfied());
419 EXPECT_EQ(content::PAGE_TYPE_ERROR, NavigateAndGetPageType(url));
420}
421
David Bertoni377f52312019-05-21 20:35:03422// Tests chrome.webNavigation APIs.
423IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, FilteredEvents) {
424 ASSERT_TRUE(RunExtensionTest(
425 "service_worker/worker_based_background/filtered_events"))
426 << message_;
427}
428
Istiaque Ahmed70f76ac2018-11-02 02:59:55429// Listens for |message| from extension Service Worker early so that tests can
430// wait for the message on startup (and not miss it).
431class ServiceWorkerWithEarlyMessageListenerTest
432 : public ServiceWorkerBasedBackgroundTest {
Istiaque Ahmedf70ab222018-10-02 03:08:24433 public:
Istiaque Ahmed70f76ac2018-11-02 02:59:55434 explicit ServiceWorkerWithEarlyMessageListenerTest(
435 const std::string& test_message)
436 : test_message_(test_message) {}
437 ~ServiceWorkerWithEarlyMessageListenerTest() override = default;
Istiaque Ahmedf70ab222018-10-02 03:08:24438
Istiaque Ahmed70f76ac2018-11-02 02:59:55439 bool WaitForMessage() { return listener_->WaitUntilSatisfied(); }
Istiaque Ahmedf70ab222018-10-02 03:08:24440
441 void CreatedBrowserMainParts(content::BrowserMainParts* main_parts) override {
442 // At this point, the notification service is initialized but the profile
443 // and extensions have not.
Istiaque Ahmed70f76ac2018-11-02 02:59:55444 listener_ =
445 std::make_unique<ExtensionTestMessageListener>(test_message_, false);
Istiaque Ahmedf70ab222018-10-02 03:08:24446 ServiceWorkerBasedBackgroundTest::CreatedBrowserMainParts(main_parts);
447 }
448
449 private:
Istiaque Ahmed70f76ac2018-11-02 02:59:55450 const std::string test_message_;
Istiaque Ahmedf70ab222018-10-02 03:08:24451 std::unique_ptr<ExtensionTestMessageListener> listener_;
452
Istiaque Ahmed70f76ac2018-11-02 02:59:55453 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerWithEarlyMessageListenerTest);
454};
455
456class ServiceWorkerOnStartupEventTest
457 : public ServiceWorkerWithEarlyMessageListenerTest {
458 public:
459 ServiceWorkerOnStartupEventTest()
460 : ServiceWorkerWithEarlyMessageListenerTest("onStartup event") {}
461 ~ServiceWorkerOnStartupEventTest() override = default;
462
463 private:
464 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerOnStartupEventTest);
Istiaque Ahmedf70ab222018-10-02 03:08:24465};
466
467// Tests "runtime.onStartup" for extension SW.
Devlin Cronin242d19d22019-03-12 18:08:48468IN_PROC_BROWSER_TEST_F(ServiceWorkerOnStartupEventTest, PRE_Event) {
Istiaque Ahmedf70ab222018-10-02 03:08:24469 ASSERT_TRUE(RunExtensionTest(
470 "service_worker/worker_based_background/on_startup_event"))
471 << message_;
472}
473
Devlin Cronin242d19d22019-03-12 18:08:48474IN_PROC_BROWSER_TEST_F(ServiceWorkerOnStartupEventTest, Event) {
Istiaque Ahmed70f76ac2018-11-02 02:59:55475 EXPECT_TRUE(WaitForMessage());
476}
477
478class ServiceWorkerRegistrationAtStartupTest
479 : public ServiceWorkerWithEarlyMessageListenerTest,
480 public ServiceWorkerTaskQueue::TestObserver {
481 public:
482 ServiceWorkerRegistrationAtStartupTest()
483 : ServiceWorkerWithEarlyMessageListenerTest("WORKER_RUNNING") {
484 ServiceWorkerTaskQueue::SetObserverForTest(this);
485 }
486 ~ServiceWorkerRegistrationAtStartupTest() override {
487 ServiceWorkerTaskQueue::SetObserverForTest(nullptr);
488 }
489
490 // ServiceWorkerTaskQueue::TestObserver:
491 void OnActivateExtension(const ExtensionId& extension_id,
492 bool will_register_service_worker) override {
493 if (extension_id != kExtensionId)
494 return;
495
496 will_register_service_worker_ = will_register_service_worker;
497
498 extension_activated_ = true;
499 if (run_loop_)
500 run_loop_->Quit();
501 }
502
503 void WaitForOnActivateExtension() {
504 if (extension_activated_)
505 return;
506 run_loop_ = std::make_unique<base::RunLoop>();
507 run_loop_->Run();
508 }
509
510 bool WillRegisterServiceWorker() {
511 return will_register_service_worker_.value();
512 }
513
514 protected:
515 static const char kExtensionId[];
516
517 private:
518 bool extension_activated_ = false;
519 base::Optional<bool> will_register_service_worker_;
520 std::unique_ptr<base::RunLoop> run_loop_;
521
522 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerRegistrationAtStartupTest);
523};
524
525// Test extension id at
526// api_test/service_worker/worker_based_background/registration_at_startup/.
527const char ServiceWorkerRegistrationAtStartupTest::kExtensionId[] =
528 "gnchfmandajfaiajniicagenfmhdjila";
529
530// Tests that Service Worker registration for existing extension isn't issued
531// upon browser restart.
532// Regression test for https://crbug.com/889687.
Devlin Cronin242d19d22019-03-12 18:08:48533IN_PROC_BROWSER_TEST_F(ServiceWorkerRegistrationAtStartupTest,
Istiaque Ahmed70f76ac2018-11-02 02:59:55534 PRE_ExtensionActivationDoesNotReregister) {
535 const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(
536 "service_worker/worker_based_background/registration_at_startup"));
537 ASSERT_TRUE(extension);
538 EXPECT_EQ(kExtensionId, extension->id());
539 // Wait for "WORKER_RUNNING" message from the Service Worker.
540 EXPECT_TRUE(WaitForMessage());
541 EXPECT_TRUE(WillRegisterServiceWorker());
542}
543
Devlin Cronin242d19d22019-03-12 18:08:48544IN_PROC_BROWSER_TEST_F(ServiceWorkerRegistrationAtStartupTest,
Istiaque Ahmed70f76ac2018-11-02 02:59:55545 ExtensionActivationDoesNotReregister) {
546 // Since the extension has onStartup listener, the Service Worker will run on
547 // browser start and we'll see "WORKER_RUNNING" message from the worker.
548 EXPECT_TRUE(WaitForMessage());
549 // As the extension activated during first run on PRE_ step, it shouldn't
550 // re-register the Service Worker upon browser restart.
551 EXPECT_FALSE(WillRegisterServiceWorker());
Istiaque Ahmedf70ab222018-10-02 03:08:24552}
553
Istiaque Ahmeda14ec482018-08-25 01:02:18554// Class that dispatches an event to |extension_id| right after a
555// non-lazy listener to the event is added from the extension's Service Worker.
Istiaque Ahmed771aa8a22018-06-20 23:40:53556class EarlyWorkerMessageSender : public EventRouter::Observer {
557 public:
558 EarlyWorkerMessageSender(content::BrowserContext* browser_context,
Istiaque Ahmeda14ec482018-08-25 01:02:18559 const ExtensionId& extension_id,
560 std::unique_ptr<Event> event)
Istiaque Ahmed771aa8a22018-06-20 23:40:53561 : browser_context_(browser_context),
562 event_router_(EventRouter::EventRouter::Get(browser_context_)),
563 extension_id_(extension_id),
Istiaque Ahmeda14ec482018-08-25 01:02:18564 event_(std::move(event)),
Istiaque Ahmed771aa8a22018-06-20 23:40:53565 listener_("PASS", false) {
566 DCHECK(browser_context_);
567 listener_.set_failure_message("FAIL");
Istiaque Ahmeda14ec482018-08-25 01:02:18568 event_router_->RegisterObserver(this, event_->event_name);
Istiaque Ahmed771aa8a22018-06-20 23:40:53569 }
570
571 ~EarlyWorkerMessageSender() override {
572 event_router_->UnregisterObserver(this);
573 }
574
575 // EventRouter::Observer:
576 void OnListenerAdded(const EventListenerInfo& details) override {
Istiaque Ahmeda14ec482018-08-25 01:02:18577 if (!event_ || extension_id_ != details.extension_id ||
578 event_->event_name != details.event_name) {
Istiaque Ahmed771aa8a22018-06-20 23:40:53579 return;
Istiaque Ahmeda14ec482018-08-25 01:02:18580 }
581
Istiaque Ahmed771aa8a22018-06-20 23:40:53582 const bool is_lazy_listener = details.browser_context == nullptr;
583 if (is_lazy_listener) {
584 // Wait for the non-lazy listener as we want to exercise the code to
585 // dispatch the event right after the Service Worker registration is
586 // completing.
587 return;
588 }
Istiaque Ahmeda14ec482018-08-25 01:02:18589 DispatchEvent(std::move(event_));
Istiaque Ahmed771aa8a22018-06-20 23:40:53590 }
591
592 bool SendAndWait() { return listener_.WaitUntilSatisfied(); }
593
594 private:
595 static constexpr const char* const kTestOnMessageEventName = "test.onMessage";
596
Istiaque Ahmeda14ec482018-08-25 01:02:18597 void DispatchEvent(std::unique_ptr<Event> event) {
Istiaque Ahmed771aa8a22018-06-20 23:40:53598 EventRouter::Get(browser_context_)
599 ->DispatchEventToExtension(extension_id_, std::move(event));
600 }
601
602 content::BrowserContext* const browser_context_ = nullptr;
603 EventRouter* const event_router_ = nullptr;
604 const ExtensionId extension_id_;
Istiaque Ahmeda14ec482018-08-25 01:02:18605 std::unique_ptr<Event> event_;
Istiaque Ahmed771aa8a22018-06-20 23:40:53606 ExtensionTestMessageListener listener_;
Istiaque Ahmed771aa8a22018-06-20 23:40:53607
608 DISALLOW_COPY_AND_ASSIGN(EarlyWorkerMessageSender);
609};
610
611// Tests that extension event dispatch works correctly right after extension
612// installation registers its Service Worker.
613// Regression test for: https://crbug.com/850792.
Devlin Cronin242d19d22019-03-12 18:08:48614IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, EarlyEventDispatch) {
Istiaque Ahmed771aa8a22018-06-20 23:40:53615 const ExtensionId kId("pkplfbidichfdicaijlchgnapepdginl");
Istiaque Ahmeda14ec482018-08-25 01:02:18616
617 // Build "test.onMessage" event for dispatch.
618 auto event = std::make_unique<Event>(
619 events::FOR_TEST, extensions::api::test::OnMessage::kEventName,
Lei Zhang582ecd12019-02-13 20:28:54620 base::ListValue::From(base::JSONReader::ReadDeprecated(
Istiaque Ahmeda14ec482018-08-25 01:02:18621 R"([{"data": "hello", "lastMessage": true}])")),
622 profile());
623
624 EarlyWorkerMessageSender sender(profile(), kId, std::move(event));
Istiaque Ahmed771aa8a22018-06-20 23:40:53625 // pkplfbidichfdicaijlchgnapepdginl
626 const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(
627 "service_worker/worker_based_background/early_event_dispatch"));
628 CHECK(extension);
629 EXPECT_EQ(kId, extension->id());
630 EXPECT_TRUE(sender.SendAndWait());
631}
632
Istiaque Ahmeda14ec482018-08-25 01:02:18633// Tests that filtered events dispatches correctly right after a non-lazy
634// listener is registered for that event (and before the corresponding lazy
635// listener is registered).
Devlin Cronin242d19d22019-03-12 18:08:48636IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
Istiaque Ahmeda14ec482018-08-25 01:02:18637 EarlyFilteredEventDispatch) {
638 const ExtensionId kId("pkplfbidichfdicaijlchgnapepdginl");
639
640 // Add minimal details required to dispatch webNavigation.onCommitted event:
641 extensions::api::web_navigation::OnCommitted::Details details;
642 details.transition_type =
643 extensions::api::web_navigation::TRANSITION_TYPE_TYPED;
644
645 // Build a dummy onCommited event to dispatch.
646 auto on_committed_event = std::make_unique<Event>(
647 events::WEB_NAVIGATION_ON_COMMITTED, "webNavigation.onCommitted",
648 api::web_navigation::OnCommitted::Create(details), profile());
649 // The filter will match the listener filter registered from the extension.
650 EventFilteringInfo info;
651 info.url = GURL("http://foo.com/a.html");
652 on_committed_event->filter_info = info;
653
654 EarlyWorkerMessageSender sender(profile(), kId,
655 std::move(on_committed_event));
656
657 // pkplfbidichfdicaijlchgnapepdginl
658 const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(
659 "service_worker/worker_based_background/early_filtered_event_dispatch"));
660 ASSERT_TRUE(extension);
661 EXPECT_EQ(kId, extension->id());
662 EXPECT_TRUE(sender.SendAndWait());
663}
664
lazyboybd325ae2015-11-18 21:35:26665class ServiceWorkerBackgroundSyncTest : public ServiceWorkerTest {
666 public:
667 ServiceWorkerBackgroundSyncTest() {}
668 ~ServiceWorkerBackgroundSyncTest() override {}
669
670 void SetUpCommandLine(base::CommandLine* command_line) override {
671 // ServiceWorkerRegistration.sync requires experimental flag.
672 command_line->AppendSwitch(
Istiaque Ahmedea5ed5042017-09-25 19:00:16673 ::switches::kEnableExperimentalWebPlatformFeatures);
lazyboybd325ae2015-11-18 21:35:26674 ServiceWorkerTest::SetUpCommandLine(command_line);
675 }
676
677 void SetUp() override {
Robbie McElrathdb12d8e2018-09-18 21:20:40678 content::background_sync_test_util::SetIgnoreNetworkChanges(true);
lazyboybd325ae2015-11-18 21:35:26679 ServiceWorkerTest::SetUp();
680 }
681
682 private:
683 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerBackgroundSyncTest);
684};
685
lazyboy561b7de2015-11-19 19:27:30686class ServiceWorkerPushMessagingTest : public ServiceWorkerTest {
687 public:
688 ServiceWorkerPushMessagingTest()
Sylvain Defresne212b4b02018-10-11 16:32:05689 : scoped_testing_factory_installer_(
690 base::BindRepeating(&gcm::FakeGCMProfileService::Build)),
691 gcm_driver_(nullptr),
692 push_service_(nullptr) {}
693
lazyboy561b7de2015-11-19 19:27:30694 ~ServiceWorkerPushMessagingTest() override {}
695
696 void GrantNotificationPermissionForTest(const GURL& url) {
Peter Beverloodd4ef1e2018-06-21 15:41:04697 NotificationPermissionContext::UpdatePermission(profile(), url.GetOrigin(),
698 CONTENT_SETTING_ALLOW);
lazyboy561b7de2015-11-19 19:27:30699 }
700
701 PushMessagingAppIdentifier GetAppIdentifierForServiceWorkerRegistration(
avia2f4804a2015-12-24 23:11:13702 int64_t service_worker_registration_id,
lazyboy561b7de2015-11-19 19:27:30703 const GURL& origin) {
704 PushMessagingAppIdentifier app_identifier =
705 PushMessagingAppIdentifier::FindByServiceWorker(
706 profile(), origin, service_worker_registration_id);
707
708 EXPECT_FALSE(app_identifier.is_null());
709 return app_identifier;
710 }
711
712 // ExtensionApiTest overrides.
713 void SetUpCommandLine(base::CommandLine* command_line) override {
peter9de96272015-12-04 15:23:27714 command_line->AppendSwitch(
Istiaque Ahmedea5ed5042017-09-25 19:00:16715 ::switches::kEnableExperimentalWebPlatformFeatures);
lazyboy561b7de2015-11-19 19:27:30716 ServiceWorkerTest::SetUpCommandLine(command_line);
717 }
Tanja Gornak89128fd2018-09-18 08:49:34718
lazyboy561b7de2015-11-19 19:27:30719 void SetUpOnMainThread() override {
miguelg9b502862017-04-24 18:13:53720 NotificationDisplayServiceFactory::GetInstance()->SetTestingFactory(
Sylvain Defresne711ff6b2018-10-04 12:33:54721 profile(),
722 base::BindRepeating(&StubNotificationDisplayService::FactoryForTests));
miguelg9b502862017-04-24 18:13:53723
johnmea5045732016-09-08 17:23:29724 gcm::FakeGCMProfileService* gcm_service =
725 static_cast<gcm::FakeGCMProfileService*>(
Tanja Gornak89128fd2018-09-18 08:49:34726 gcm::GCMProfileServiceFactory::GetForProfile(profile()));
johnmea5045732016-09-08 17:23:29727 gcm_driver_ = static_cast<instance_id::FakeGCMDriverForInstanceID*>(
728 gcm_service->driver());
lazyboy561b7de2015-11-19 19:27:30729 push_service_ = PushMessagingServiceFactory::GetForProfile(profile());
730
731 ServiceWorkerTest::SetUpOnMainThread();
732 }
733
johnmea5045732016-09-08 17:23:29734 instance_id::FakeGCMDriverForInstanceID* gcm_driver() const {
735 return gcm_driver_;
736 }
lazyboy561b7de2015-11-19 19:27:30737 PushMessagingServiceImpl* push_service() const { return push_service_; }
738
739 private:
Sylvain Defresne212b4b02018-10-11 16:32:05740 gcm::GCMProfileServiceFactory::ScopedTestingFactoryInstaller
741 scoped_testing_factory_installer_;
742
johnmea5045732016-09-08 17:23:29743 instance_id::FakeGCMDriverForInstanceID* gcm_driver_;
lazyboy561b7de2015-11-19 19:27:30744 PushMessagingServiceImpl* push_service_;
745
746 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerPushMessagingTest);
747};
748
Istiaque Ahmed805f6a83b2017-10-05 01:23:26749class ServiceWorkerLazyBackgroundTest : public ServiceWorkerTest {
750 public:
Istiaque Ahmed7105f2a2017-10-07 01:11:59751 ServiceWorkerLazyBackgroundTest()
752 : ServiceWorkerTest(
753 // Extensions APIs from SW are only enabled on trunk.
754 // It is important to set the channel early so that this change is
755 // visible in renderers running with service workers (and no
756 // extension).
757 version_info::Channel::UNKNOWN) {}
Istiaque Ahmed805f6a83b2017-10-05 01:23:26758 ~ServiceWorkerLazyBackgroundTest() override {}
759
760 void SetUpCommandLine(base::CommandLine* command_line) override {
761 ServiceWorkerTest::SetUpCommandLine(command_line);
762 // Disable background network activity as it can suddenly bring the Lazy
763 // Background Page alive.
764 command_line->AppendSwitch(::switches::kDisableBackgroundNetworking);
765 command_line->AppendSwitch(::switches::kNoProxyServer);
766 }
767
768 void SetUpInProcessBrowserTestFixture() override {
769 ServiceWorkerTest::SetUpInProcessBrowserTestFixture();
770 // Set shorter delays to prevent test timeouts.
771 ProcessManager::SetEventPageIdleTimeForTesting(1);
772 ProcessManager::SetEventPageSuspendingTimeForTesting(1);
773 }
774
775 private:
776 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerLazyBackgroundTest);
777};
778
Devlin Cronin242d19d22019-03-12 18:08:48779IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, RegisterSucceeds) {
Istiaque Ahmed93ff7f42018-08-31 01:42:22780 StartTestFromBackgroundPage("register.js");
annekao38685502015-07-14 17:46:39781}
782
Devlin Cronin242d19d22019-03-12 18:08:48783IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, UpdateRefreshesServiceWorker) {
Francois Doraye6fb2d02017-10-18 21:29:13784 base::ScopedAllowBlockingForTesting allow_blocking;
lazyboyc3e763a2015-12-09 23:09:58785 base::ScopedTempDir scoped_temp_dir;
786 ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
787 base::FilePath pem_path = test_data_dir_.AppendASCII("service_worker")
788 .AppendASCII("update")
789 .AppendASCII("service_worker.pem");
vabr9142fe22016-09-08 13:19:22790 base::FilePath path_v1 =
791 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
792 .AppendASCII("update")
793 .AppendASCII("v1"),
794 scoped_temp_dir.GetPath().AppendASCII("v1.crx"),
795 pem_path, base::FilePath());
796 base::FilePath path_v2 =
797 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
798 .AppendASCII("update")
799 .AppendASCII("v2"),
800 scoped_temp_dir.GetPath().AppendASCII("v2.crx"),
801 pem_path, base::FilePath());
lazyboyc3e763a2015-12-09 23:09:58802 const char* kId = "hfaanndiiilofhfokeanhddpkfffchdi";
803
804 ExtensionTestMessageListener listener_v1("Pong from version 1", false);
805 listener_v1.set_failure_message("FAILURE_V1");
806 // Install version 1.0 of the extension.
807 ASSERT_TRUE(InstallExtension(path_v1, 1));
808 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
809 ->enabled_extensions()
810 .GetByID(kId));
811 EXPECT_TRUE(listener_v1.WaitUntilSatisfied());
812
813 ExtensionTestMessageListener listener_v2("Pong from version 2", false);
814 listener_v2.set_failure_message("FAILURE_V2");
815
816 // Update to version 2.0.
817 EXPECT_TRUE(UpdateExtension(kId, path_v2, 0));
818 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
819 ->enabled_extensions()
820 .GetByID(kId));
821 EXPECT_TRUE(listener_v2.WaitUntilSatisfied());
822}
823
[email protected]2ef85d562017-09-15 18:41:52824// TODO(crbug.com/765736) Fix the test.
Devlin Cronin242d19d22019-03-12 18:08:48825IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, DISABLED_UpdateWithoutSkipWaiting) {
Francois Doraye6fb2d02017-10-18 21:29:13826 base::ScopedAllowBlockingForTesting allow_blocking;
lazyboy22eddc712015-12-10 21:16:26827 base::ScopedTempDir scoped_temp_dir;
828 ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
829 base::FilePath pem_path = test_data_dir_.AppendASCII("service_worker")
830 .AppendASCII("update_without_skip_waiting")
831 .AppendASCII("update_without_skip_waiting.pem");
vabr9142fe22016-09-08 13:19:22832 base::FilePath path_v1 =
833 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
834 .AppendASCII("update_without_skip_waiting")
835 .AppendASCII("v1"),
836 scoped_temp_dir.GetPath().AppendASCII("v1.crx"),
837 pem_path, base::FilePath());
838 base::FilePath path_v2 =
839 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
840 .AppendASCII("update_without_skip_waiting")
841 .AppendASCII("v2"),
842 scoped_temp_dir.GetPath().AppendASCII("v2.crx"),
843 pem_path, base::FilePath());
lazyboy22eddc712015-12-10 21:16:26844 const char* kId = "mhnnnflgagdakldgjpfcofkiocpdmogl";
845
846 // Install version 1.0 of the extension.
847 ASSERT_TRUE(InstallExtension(path_v1, 1));
848 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
849 ->enabled_extensions()
850 .GetByID(kId));
851 const Extension* extension = extensions::ExtensionRegistry::Get(profile())
852 ->enabled_extensions()
853 .GetByID(kId);
854
855 ExtensionTestMessageListener listener1("Pong from version 1", false);
856 listener1.set_failure_message("FAILURE");
Istiaque Ahmed3f692562019-07-26 22:59:26857 content::WebContents* web_contents = browsertest_util::AddTab(
858 browser(), extension->GetResourceURL("page.html"));
lazyboy22eddc712015-12-10 21:16:26859 EXPECT_TRUE(listener1.WaitUntilSatisfied());
860
861 // Update to version 2.0.
862 EXPECT_TRUE(UpdateExtension(kId, path_v2, 0));
863 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
864 ->enabled_extensions()
865 .GetByID(kId));
866 const Extension* extension_after_update =
867 extensions::ExtensionRegistry::Get(profile())
868 ->enabled_extensions()
869 .GetByID(kId);
870
871 // Service worker version 2 would be installed but it won't be controlling
872 // the extension page yet.
873 ExtensionTestMessageListener listener2("Pong from version 1", false);
874 listener2.set_failure_message("FAILURE");
Istiaque Ahmed3f692562019-07-26 22:59:26875 web_contents = browsertest_util::AddTab(
876 browser(), extension_after_update->GetResourceURL("page.html"));
lazyboy22eddc712015-12-10 21:16:26877 EXPECT_TRUE(listener2.WaitUntilSatisfied());
878
879 // Navigate the tab away from the extension page so that no clients are
880 // using the service worker.
881 // Note that just closing the tab with WebContentsDestroyedWatcher doesn't
882 // seem to be enough because it returns too early.
883 WebContentsLoadStopObserver navigate_away_observer(web_contents);
884 web_contents->GetController().LoadURL(
885 GURL(url::kAboutBlankURL), content::Referrer(), ui::PAGE_TRANSITION_TYPED,
886 std::string());
887 navigate_away_observer.WaitForLoadStop();
888
889 // Now expect service worker version 2 to control the extension page.
890 ExtensionTestMessageListener listener3("Pong from version 2", false);
891 listener3.set_failure_message("FAILURE");
Istiaque Ahmed3f692562019-07-26 22:59:26892 web_contents = browsertest_util::AddTab(
893 browser(), extension_after_update->GetResourceURL("page.html"));
lazyboy22eddc712015-12-10 21:16:26894 EXPECT_TRUE(listener3.WaitUntilSatisfied());
895}
896
Devlin Cronin242d19d22019-03-12 18:08:48897IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, FetchArbitraryPaths) {
Istiaque Ahmed93ff7f42018-08-31 01:42:22898 const Extension* extension = StartTestFromBackgroundPage("fetch.js");
annekao1db36fd2015-07-29 17:09:16899
kalman6f984ae2015-09-18 17:21:58900 // Open some arbirary paths. Their contents should be what the service worker
901 // responds with, which in this case is the path of the fetch.
902 EXPECT_EQ(
903 "Caught a fetch for /index.html",
904 NavigateAndExtractInnerText(extension->GetResourceURL("index.html")));
905 EXPECT_EQ("Caught a fetch for /path/to/other.html",
906 NavigateAndExtractInnerText(
907 extension->GetResourceURL("path/to/other.html")));
908 EXPECT_EQ("Caught a fetch for /some/text/file.txt",
909 NavigateAndExtractInnerText(
910 extension->GetResourceURL("some/text/file.txt")));
911 EXPECT_EQ("Caught a fetch for /no/file/extension",
912 NavigateAndExtractInnerText(
913 extension->GetResourceURL("no/file/extension")));
914 EXPECT_EQ("Caught a fetch for /",
915 NavigateAndExtractInnerText(extension->GetResourceURL("")));
annekao1db36fd2015-07-29 17:09:16916}
917
Devlin Cronin242d19d22019-03-12 18:08:48918IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
Kenichi Ishibashi773b82972018-08-30 07:02:03919 FetchExtensionResourceFromServiceWorker) {
Istiaque Ahmed93ff7f42018-08-31 01:42:22920 const Extension* extension = StartTestFromBackgroundPage("fetch_from_sw.js");
Kenichi Ishibashi773b82972018-08-30 07:02:03921 ASSERT_TRUE(extension);
922
923 // The service worker in this test tries to load 'hello.txt' via fetch()
924 // and sends back the content of the file, which should be 'hello'.
925 const char* kScript = R"(
926 let channel = new MessageChannel();
927 test.waitForMessage(channel.port1).then(message => {
928 window.domAutomationController.send(message);
929 });
930 test.registeredServiceWorker.postMessage(
931 {port: channel.port2}, [channel.port2]);
932 )";
933 EXPECT_EQ("hello", ExecuteScriptInBackgroundPage(extension->id(), kScript));
934}
935
Kenichi Ishibashi09ee5e72018-11-27 07:12:38936// Tests that fetch() from service worker and network fallback
937// go through webRequest.onBeforeRequest API.
Devlin Cronin242d19d22019-03-12 18:08:48938IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, OnBeforeRequest) {
Kenichi Ishibashi09ee5e72018-11-27 07:12:38939 const Extension* extension = LoadExtensionWithFlags(
940 test_data_dir_.AppendASCII("service_worker/webrequest"), kFlagNone);
941 ASSERT_TRUE(extension);
942 ASSERT_TRUE(StartEmbeddedTestServer());
943
944 // Start a service worker and make it control the page.
945 GURL page_url = embedded_test_server()->GetURL(
946 "/extensions/api_test/service_worker/"
947 "webrequest/webpage.html");
948 content::WebContents* web_contents =
949 browser()->tab_strip_model()->GetActiveWebContents();
950 ui_test_utils::NavigateToURL(browser(), page_url);
951 content::WaitForLoadStop(web_contents);
952
953 std::string result;
954 ASSERT_TRUE(content::ExecuteScriptAndExtractString(web_contents,
955 "register();", &result));
956 EXPECT_EQ("ready", result);
957
958 // Initiate a fetch that the service worker doesn't intercept
959 // (network fallback).
960 result.clear();
961 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
962 web_contents, "doFetch('hello.txt?fallthrough');", &result));
963 EXPECT_EQ("hello", result);
964 EXPECT_EQ(
965 "/extensions/api_test/service_worker/webrequest/hello.txt?fallthrough",
966 ExecuteScriptInBackgroundPage(extension->id(), "getLastHookedPath()"));
967
968 // Initiate a fetch that results in calling fetch() in the service worker.
969 result.clear();
970 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
971 web_contents, "doFetch('hello.txt?respondWithFetch');", &result));
972 EXPECT_EQ("hello", result);
973 EXPECT_EQ(
974 "/extensions/api_test/service_worker/webrequest/"
975 "hello.txt?respondWithFetch",
976 ExecuteScriptInBackgroundPage(extension->id(), "getLastHookedPath()"));
977}
978
Devlin Cronin242d19d22019-03-12 18:08:48979IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, SWServedBackgroundPageReceivesEvent) {
lazyboy52c3bcf2016-01-08 00:11:29980 const Extension* extension =
Istiaque Ahmed93ff7f42018-08-31 01:42:22981 StartTestFromBackgroundPage("replace_background.js");
lazyboy52c3bcf2016-01-08 00:11:29982 ExtensionHost* background_page =
983 process_manager()->GetBackgroundHostForExtension(extension->id());
984 ASSERT_TRUE(background_page);
985
986 // Close the background page and start it again so that the service worker
987 // will start controlling pages.
988 background_page->Close();
989 BackgroundPageWatcher(process_manager(), extension).WaitForClose();
990 background_page = nullptr;
Peter Kasting341e1fb2018-02-24 00:03:01991 process_manager()->WakeEventPage(extension->id(), base::DoNothing());
lazyboy52c3bcf2016-01-08 00:11:29992 BackgroundPageWatcher(process_manager(), extension).WaitForOpen();
993
994 // Since the SW is now controlling the extension, the SW serves the background
995 // script. page.html sends a message to the background script and we verify
996 // that the SW served background script correctly receives the message/event.
997 ExtensionTestMessageListener listener("onMessage/SW BG.", false);
998 listener.set_failure_message("onMessage/original BG.");
Istiaque Ahmed3f692562019-07-26 22:59:26999 content::WebContents* web_contents = browsertest_util::AddTab(
1000 browser(), extension->GetResourceURL("page.html"));
lazyboy52c3bcf2016-01-08 00:11:291001 ASSERT_TRUE(web_contents);
1002 EXPECT_TRUE(listener.WaitUntilSatisfied());
1003}
1004
Devlin Cronin242d19d22019-03-12 18:08:481005IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, SWServedBackgroundPage) {
Istiaque Ahmed93ff7f42018-08-31 01:42:221006 const Extension* extension = StartTestFromBackgroundPage("fetch.js");
annekao49241182015-08-18 17:14:011007
kalman6f984ae2015-09-18 17:21:581008 std::string kExpectedInnerText = "background.html contents for testing.";
annekao49241182015-08-18 17:14:011009
kalman6f984ae2015-09-18 17:21:581010 // Sanity check that the background page has the expected content.
1011 ExtensionHost* background_page =
1012 process_manager()->GetBackgroundHostForExtension(extension->id());
1013 ASSERT_TRUE(background_page);
1014 EXPECT_EQ(kExpectedInnerText,
1015 ExtractInnerText(background_page->host_contents()));
annekao49241182015-08-18 17:14:011016
kalman6f984ae2015-09-18 17:21:581017 // Close the background page.
1018 background_page->Close();
1019 BackgroundPageWatcher(process_manager(), extension).WaitForClose();
1020 background_page = nullptr;
1021
1022 // Start it again.
Peter Kasting341e1fb2018-02-24 00:03:011023 process_manager()->WakeEventPage(extension->id(), base::DoNothing());
kalman6f984ae2015-09-18 17:21:581024 BackgroundPageWatcher(process_manager(), extension).WaitForOpen();
1025
Matt Falkenhagena612fc02018-05-30 00:35:391026 // The service worker should get a fetch event for the background page.
kalman6f984ae2015-09-18 17:21:581027 background_page =
1028 process_manager()->GetBackgroundHostForExtension(extension->id());
1029 ASSERT_TRUE(background_page);
1030 content::WaitForLoadStop(background_page->host_contents());
1031
kalman6f984ae2015-09-18 17:21:581032 EXPECT_EQ("Caught a fetch for /background.html",
1033 ExtractInnerText(background_page->host_contents()));
annekao49241182015-08-18 17:14:011034}
1035
Devlin Cronin242d19d22019-03-12 18:08:481036IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
kalman6f984ae2015-09-18 17:21:581037 ServiceWorkerPostsMessageToBackgroundClient) {
Istiaque Ahmed93ff7f42018-08-31 01:42:221038 const Extension* extension =
1039 StartTestFromBackgroundPage("post_message_to_background_client.js");
annekao533482222015-08-21 23:23:531040
kalman6f984ae2015-09-18 17:21:581041 // The service worker in this test simply posts a message to the background
1042 // client it receives from getBackgroundClient().
1043 const char* kScript =
1044 "var messagePromise = null;\n"
1045 "if (test.lastMessageFromServiceWorker) {\n"
1046 " messagePromise = Promise.resolve(test.lastMessageFromServiceWorker);\n"
1047 "} else {\n"
1048 " messagePromise = test.waitForMessage(navigator.serviceWorker);\n"
1049 "}\n"
1050 "messagePromise.then(function(message) {\n"
1051 " window.domAutomationController.send(String(message == 'success'));\n"
1052 "})\n";
1053 EXPECT_EQ("true", ExecuteScriptInBackgroundPage(extension->id(), kScript));
annekao533482222015-08-21 23:23:531054}
1055
Devlin Cronin242d19d22019-03-12 18:08:481056IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
kalman6f984ae2015-09-18 17:21:581057 BackgroundPagePostsMessageToServiceWorker) {
1058 const Extension* extension =
Istiaque Ahmed93ff7f42018-08-31 01:42:221059 StartTestFromBackgroundPage("post_message_to_sw.js");
annekao533482222015-08-21 23:23:531060
kalman6f984ae2015-09-18 17:21:581061 // The service worker in this test waits for a message, then echoes it back
1062 // by posting a message to the background page via getBackgroundClient().
1063 const char* kScript =
1064 "var mc = new MessageChannel();\n"
1065 "test.waitForMessage(mc.port1).then(function(message) {\n"
1066 " window.domAutomationController.send(String(message == 'hello'));\n"
1067 "});\n"
1068 "test.registeredServiceWorker.postMessage(\n"
1069 " {message: 'hello', port: mc.port2}, [mc.port2])\n";
1070 EXPECT_EQ("true", ExecuteScriptInBackgroundPage(extension->id(), kScript));
annekao533482222015-08-21 23:23:531071}
1072
Devlin Cronin242d19d22019-03-12 18:08:481073IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
rdevlin.croninf5863da2015-09-10 19:21:451074 ServiceWorkerSuspensionOnExtensionUnload) {
kalman6f984ae2015-09-18 17:21:581075 // For this test, only hold onto the extension's ID and URL + a function to
1076 // get a resource URL, because we're going to be disabling and uninstalling
1077 // it, which will invalidate the pointer.
1078 std::string extension_id;
1079 GURL extension_url;
1080 {
Istiaque Ahmed93ff7f42018-08-31 01:42:221081 const Extension* extension = StartTestFromBackgroundPage("fetch.js");
kalman6f984ae2015-09-18 17:21:581082 extension_id = extension->id();
1083 extension_url = extension->url();
1084 }
1085 auto get_resource_url = [&extension_url](const std::string& path) {
1086 return Extension::GetResourceURL(extension_url, path);
1087 };
rdevlin.croninf5863da2015-09-10 19:21:451088
kalman6f984ae2015-09-18 17:21:581089 // Fetch should route to the service worker.
1090 EXPECT_EQ("Caught a fetch for /index.html",
1091 NavigateAndExtractInnerText(get_resource_url("index.html")));
rdevlin.croninf5863da2015-09-10 19:21:451092
kalman6f984ae2015-09-18 17:21:581093 // Disable the extension. Opening the page should fail.
1094 extension_service()->DisableExtension(extension_id,
Minh X. Nguyen45479012017-08-18 21:35:361095 disable_reason::DISABLE_USER_ACTION);
rdevlin.croninf5863da2015-09-10 19:21:451096 base::RunLoop().RunUntilIdle();
rdevlin.croninf5863da2015-09-10 19:21:451097
kalman6f984ae2015-09-18 17:21:581098 EXPECT_EQ(content::PAGE_TYPE_ERROR,
1099 NavigateAndGetPageType(get_resource_url("index.html")));
1100 EXPECT_EQ(content::PAGE_TYPE_ERROR,
1101 NavigateAndGetPageType(get_resource_url("other.html")));
1102
1103 // Re-enable the extension. Opening pages should immediately start to succeed
1104 // again.
rdevlin.croninf5863da2015-09-10 19:21:451105 extension_service()->EnableExtension(extension_id);
1106 base::RunLoop().RunUntilIdle();
1107
kalman6f984ae2015-09-18 17:21:581108 EXPECT_EQ("Caught a fetch for /index.html",
1109 NavigateAndExtractInnerText(get_resource_url("index.html")));
1110 EXPECT_EQ("Caught a fetch for /other.html",
1111 NavigateAndExtractInnerText(get_resource_url("other.html")));
1112 EXPECT_EQ("Caught a fetch for /another.html",
1113 NavigateAndExtractInnerText(get_resource_url("another.html")));
rdevlin.croninf5863da2015-09-10 19:21:451114
kalman6f984ae2015-09-18 17:21:581115 // Uninstall the extension. Opening pages should fail again.
1116 base::string16 error;
1117 extension_service()->UninstallExtension(
Devlin Cronin218df7f2017-11-21 21:41:311118 extension_id, UninstallReason::UNINSTALL_REASON_FOR_TESTING, &error);
kalman6f984ae2015-09-18 17:21:581119 base::RunLoop().RunUntilIdle();
1120
1121 EXPECT_EQ(content::PAGE_TYPE_ERROR,
1122 NavigateAndGetPageType(get_resource_url("index.html")));
1123 EXPECT_EQ(content::PAGE_TYPE_ERROR,
1124 NavigateAndGetPageType(get_resource_url("other.html")));
1125 EXPECT_EQ(content::PAGE_TYPE_ERROR,
1126 NavigateAndGetPageType(get_resource_url("anotherother.html")));
1127 EXPECT_EQ(content::PAGE_TYPE_ERROR,
1128 NavigateAndGetPageType(get_resource_url("final.html")));
1129}
1130
Devlin Cronin242d19d22019-03-12 18:08:481131IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, BackgroundPageIsWokenIfAsleep) {
Istiaque Ahmed93ff7f42018-08-31 01:42:221132 const Extension* extension = StartTestFromBackgroundPage("wake_on_fetch.js");
kalman6f984ae2015-09-18 17:21:581133
1134 // Navigate to special URLs that this test's service worker recognises, each
1135 // making a check then populating the response with either "true" or "false".
1136 EXPECT_EQ("true", NavigateAndExtractInnerText(extension->GetResourceURL(
1137 "background-client-is-awake")));
1138 EXPECT_EQ("true", NavigateAndExtractInnerText(
1139 extension->GetResourceURL("ping-background-client")));
1140 // Ping more than once for good measure.
1141 EXPECT_EQ("true", NavigateAndExtractInnerText(
1142 extension->GetResourceURL("ping-background-client")));
1143
1144 // Shut down the event page. The SW should detect that it's closed, but still
1145 // be able to ping it.
1146 ExtensionHost* background_page =
1147 process_manager()->GetBackgroundHostForExtension(extension->id());
1148 ASSERT_TRUE(background_page);
1149 background_page->Close();
1150 BackgroundPageWatcher(process_manager(), extension).WaitForClose();
1151
1152 EXPECT_EQ("false", NavigateAndExtractInnerText(extension->GetResourceURL(
1153 "background-client-is-awake")));
1154 EXPECT_EQ("true", NavigateAndExtractInnerText(
1155 extension->GetResourceURL("ping-background-client")));
1156 EXPECT_EQ("true", NavigateAndExtractInnerText(
1157 extension->GetResourceURL("ping-background-client")));
1158 EXPECT_EQ("true", NavigateAndExtractInnerText(extension->GetResourceURL(
1159 "background-client-is-awake")));
1160}
1161
Devlin Cronin242d19d22019-03-12 18:08:481162IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
kalman6f984ae2015-09-18 17:21:581163 GetBackgroundClientFailsWithNoBackgroundPage) {
1164 // This extension doesn't have a background page, only a tab at page.html.
1165 // The service worker it registers tries to call getBackgroundClient() and
1166 // should fail.
1167 // Note that this also tests that service workers can be registered from tabs.
1168 EXPECT_TRUE(RunExtensionSubtest("service_worker/no_background", "page.html"));
rdevlin.croninf5863da2015-09-10 19:21:451169}
1170
Devlin Cronin242d19d22019-03-12 18:08:481171IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, NotificationAPI) {
lazyboy6ddb7d62015-11-10 23:15:271172 EXPECT_TRUE(RunExtensionSubtest("service_worker/notifications/has_permission",
1173 "page.html"));
1174}
1175
Devlin Cronin242d19d22019-03-12 18:08:481176IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, WebAccessibleResourcesFetch) {
lazyboyaea32c22016-01-04 21:37:071177 EXPECT_TRUE(RunExtensionSubtest(
1178 "service_worker/web_accessible_resources/fetch/", "page.html"));
1179}
1180
David Bertoni9026eff2019-05-01 18:04:311181// Tests that updating a packed extension with modified scripts works
1182// properly -- we expect that the new script will execute, rather than the
1183// previous one.
1184IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, UpdatePackedExtension) {
1185 // Extensions APIs from SW are only enabled on trunk.
1186 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
1187 constexpr char kManifest1[] =
1188 R"({
1189 "name": "Test Extension",
1190 "manifest_version": 2,
1191 "version": "0.1",
1192 "background": {"service_worker": "script.js"}
1193 })";
David Bertoni353f0fb42019-05-30 15:53:301194 constexpr char kNewVersionString[] = "0.2";
1195
David Bertoni9026eff2019-05-01 18:04:311196 // This script installs an event listener for updates to the extension with
1197 // a callback that forces itself to reload.
David Bertoni353f0fb42019-05-30 15:53:301198 constexpr char kScript1[] =
David Bertoni9026eff2019-05-01 18:04:311199 R"(
1200 chrome.runtime.onUpdateAvailable.addListener(function(details) {
David Bertoni353f0fb42019-05-30 15:53:301201 chrome.test.assertEq('%s', details.version);
David Bertoni9026eff2019-05-01 18:04:311202 chrome.runtime.reload();
1203 });
1204 chrome.test.sendMessage('ready1');
1205 )";
1206
1207 std::string id;
1208 TestExtensionDir test_dir;
1209
1210 // Write the manifest and script files and load the extension.
1211 test_dir.WriteManifest(kManifest1);
David Bertoni353f0fb42019-05-30 15:53:301212 test_dir.WriteFile(FILE_PATH_LITERAL("script.js"),
1213 base::StringPrintf(kScript1, kNewVersionString));
David Bertoni9026eff2019-05-01 18:04:311214
1215 {
1216 ExtensionTestMessageListener ready_listener("ready1", false);
1217 base::FilePath path = test_dir.Pack();
1218 const Extension* extension = LoadExtension(path);
1219 ASSERT_TRUE(extension);
1220
1221 EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
1222 id = extension->id();
1223 }
1224
1225 constexpr char kManifest2[] =
1226 R"({
1227 "name": "Test Extension",
1228 "manifest_version": 2,
David Bertoni353f0fb42019-05-30 15:53:301229 "version": "%s",
David Bertoni9026eff2019-05-01 18:04:311230 "background": {"service_worker": "script.js"}
1231 })";
David Bertoni353f0fb42019-05-30 15:53:301232 constexpr char kScript2[] =
1233 R"(
1234 chrome.runtime.onInstalled.addListener(function(details) {
1235 chrome.test.assertEq('update', details.reason);
1236 chrome.test.sendMessage('onInstalled');
1237 });
1238 chrome.test.sendMessage('ready2');
1239 )";
David Bertoni9026eff2019-05-01 18:04:311240 // Rewrite the manifest and script files with a version change in the manifest
1241 // file. After reloading the extension, the old version of the extension
1242 // should detect the update, force the reload, and the new script should
1243 // execute.
David Bertoni353f0fb42019-05-30 15:53:301244 test_dir.WriteManifest(base::StringPrintf(kManifest2, kNewVersionString));
1245 test_dir.WriteFile(FILE_PATH_LITERAL("script.js"), kScript2);
David Bertoni9026eff2019-05-01 18:04:311246 {
1247 ExtensionTestMessageListener ready_listener("ready2", false);
David Bertoni353f0fb42019-05-30 15:53:301248 ExtensionTestMessageListener on_installed_listener("onInstalled", false);
David Bertoni9026eff2019-05-01 18:04:311249 base::FilePath path = test_dir.Pack();
1250 ExtensionService* const extension_service =
1251 ExtensionSystem::Get(profile())->extension_service();
1252 EXPECT_TRUE(extension_service->UpdateExtension(
1253 CRXFileInfo(id, GetTestVerifierFormat(), path), true, nullptr));
1254 EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
1255 EXPECT_EQ("0.2", ExtensionRegistry::Get(profile())
1256 ->enabled_extensions()
1257 .GetByID(id)
1258 ->version()
1259 .GetString());
David Bertoni353f0fb42019-05-30 15:53:301260 EXPECT_TRUE(on_installed_listener.WaitUntilSatisfied());
David Bertoni9026eff2019-05-01 18:04:311261 }
1262}
1263
David Bertoni1d646a152019-04-25 02:09:221264// Tests that updating an unpacked extension with modified scripts works
1265// properly -- we expect that the new script will execute, rather than the
1266// previous one.
1267IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, UpdateUnpackedExtension) {
1268 // Extensions APIs from SW are only enabled on trunk.
1269 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
1270 constexpr char kManifest1[] =
1271 R"({
1272 "name": "Test Extension",
1273 "manifest_version": 2,
1274 "version": "0.1",
1275 "background": {"service_worker": "script.js"}
1276 })";
1277 constexpr char kManifest2[] =
1278 R"({
1279 "name": "Test Extension",
1280 "manifest_version": 2,
1281 "version": "0.2",
1282 "background": {"service_worker": "script.js"}
1283 })";
David Bertoni353f0fb42019-05-30 15:53:301284 constexpr char kScript[] =
1285 R"(
1286 chrome.runtime.onInstalled.addListener(function(details) {
1287 chrome.test.assertEq('%s', details.reason);
1288 chrome.test.sendMessage('onInstalled');
1289 });
1290 chrome.test.sendMessage('%s');
1291 )";
David Bertoni1d646a152019-04-25 02:09:221292
1293 std::string id;
1294
1295 ExtensionService* const extension_service =
1296 ExtensionSystem::Get(profile())->extension_service();
1297 scoped_refptr<UnpackedInstaller> installer =
1298 UnpackedInstaller::Create(extension_service);
1299
1300 // Set a completion callback so we can get the ID of the extension.
1301 installer->set_completion_callback(base::BindLambdaForTesting(
1302 [&id](const Extension* extension, const base::FilePath& path,
1303 const std::string& error) {
1304 ASSERT_TRUE(extension);
1305 ASSERT_TRUE(error.empty());
1306 id = extension->id();
1307 }));
1308
1309 TestExtensionDir test_dir;
1310
1311 // Write the manifest and script files and load the extension.
1312 test_dir.WriteManifest(kManifest1);
1313 test_dir.WriteFile(FILE_PATH_LITERAL("script.js"),
David Bertoni353f0fb42019-05-30 15:53:301314 base::StringPrintf(kScript, "install", "ready1"));
David Bertoni1d646a152019-04-25 02:09:221315 {
1316 ExtensionTestMessageListener ready_listener("ready1", false);
David Bertoni353f0fb42019-05-30 15:53:301317 ExtensionTestMessageListener on_installed_listener("onInstalled", false);
David Bertoni1d646a152019-04-25 02:09:221318
1319 installer->Load(test_dir.UnpackedPath());
1320 EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
David Bertoni353f0fb42019-05-30 15:53:301321 EXPECT_TRUE(on_installed_listener.WaitUntilSatisfied());
David Bertoni1d646a152019-04-25 02:09:221322 ASSERT_FALSE(id.empty());
1323 }
1324
1325 // Rewrite the script file without a version change in the manifest and reload
1326 // the extension. The new script should execute.
1327 test_dir.WriteFile(FILE_PATH_LITERAL("script.js"),
David Bertoni353f0fb42019-05-30 15:53:301328 base::StringPrintf(kScript, "update", "ready2"));
David Bertoni1d646a152019-04-25 02:09:221329 {
1330 ExtensionTestMessageListener ready_listener("ready2", false);
David Bertoni353f0fb42019-05-30 15:53:301331 ExtensionTestMessageListener on_installed_listener("onInstalled", false);
David Bertoni1d646a152019-04-25 02:09:221332
1333 extension_service->ReloadExtension(id);
1334 EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
David Bertoni353f0fb42019-05-30 15:53:301335 EXPECT_TRUE(on_installed_listener.WaitUntilSatisfied());
David Bertoni1d646a152019-04-25 02:09:221336 }
1337
1338 // Rewrite the manifest and script files with a version change in the manifest
1339 // file. After reloading the extension, the new script should execute.
1340 test_dir.WriteManifest(kManifest2);
1341 test_dir.WriteFile(FILE_PATH_LITERAL("script.js"),
David Bertoni353f0fb42019-05-30 15:53:301342 base::StringPrintf(kScript, "update", "ready3"));
David Bertoni1d646a152019-04-25 02:09:221343 {
1344 ExtensionTestMessageListener ready_listener("ready3", false);
David Bertoni353f0fb42019-05-30 15:53:301345 ExtensionTestMessageListener on_installed_listener("onInstalled", false);
David Bertoni1d646a152019-04-25 02:09:221346
1347 extension_service->ReloadExtension(id);
1348 EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
David Bertoni353f0fb42019-05-30 15:53:301349 EXPECT_TRUE(on_installed_listener.WaitUntilSatisfied());
David Bertoni1d646a152019-04-25 02:09:221350 }
1351}
1352
lazyboyaea32c22016-01-04 21:37:071353// This test loads a web page that has an iframe pointing to a
1354// chrome-extension:// URL. The URL is listed in the extension's
1355// web_accessible_resources. Initially the iframe is served from the extension's
1356// resource file. After verifying that, we register a Service Worker that
1357// controls the extension. Further requests to the same resource as before
1358// should now be served by the Service Worker.
1359// This test also verifies that if the requested resource exists in the manifest
1360// but is not present in the extension directory, the Service Worker can still
1361// serve the resource file.
Devlin Cronin242d19d22019-03-12 18:08:481362IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, WebAccessibleResourcesIframeSrc) {
lazyboyaea32c22016-01-04 21:37:071363 const Extension* extension = LoadExtensionWithFlags(
1364 test_data_dir_.AppendASCII(
1365 "service_worker/web_accessible_resources/iframe_src"),
1366 kFlagNone);
1367 ASSERT_TRUE(extension);
1368 ASSERT_TRUE(StartEmbeddedTestServer());
falkenad185092016-06-16 06:10:021369
1370 // Service workers can only control secure contexts
1371 // (https://w3c.github.io/webappsec-secure-contexts/). For documents, this
1372 // typically means the document must have a secure origin AND all its ancestor
1373 // frames must have documents with secure origins. However, extension pages
1374 // are considered secure, even if they have an ancestor document that is an
1375 // insecure context (see GetSchemesBypassingSecureContextCheckWhitelist). So
1376 // extension service workers must be able to control an extension page
1377 // embedded in an insecure context. To test this, set up an insecure
1378 // (non-localhost, non-https) URL for the web page. This page will create
1379 // iframes that load extension pages that must be controllable by service
1380 // worker.
falkenad185092016-06-16 06:10:021381 GURL page_url =
1382 embedded_test_server()->GetURL("a.com",
1383 "/extensions/api_test/service_worker/"
1384 "web_accessible_resources/webpage.html");
1385 EXPECT_FALSE(content::IsOriginSecure(page_url));
lazyboyaea32c22016-01-04 21:37:071386
Istiaque Ahmed3f692562019-07-26 22:59:261387 content::WebContents* web_contents =
1388 browsertest_util::AddTab(browser(), page_url);
lazyboyaea32c22016-01-04 21:37:071389 std::string result;
1390 // webpage.html will create an iframe pointing to a resource from |extension|.
1391 // Expect the resource to be served by the extension.
1392 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1393 web_contents, base::StringPrintf("window.testIframe('%s', 'iframe.html')",
1394 extension->id().c_str()),
1395 &result));
1396 EXPECT_EQ("FROM_EXTENSION_RESOURCE", result);
1397
1398 ExtensionTestMessageListener service_worker_ready_listener("SW_READY", false);
1399 EXPECT_TRUE(ExecuteScriptInBackgroundPageNoWait(
1400 extension->id(), "window.registerServiceWorker()"));
1401 EXPECT_TRUE(service_worker_ready_listener.WaitUntilSatisfied());
1402
1403 result.clear();
1404 // webpage.html will create another iframe pointing to a resource from
1405 // |extension| as before. But this time, the resource should be be served
1406 // from the Service Worker.
1407 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1408 web_contents, base::StringPrintf("window.testIframe('%s', 'iframe.html')",
1409 extension->id().c_str()),
1410 &result));
1411 EXPECT_EQ("FROM_SW_RESOURCE", result);
1412
1413 result.clear();
1414 // webpage.html will create yet another iframe pointing to a resource that
1415 // exists in the extension manifest's web_accessible_resources, but is not
1416 // present in the extension directory. Expect the resources of the iframe to
1417 // be served by the Service Worker.
1418 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1419 web_contents,
1420 base::StringPrintf("window.testIframe('%s', 'iframe_non_existent.html')",
1421 extension->id().c_str()),
1422 &result));
1423 EXPECT_EQ("FROM_SW_RESOURCE", result);
1424}
1425
David Bertonide552de2019-06-28 19:51:261426// Verifies that service workers that aren't specified as the background script
1427// for the extension do not have extension API bindings.
1428IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, VerifyNoApiBindings) {
1429 // Extensions APIs from SW are only enabled on trunk.
1430 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
1431 const Extension* extension = LoadExtensionWithFlags(
1432 test_data_dir_.AppendASCII("service_worker/verify_no_api_bindings"),
1433 kFlagNone);
1434 ASSERT_TRUE(extension);
1435 ui_test_utils::NavigateToURL(browser(),
1436 extension->GetResourceURL("page.html"));
1437 content::WebContents* web_contents =
1438 browser()->tab_strip_model()->GetActiveWebContents();
1439
1440 // Have the page script start the service worker and wait for that to
1441 // succeed.
1442 ExtensionTestMessageListener worker_start_listener("WORKER STARTED", false);
1443 worker_start_listener.set_failure_message("FAILURE");
1444 ASSERT_TRUE(
1445 content::ExecuteScript(web_contents, "window.runServiceWorker()"));
1446 ASSERT_TRUE(worker_start_listener.WaitUntilSatisfied());
1447
1448 // Kick off the test, which will check the available bindings and fail if
1449 // there is anything unexpected.
1450 ExtensionTestMessageListener worker_listener("SUCCESS", false);
1451 worker_listener.set_failure_message("FAILURE");
1452 ASSERT_TRUE(content::ExecuteScript(web_contents, "window.testSendMessage()"));
1453 EXPECT_TRUE(worker_listener.WaitUntilSatisfied());
1454}
1455
Devlin Cronin242d19d22019-03-12 18:08:481456IN_PROC_BROWSER_TEST_F(ServiceWorkerBackgroundSyncTest, Sync) {
lazyboybd325ae2015-11-18 21:35:261457 const Extension* extension = LoadExtensionWithFlags(
1458 test_data_dir_.AppendASCII("service_worker/sync"), kFlagNone);
1459 ASSERT_TRUE(extension);
1460 ui_test_utils::NavigateToURL(browser(),
1461 extension->GetResourceURL("page.html"));
1462 content::WebContents* web_contents =
1463 browser()->tab_strip_model()->GetActiveWebContents();
1464
1465 // Prevent firing by going offline.
1466 content::background_sync_test_util::SetOnline(web_contents, false);
1467
1468 ExtensionTestMessageListener sync_listener("SYNC: send-chats", false);
1469 sync_listener.set_failure_message("FAIL");
1470
1471 std::string result;
1472 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
1473 web_contents, "window.runServiceWorker()", &result));
1474 ASSERT_EQ("SERVICE_WORKER_READY", result);
1475
1476 EXPECT_FALSE(sync_listener.was_satisfied());
1477 // Resume firing by going online.
1478 content::background_sync_test_util::SetOnline(web_contents, true);
1479 EXPECT_TRUE(sync_listener.WaitUntilSatisfied());
1480}
1481
Devlin Cronin242d19d22019-03-12 18:08:481482IN_PROC_BROWSER_TEST_F(ServiceWorkerTest,
horo1eeddde2015-11-19 05:59:251483 FetchFromContentScriptShouldNotGoToServiceWorkerOfPage) {
1484 ASSERT_TRUE(StartEmbeddedTestServer());
1485 GURL page_url = embedded_test_server()->GetURL(
1486 "/extensions/api_test/service_worker/content_script_fetch/"
1487 "controlled_page/index.html");
1488 content::WebContents* tab =
1489 browser()->tab_strip_model()->GetActiveWebContents();
1490 ui_test_utils::NavigateToURL(browser(), page_url);
1491 content::WaitForLoadStop(tab);
1492
1493 std::string value;
1494 ASSERT_TRUE(
1495 content::ExecuteScriptAndExtractString(tab, "register();", &value));
1496 EXPECT_EQ("SW controlled", value);
1497
1498 ASSERT_TRUE(RunExtensionTest("service_worker/content_script_fetch"))
1499 << message_;
1500}
1501
Devlin Cronin242d19d22019-03-12 18:08:481502IN_PROC_BROWSER_TEST_F(ServiceWorkerPushMessagingTest, OnPush) {
lazyboy561b7de2015-11-19 19:27:301503 const Extension* extension = LoadExtensionWithFlags(
1504 test_data_dir_.AppendASCII("service_worker/push_messaging"), kFlagNone);
1505 ASSERT_TRUE(extension);
1506 GURL extension_url = extension->url();
1507
Peter Beverloodd4ef1e2018-06-21 15:41:041508 GrantNotificationPermissionForTest(extension_url);
lazyboy561b7de2015-11-19 19:27:301509
1510 GURL url = extension->GetResourceURL("page.html");
1511 ui_test_utils::NavigateToURL(browser(), url);
1512
1513 content::WebContents* web_contents =
1514 browser()->tab_strip_model()->GetActiveWebContents();
1515
1516 // Start the ServiceWorker.
1517 ExtensionTestMessageListener ready_listener("SERVICE_WORKER_READY", false);
1518 ready_listener.set_failure_message("SERVICE_WORKER_FAILURE");
1519 const char* kScript = "window.runServiceWorker()";
1520 EXPECT_TRUE(content::ExecuteScript(web_contents->GetMainFrame(), kScript));
1521 EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
1522
1523 PushMessagingAppIdentifier app_identifier =
1524 GetAppIdentifierForServiceWorkerRegistration(0LL, extension_url);
johnmea5045732016-09-08 17:23:291525 ASSERT_EQ(app_identifier.app_id(), gcm_driver()->last_gettoken_app_id());
1526 EXPECT_EQ("1234567890", gcm_driver()->last_gettoken_authorized_entity());
lazyboy561b7de2015-11-19 19:27:301527
lazyboyd429e2582016-05-20 20:18:521528 base::RunLoop run_loop;
lazyboy561b7de2015-11-19 19:27:301529 // Send a push message via gcm and expect the ServiceWorker to receive it.
1530 ExtensionTestMessageListener push_message_listener("OK", false);
1531 push_message_listener.set_failure_message("FAIL");
1532 gcm::IncomingMessage message;
1533 message.sender_id = "1234567890";
1534 message.raw_data = "testdata";
1535 message.decrypted = true;
lazyboyd429e2582016-05-20 20:18:521536 push_service()->SetMessageCallbackForTesting(run_loop.QuitClosure());
lazyboy561b7de2015-11-19 19:27:301537 push_service()->OnMessage(app_identifier.app_id(), message);
1538 EXPECT_TRUE(push_message_listener.WaitUntilSatisfied());
lazyboyd429e2582016-05-20 20:18:521539 run_loop.Run(); // Wait until the message is handled by push service.
lazyboy561b7de2015-11-19 19:27:301540}
Devlin Cronin242d19d22019-03-12 18:08:481541IN_PROC_BROWSER_TEST_F(ServiceWorkerTest, MimeHandlerView) {
Rob Wue89b90032018-02-16 19:46:081542 ASSERT_TRUE(RunExtensionTest("service_worker/mime_handler_view"));
1543}
1544
David Bertoni3b3597d82019-06-22 02:29:361545// An observer for service worker registration events.
1546class TestRegistrationObserver : public content::ServiceWorkerContextObserver {
David Bertoni22aeae52019-06-10 22:42:531547 public:
David Bertoni3b3597d82019-06-22 02:29:361548 using RegistrationsMap = std::map<GURL, int>;
1549
1550 explicit TestRegistrationObserver(content::ServiceWorkerContext* context)
1551 : context_(context) {
David Bertoni22aeae52019-06-10 22:42:531552 context_->AddObserver(this);
1553 }
1554
David Bertoni3b3597d82019-06-22 02:29:361555 ~TestRegistrationObserver() override {
David Bertoni22aeae52019-06-10 22:42:531556 if (context_) {
1557 context_->RemoveObserver(this);
1558 }
1559 }
1560
David Bertoni3b3597d82019-06-22 02:29:361561 // Wait for the first service worker registration with an extension scheme
1562 // scope to be stored.
1563 void WaitForRegistrationStored() { stored_run_loop_.Run(); }
1564
1565 int GetCompletedCount(const GURL& scope) const {
1566 const auto it = registrations_completed_map_.find(scope);
1567 return it == registrations_completed_map_.end() ? 0 : it->second;
1568 }
1569
1570 private:
1571 // ServiceWorkerContextObserver overrides.
1572 void OnRegistrationCompleted(const GURL& scope) override {
1573 ++registrations_completed_map_[scope];
1574 }
1575
David Bertoni22aeae52019-06-10 22:42:531576 void OnRegistrationStored(int64_t registration_id,
1577 const GURL& scope) override {
1578 if (scope.SchemeIs(kExtensionScheme)) {
David Bertoni3b3597d82019-06-22 02:29:361579 stored_run_loop_.Quit();
David Bertoni22aeae52019-06-10 22:42:531580 }
1581 }
1582
1583 void OnDestruct(content::ServiceWorkerContext* context) override {
1584 context_ = nullptr;
1585 }
1586
David Bertoni3b3597d82019-06-22 02:29:361587 RegistrationsMap registrations_completed_map_;
1588 base::RunLoop stored_run_loop_;
David Bertoni22aeae52019-06-10 22:42:531589 content::ServiceWorkerContext* context_;
David Bertoni22aeae52019-06-10 22:42:531590};
1591
1592IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
1593 EventsToStoppedWorker) {
1594 content::StoragePartition* storage_partition =
1595 content::BrowserContext::GetDefaultStoragePartition(browser()->profile());
1596 content::ServiceWorkerContext* context =
1597 storage_partition->GetServiceWorkerContext();
1598
1599 // Set up an observer to wait for the registration to be stored.
David Bertoni3b3597d82019-06-22 02:29:361600 TestRegistrationObserver observer(context);
David Bertoni22aeae52019-06-10 22:42:531601
1602 ExtensionTestMessageListener event_listener_added("ready", false);
1603 event_listener_added.set_failure_message("ERROR");
1604 const Extension* extension = LoadExtensionWithFlags(
1605 test_data_dir_.AppendASCII(
1606 "service_worker/worker_based_background/events_to_stopped_worker"),
1607 kFlagNone);
1608 ASSERT_TRUE(extension);
1609
David Bertoni3b3597d82019-06-22 02:29:361610 observer.WaitForRegistrationStored();
David Bertoni22aeae52019-06-10 22:42:531611 EXPECT_TRUE(event_listener_added.WaitUntilSatisfied());
1612
1613 // Stop the service worker.
1614 {
1615 base::RunLoop run_loop;
1616 // The service worker is registered at the root scope.
1617 content::StopServiceWorkerForScope(context, extension->url(),
1618 run_loop.QuitClosure());
1619 run_loop.Run();
1620 }
1621
1622 // Navigate to a URL, which should wake up the service worker.
1623 ExtensionTestMessageListener finished_listener("finished", false);
1624 ui_test_utils::NavigateToURL(browser(),
1625 extension->GetResourceURL("page.html"));
1626 EXPECT_TRUE(finished_listener.WaitUntilSatisfied());
1627}
1628
David Bertoni3b3597d82019-06-22 02:29:361629// Tests the restriction on registering service worker scripts at root scope.
1630IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
1631 ServiceWorkerScriptRootScope) {
1632 content::StoragePartition* storage_partition =
1633 content::BrowserContext::GetDefaultStoragePartition(browser()->profile());
1634 content::ServiceWorkerContext* context =
1635 storage_partition->GetServiceWorkerContext();
1636
1637 // Set up an observer to track all SW registrations. We expect only
1638 // one for the extension's root scope. This test attempts to register
1639 // an additional service worker, which will fail.
1640 TestRegistrationObserver observer(context);
1641 ExtensionTestMessageListener registration_listener("REGISTRATION_FAILED",
1642 false);
1643 registration_listener.set_failure_message("WORKER_STARTED");
1644 const Extension* extension = LoadExtensionWithFlags(
1645 test_data_dir_.AppendASCII(
1646 "service_worker/worker_based_background/script_root_scope"),
1647 kFlagNone);
1648 ASSERT_TRUE(extension);
1649
1650 EXPECT_TRUE(registration_listener.WaitUntilSatisfied());
1651 // We expect exactly one registration, which is the one specified in the
1652 // manifest.
1653 EXPECT_EQ(1, observer.GetCompletedCount(extension->url()));
1654}
1655
Devlin Cronin242d19d22019-03-12 18:08:481656IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
Istiaque Ahmedd4b67ee2019-03-02 10:53:201657 ProcessManagerRegistrationOnShutdown) {
1658 // Note that StopServiceWorkerForScope call below expects the worker to be
1659 // completely installed, so wait for the |extension| worker to see "activate"
1660 // event.
1661 ExtensionTestMessageListener activated_listener("WORKER_ACTIVATED", false);
1662 const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(
1663 "service_worker/worker_based_background/process_manager"));
1664 ASSERT_TRUE(extension);
1665 EXPECT_TRUE(activated_listener.WaitUntilSatisfied());
1666
1667 base::Optional<WorkerId> worker_id =
1668 GetUniqueRunningWorkerId(extension->id());
1669 ASSERT_TRUE(worker_id);
1670 {
1671 // Shutdown the worker.
1672 // TODO(lazyboy): Ideally we'd want to test worker shutdown on idle, do that
1673 // once //content API allows to override test timeouts for Service Workers.
1674 base::RunLoop run_loop;
1675 content::StoragePartition* storage_partition =
1676 content::BrowserContext::GetDefaultStoragePartition(
1677 browser()->profile());
1678 GURL scope = extension->url();
1679 content::StopServiceWorkerForScope(
1680 storage_partition->GetServiceWorkerContext(),
1681 // The service worker is registered at the top level scope.
1682 extension->url(), run_loop.QuitClosure());
1683 run_loop.Run();
1684 }
1685
1686 EXPECT_FALSE(ProcessManager::Get(profile())->HasServiceWorker(*worker_id));
1687}
1688
Devlin Cronin242d19d22019-03-12 18:08:481689IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
Istiaque Ahmedd4b67ee2019-03-02 10:53:201690 ProcessManagerRegistrationOnTerminate) {
1691 // NOTE: It is not necessary to wait for "activate" event from the worker
1692 // for this test, but we're lazily reusing the extension from
1693 // ProcessManagerRegistrationOnShutdown test.
1694 ExtensionTestMessageListener activated_listener("WORKER_ACTIVATED", false);
1695 const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(
1696 "service_worker/worker_based_background/process_manager"));
1697 ASSERT_TRUE(extension);
1698 EXPECT_TRUE(activated_listener.WaitUntilSatisfied());
1699
1700 base::Optional<WorkerId> worker_id =
1701 GetUniqueRunningWorkerId(extension->id());
1702 ASSERT_TRUE(worker_id);
1703 {
1704 // Terminate worker's RenderProcessHost.
1705 content::RenderProcessHost* worker_render_process_host =
1706 content::RenderProcessHost::FromID(worker_id->render_process_id);
1707 ASSERT_TRUE(worker_render_process_host);
1708 content::RenderProcessHostWatcher process_exit_observer(
1709 worker_render_process_host,
1710 content::RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
1711 worker_render_process_host->Shutdown(content::RESULT_CODE_KILLED);
1712 process_exit_observer.Wait();
1713 }
1714
1715 EXPECT_FALSE(ProcessManager::Get(profile())->HasServiceWorker(*worker_id));
1716}
1717
David Bertoni904dd602019-06-24 21:42:091718// Tests that worker ref count increments while extension API function is
1719// active.
1720IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, WorkerRefCount) {
1721 ExtensionTestMessageListener worker_start_listener("WORKER STARTED", false);
1722
1723 const Extension* extension = LoadExtensionWithFlags(
1724 test_data_dir_.AppendASCII(
1725 "service_worker/worker_based_background/worker_ref_count"),
1726 kFlagNone);
1727 ASSERT_TRUE(extension);
1728 ASSERT_TRUE(worker_start_listener.WaitUntilSatisfied());
1729
1730 ui_test_utils::NavigateToURL(browser(),
1731 extension->GetResourceURL("page.html"));
1732 content::WebContents* web_contents =
1733 browser()->tab_strip_model()->GetActiveWebContents();
1734
1735 // Service worker should have no pending requests because it hasn't performed
1736 // any extension API request yet.
1737 EXPECT_EQ(0u, GetWorkerRefCount(extension->url()));
1738
1739 ExtensionTestMessageListener worker_listener("CHECK_REF_COUNT", true);
1740 worker_listener.set_failure_message("FAILURE");
1741 ASSERT_TRUE(content::ExecuteScript(web_contents, "window.testSendMessage()"));
1742 ASSERT_TRUE(worker_listener.WaitUntilSatisfied());
1743
1744 // Service worker should have exactly one pending request because
1745 // chrome.test.sendMessage() API call is in-flight.
1746 EXPECT_EQ(1u, GetWorkerRefCount(extension->url()));
1747
1748 // Perform another extension API request while one is ongoing.
1749 {
1750 ExtensionTestMessageListener listener("CHECK_REF_COUNT", true);
1751 listener.set_failure_message("FAILURE");
1752 ASSERT_TRUE(
1753 content::ExecuteScript(web_contents, "window.testSendMessage()"));
1754 ASSERT_TRUE(listener.WaitUntilSatisfied());
1755
1756 // Service worker currently has two extension API requests in-flight.
1757 EXPECT_EQ(2u, GetWorkerRefCount(extension->url()));
1758 // Finish executing the nested chrome.test.sendMessage() first.
1759 listener.Reply("Hello world");
1760 }
1761
1762 ExtensionTestMessageListener worker_completion_listener("SUCCESS_FROM_WORKER",
1763 false);
1764 // Finish executing chrome.test.sendMessage().
1765 worker_listener.Reply("Hello world");
1766 EXPECT_TRUE(worker_completion_listener.WaitUntilSatisfied());
1767
1768 // The following block makes sure we have received all the IPCs related to
1769 // ref-count from the worker.
1770 {
1771 // The following roundtrip:
1772 // browser->extension->worker->extension->browser
1773 // will ensure that the worker sent the relevant ref count IPCs.
1774 std::string result;
1775 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1776 web_contents, "window.roundtripToWorker();", &result));
1777 EXPECT_EQ("roundtrip-succeeded", result);
1778
1779 // Ensure IO thread IPCs run.
1780 content::RunAllTasksUntilIdle();
1781 }
1782
1783 // The ref count should drop to 0.
1784 EXPECT_EQ(0u, GetWorkerRefCount(extension->url()));
1785}
1786
David Bertoni4d9cf41d2019-06-04 00:06:221787IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
1788 PRE_EventsAfterRestart) {
1789 ExtensionTestMessageListener event_added_listener("ready", false);
1790 const Extension* extension = LoadExtensionWithFlags(
1791 test_data_dir_.AppendASCII(
1792 "service_worker/worker_based_background/events_to_stopped_extension"),
1793 kFlagNone);
1794 ASSERT_TRUE(extension);
1795 EXPECT_EQ(kTestExtensionId, extension->id());
1796 ProcessManager* pm = ProcessManager::Get(browser()->profile());
1797 // TODO(crbug.com/969884): This will break once keep alive counts
1798 // for service workers are tracked by the Process Manager.
1799 EXPECT_LT(pm->GetLazyKeepaliveCount(extension), 1);
1800 EXPECT_TRUE(pm->GetLazyKeepaliveActivities(extension).empty());
1801 EXPECT_TRUE(event_added_listener.WaitUntilSatisfied());
1802}
1803
1804// After browser restarts, this test step ensures that opening a tab fires
1805// tabs.onCreated event listener to the extension without explicitly loading the
1806// extension. This is because the extension registered a listener for
1807// tabs.onMoved before browser restarted in PRE_EventsAfterRestart.
1808IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, EventsAfterRestart) {
1809 // Verify there is no RenderProcessHost for the extension.
David Bertoni023e0ec2019-06-10 17:28:221810 EXPECT_FALSE(ExtensionHasRenderProcessHost(kTestExtensionId));
David Bertoni4d9cf41d2019-06-04 00:06:221811
1812 ExtensionTestMessageListener moved_tab_listener("moved-tab", false);
1813 // Add a tab, then move it.
1814 content::WebContents* new_web_contents =
Istiaque Ahmed3f692562019-07-26 22:59:261815 browsertest_util::AddTab(browser(), GURL(url::kAboutBlankURL));
David Bertoni4d9cf41d2019-06-04 00:06:221816 EXPECT_TRUE(new_web_contents);
1817 browser()->tab_strip_model()->MoveWebContentsAt(
1818 browser()->tab_strip_model()->count() - 1, 0, false);
1819 EXPECT_TRUE(moved_tab_listener.WaitUntilSatisfied());
1820}
1821
Istiaque Ahmed1e59aec2019-06-05 22:40:241822IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, TabsOnCreated) {
1823 ASSERT_TRUE(RunExtensionTestWithFlags("tabs/lazy_background_on_created",
1824 kFlagRunAsServiceWorkerBasedExtension))
1825 << message_;
1826}
1827
David Bertoni023e0ec2019-06-10 17:28:221828IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
1829 PRE_FilteredEventsAfterRestart) {
1830 ExtensionTestMessageListener listener_added("ready", false);
1831 const Extension* extension = LoadExtensionWithFlags(
1832 test_data_dir_.AppendASCII("service_worker/worker_based_background/"
1833 "filtered_events_after_restart"),
1834 kFlagNone);
1835 ASSERT_TRUE(extension);
1836 EXPECT_EQ(kTestExtensionId, extension->id());
1837 ProcessManager* pm = ProcessManager::Get(browser()->profile());
1838 // TODO(crbug.com/969884): This will break once keep alive counts
1839 // for service workers are tracked by the Process Manager.
1840 EXPECT_LT(pm->GetLazyKeepaliveCount(extension), 1);
1841 EXPECT_TRUE(pm->GetLazyKeepaliveActivities(extension).empty());
1842 EXPECT_TRUE(listener_added.WaitUntilSatisfied());
1843}
1844
1845// After browser restarts, this test step ensures that opening a tab fires
1846// tabs.onCreated event listener to the extension without explicitly loading the
1847// extension. This is because the extension registered a listener for
1848// tabs.onMoved before browser restarted in PRE_EventsAfterRestart.
1849IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
1850 FilteredEventsAfterRestart) {
1851 // Verify there is no RenderProcessHost for the extension.
1852 // TODO(crbug.com/971309): This is currently broken because the test
1853 // infrastructure opens a tab, which dispatches an event to our
1854 // extension, even though the filter doesn't include that URL. The
1855 // referenced bug is about moving filtering into the EventRouter so they
1856 // get filtered before being dispatched.
1857 EXPECT_TRUE(ExtensionHasRenderProcessHost(kTestExtensionId));
1858
1859 // Create a tab to a.html, expect it to navigate to b.html. The service worker
1860 // will see two webNavigation.onCommitted events.
1861 GURL page_url = embedded_test_server()->GetURL(
1862 "/extensions/api_test/service_worker/worker_based_background/"
1863 "filtered_events_after_restart/"
1864 "a.html");
1865 ExtensionTestMessageListener worker_filtered_event_listener(
1866 "PASS_FROM_WORKER", false);
1867 worker_filtered_event_listener.set_failure_message("FAIL_FROM_WORKER");
Istiaque Ahmed3f692562019-07-26 22:59:261868 content::WebContents* web_contents =
1869 browsertest_util::AddTab(browser(), page_url);
David Bertoni023e0ec2019-06-10 17:28:221870 EXPECT_TRUE(web_contents);
1871 EXPECT_TRUE(worker_filtered_event_listener.WaitUntilSatisfied());
1872}
1873
Istiaque Ahmed91d6987c2019-06-25 00:09:331874// Tests that chrome.browserAction.onClicked sees user gesture.
1875IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest,
1876 BrowserActionUserGesture) {
1877 // First, load |extension| first so that it has browserAction.onClicked
1878 // listener registered.
1879 ExtensionTestMessageListener listener_added("ready", false);
1880 const Extension* extension = LoadExtension(
1881 test_data_dir_.AppendASCII("service_worker/worker_based_background/"
1882 "browser_action"));
1883 ASSERT_TRUE(extension);
1884 EXPECT_TRUE(listener_added.WaitUntilSatisfied());
1885
1886 ResultCatcher catcher;
1887 // Click on browser action to start the test.
1888 {
Istiaque Ahmed3f692562019-07-26 22:59:261889 content::WebContents* web_contents =
1890 browsertest_util::AddTab(browser(), GURL("about:blank"));
Istiaque Ahmed91d6987c2019-06-25 00:09:331891 ASSERT_TRUE(web_contents);
1892 ExtensionActionRunner::GetForWebContents(
1893 browser()->tab_strip_model()->GetActiveWebContents())
1894 ->RunAction(extension, true);
1895 }
1896 EXPECT_TRUE(catcher.GetNextResult()) << message_;
1897}
1898
Istiaque Ahmed242a4102019-06-25 01:47:571899// Tests that Service Worker notification handlers can call extension APIs that
1900// require user gesture to be present.
1901IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTestWithNotification,
1902 ServiceWorkerNotificationClick) {
1903 ResultCatcher catcher;
1904 const Extension* extension = LoadExtension(
1905 test_data_dir_.AppendASCII("service_worker/worker_based_background/"
1906 "notification_click"));
1907 ASSERT_TRUE(extension);
1908 EXPECT_TRUE(catcher.GetNextResult()) << message_;
1909
1910 // Click on the Service Worker notification.
1911 {
1912 std::vector<message_center::Notification> notifications =
1913 GetDisplayedNotifications();
1914 ASSERT_EQ(1u, notifications.size());
1915 display_service_tester_->SimulateClick(
1916 NotificationHandler::Type::WEB_PERSISTENT, notifications[0].id(),
1917 base::nullopt, base::nullopt);
1918 }
1919
1920 EXPECT_TRUE(catcher.GetNextResult()) << message_;
1921}
1922
Istiaque Ahmed3dd604232019-08-02 19:22:211923// Tests chrome.permissions.request API.
1924IN_PROC_BROWSER_TEST_F(ServiceWorkerBasedBackgroundTest, PermissionsAPI) {
1925 // First, load |extension| first so that it has browserAction.onClicked
1926 // listener registered.
1927 ExtensionTestMessageListener worker_listener("ready", false);
1928 const Extension* extension = LoadExtension(test_data_dir_.AppendASCII(
1929 "service_worker/worker_based_background/permissions_api"));
1930 ASSERT_TRUE(extension);
1931 const ExtensionId extension_id = extension->id();
1932 EXPECT_TRUE(worker_listener.WaitUntilSatisfied());
1933
1934 // "storage" permission is optional in |extension|, and isn't available right
1935 // away.
1936 EXPECT_FALSE(
1937 extension->permissions_data()->HasAPIPermission(APIPermission::kStorage));
1938
1939 PermissionsRequestFunction::SetAutoConfirmForTests(true);
1940
1941 ResultCatcher catcher;
1942 // Click on browser action to start the test.
1943 {
1944 content::WebContents* web_contents =
1945 browsertest_util::AddTab(browser(), GURL("about:blank"));
1946 ASSERT_TRUE(web_contents);
1947 ExtensionActionRunner::GetForWebContents(
1948 browser()->tab_strip_model()->GetActiveWebContents())
1949 ->RunAction(extension, true);
1950 }
1951 EXPECT_TRUE(catcher.GetNextResult()) << message_;
1952
1953 // Expect the permission ("storage") to be available now.
1954 EXPECT_TRUE(
1955 extension->permissions_data()->HasAPIPermission(APIPermission::kStorage));
1956}
1957
Devlin Cronin59551d82019-03-05 01:28:591958// Tests that console messages logged by extension service workers, both via
1959// the typical console.* methods and via our custom bindings console, are
1960// passed through the normal ServiceWorker console messaging and are
1961// observable.
Devlin Cronin242d19d22019-03-12 18:08:481962IN_PROC_BROWSER_TEST_F(ServiceWorkerLazyBackgroundTest, ConsoleLogging) {
Devlin Cronin59551d82019-03-05 01:28:591963 // A helper class to wait for a particular message to be logged from a
1964 // ServiceWorker.
1965 class ConsoleMessageObserver : public content::ServiceWorkerContextObserver {
1966 public:
1967 ConsoleMessageObserver(content::BrowserContext* browser_context,
1968 const std::string& expected_message)
1969 : expected_message_(base::UTF8ToUTF16(expected_message)),
1970 scoped_observer_(this) {
1971 content::StoragePartition* partition =
1972 content::BrowserContext::GetDefaultStoragePartition(browser_context);
1973 scoped_observer_.Add(partition->GetServiceWorkerContext());
1974 }
1975 ~ConsoleMessageObserver() override = default;
1976
1977 void Wait() { run_loop_.Run(); }
1978
1979 private:
1980 // ServiceWorkerContextObserver:
1981 void OnReportConsoleMessage(
1982 int64_t version_id,
1983 const content::ConsoleMessage& message) override {
1984 // NOTE: We could check the version_id, but it shouldn't be necessary with
1985 // the expected messages we're verifying (they're uncommon enough).
1986 if (message.message != expected_message_)
1987 return;
1988 scoped_observer_.RemoveAll();
1989 run_loop_.QuitWhenIdle();
1990 }
1991
1992 base::string16 expected_message_;
1993 base::RunLoop run_loop_;
1994 ScopedObserver<content::ServiceWorkerContext,
1995 content::ServiceWorkerContextObserver>
1996 scoped_observer_;
1997
1998 DISALLOW_COPY_AND_ASSIGN(ConsoleMessageObserver);
1999 };
2000
2001 TestExtensionDir test_dir;
2002 test_dir.WriteManifest(
2003 R"({
2004 "name": "Test Extension",
2005 "manifest_version": 2,
2006 "version": "0.1",
David Bertoni630837d2019-04-02 21:22:102007 "background": {"service_worker": "script.js"}
Devlin Cronin59551d82019-03-05 01:28:592008 })");
2009 constexpr char kScript[] =
2010 R"(// First, log a message using the normal, built-in blink console.
2011 console.log('test message');
2012 chrome.test.runTests([
2013 function justATest() {
2014 // Next, we use the "Console" object from
2015 // extensions/renderer/console.cc, which is used by custom bindings
2016 // so that it isn't tampered with by untrusted script. The test
2017 // custom bindings log a message whenever a test is passed, so we
2018 // force a log by just passing this test.
2019 chrome.test.succeed();
2020 }
2021 ]);)";
2022 test_dir.WriteFile(FILE_PATH_LITERAL("script.js"), kScript);
2023
2024 // The observer for the built-in blink console.
2025 ConsoleMessageObserver default_console_observer(profile(), "test message");
2026 // The observer for our custom extensions bindings console.
2027 ConsoleMessageObserver custom_console_observer(profile(),
2028 "[SUCCESS] justATest");
2029
2030 const Extension* extension = LoadExtension(test_dir.UnpackedPath());
2031 ASSERT_TRUE(extension);
2032
2033 default_console_observer.Wait();
2034 custom_console_observer.Wait();
2035 // If we receive both messages, we passed!
2036}
2037
David Bertoni98a5da72019-08-23 23:38:222038class ServiceWorkerCheckBindingsTest
2039 : public ServiceWorkerTest,
2040 public testing::WithParamInterface<version_info::Channel> {
2041 public:
2042 ServiceWorkerCheckBindingsTest() : ServiceWorkerTest(GetParam()) {}
2043 ~ServiceWorkerCheckBindingsTest() override {}
2044
2045 private:
2046 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerCheckBindingsTest);
2047};
2048
2049// Load an extension in each allowed channel and check that the expected
2050// bindings are available.
2051IN_PROC_BROWSER_TEST_P(ServiceWorkerCheckBindingsTest, BindingsAvailability) {
2052 scoped_refptr<const Extension> extension;
2053 static constexpr char kManifest[] =
2054 R"({
2055 "name": "Service Worker-based background script",
2056 "version": "0.1",
2057 "manifest_version": 2,
2058 "description": "Test that bindings are available.",
2059 "permissions": ["storage"],
2060 "background": {"service_worker": "worker.js"}
2061 })";
2062 static constexpr char kScript[] =
2063 R"(var chromeAPIAvailable = !!chrome;
2064 var storageAPIAvailable = chromeAPIAvailable && !!chrome.storage;
2065 var tabsAPIAvailable = chromeAPIAvailable && !!chrome.tabs;
2066 var testAPIAvailable = chromeAPIAvailable && !!chrome.test;
2067
2068 if (chromeAPIAvailable && storageAPIAvailable && tabsAPIAvailable &&
2069 testAPIAvailable) {
2070 chrome.test.sendMessage('SUCCESS');
2071 } else {
2072 console.log('chromeAPIAvailable: ' + chromeAPIAvailable);
2073 console.log('storageAPIAvailable: ' + storageAPIAvailable);
2074 console.log('tabsAPIAvailable: ' + tabsAPIAvailable);
2075 console.log('testAPIAvailable: ' + testAPIAvailable);
2076 chrome.test.sendMessage('FAILURE');
2077 })";
2078
2079 if (GetParam() <= version_info::Channel::CANARY) {
2080 TestExtensionDir test_dir;
2081 test_dir.WriteManifest(kManifest);
2082 test_dir.WriteFile(FILE_PATH_LITERAL("worker.js"), kScript);
2083 const base::FilePath path = test_dir.UnpackedPath();
2084
2085 // Wait for the extension to load and the script to finish.
2086 ExtensionTestMessageListener result_listener("SUCCESS", false);
2087 result_listener.set_failure_message("FAILURE");
2088
2089 extension = LoadExtension(test_dir.UnpackedPath());
2090 ASSERT_TRUE(extension.get());
2091 EXPECT_TRUE(BackgroundInfo::IsServiceWorkerBased(extension.get()));
2092 EXPECT_TRUE(result_listener.WaitUntilSatisfied());
2093 }
2094}
2095
2096INSTANTIATE_TEST_SUITE_P(Unknown,
2097 ServiceWorkerCheckBindingsTest,
2098 ::testing::Values(version_info::Channel::UNKNOWN,
2099 version_info::Channel::CANARY));
2100
annekao38685502015-07-14 17:46:392101} // namespace extensions