blob: 5cdb34840ec6dda4e3d0ea609194c85600180c90 [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
kalman6f984ae2015-09-18 17:21:587#include "base/bind_helpers.h"
avia2f4804a2015-12-24 23:11:138#include "base/macros.h"
Gabriel Charette078e3662017-08-28 22:59:049#include "base/run_loop.h"
kalman6f984ae2015-09-18 17:21:5810#include "base/strings/stringprintf.h"
horo1eeddde2015-11-19 05:59:2511#include "base/strings/utf_string_conversions.h"
jam3f2d3932017-04-26 20:28:5112#include "base/threading/thread_restrictions.h"
Olga Sharonova3e13cd92018-02-08 16:43:5613#include "build/build_config.h"
annekao38685502015-07-14 17:46:3914#include "chrome/browser/extensions/extension_apitest.h"
rdevlin.croninf5863da2015-09-10 19:21:4515#include "chrome/browser/extensions/extension_service.h"
Istiaque Ahmed805f6a83b2017-10-05 01:23:2616#include "chrome/browser/extensions/lazy_background_page_test_util.h"
peter9f4490a2017-01-27 00:58:3617#include "chrome/browser/gcm/gcm_profile_service_factory.h"
lazyboy561b7de2015-11-19 19:27:3018#include "chrome/browser/notifications/desktop_notification_profile_util.h"
miguelg9b502862017-04-24 18:13:5319#include "chrome/browser/notifications/notification_display_service_factory.h"
20#include "chrome/browser/notifications/stub_notification_display_service.h"
lshang106c1772016-06-06 01:43:2321#include "chrome/browser/permissions/permission_manager.h"
timlohc6911802017-03-01 05:37:0322#include "chrome/browser/permissions/permission_result.h"
lazyboy561b7de2015-11-19 19:27:3023#include "chrome/browser/push_messaging/push_messaging_app_identifier.h"
24#include "chrome/browser/push_messaging/push_messaging_service_factory.h"
25#include "chrome/browser/push_messaging/push_messaging_service_impl.h"
annekao1db36fd2015-07-29 17:09:1626#include "chrome/browser/ui/tabs/tab_strip_model.h"
Trent Apted4267b942017-10-27 03:25:3627#include "chrome/common/chrome_switches.h"
rdevlin.croninf5863da2015-09-10 19:21:4528#include "chrome/test/base/ui_test_utils.h"
timloh9a180ad2017-02-20 07:15:2329#include "components/content_settings/core/common/content_settings_types.h"
Peter Beverloo34139462018-04-10 14:18:0630#include "components/gcm_driver/fake_gcm_profile_service.h"
johnmea5045732016-09-08 17:23:2931#include "components/gcm_driver/instance_id/fake_gcm_driver_for_instance_id.h"
sdefresne9fb67692015-08-03 18:48:2232#include "components/version_info/version_info.h"
kalman6f984ae2015-09-18 17:21:5833#include "content/public/browser/navigation_controller.h"
rdevlin.croninf5863da2015-09-10 19:21:4534#include "content/public/browser/navigation_entry.h"
lazyboy4c82177a2016-10-18 00:04:0935#include "content/public/browser/service_worker_context.h"
36#include "content/public/browser/storage_partition.h"
kalman6f984ae2015-09-18 17:21:5837#include "content/public/browser/web_contents.h"
lazyboybd325ae2015-11-18 21:35:2638#include "content/public/common/content_switches.h"
falkenad185092016-06-16 06:10:0239#include "content/public/common/origin_util.h"
kalman6f984ae2015-09-18 17:21:5840#include "content/public/common/page_type.h"
lazyboybd325ae2015-11-18 21:35:2641#include "content/public/test/background_sync_test_util.h"
annekao1db36fd2015-07-29 17:09:1642#include "content/public/test/browser_test_utils.h"
lazyboy63b994a2017-06-30 21:20:2343#include "content/public/test/service_worker_test_helpers.h"
kalman6f984ae2015-09-18 17:21:5844#include "extensions/browser/extension_host.h"
lazyboyc3e763a2015-12-09 23:09:5845#include "extensions/browser/extension_registry.h"
kalman6f984ae2015-09-18 17:21:5846#include "extensions/browser/process_manager.h"
Devlin Cronina3fe3d602017-11-22 04:47:4347#include "extensions/common/extension_features.h"
kalman6f984ae2015-09-18 17:21:5848#include "extensions/test/background_page_watcher.h"
annekao38685502015-07-14 17:46:3949#include "extensions/test/extension_test_message_listener.h"
Istiaque Ahmed805f6a83b2017-10-05 01:23:2650#include "extensions/test/result_catcher.h"
falkenad185092016-06-16 06:10:0251#include "net/dns/mock_host_resolver.h"
horo1eeddde2015-11-19 05:59:2552#include "net/test/embedded_test_server/embedded_test_server.h"
lazyboy63b994a2017-06-30 21:20:2353#include "url/url_constants.h"
annekao38685502015-07-14 17:46:3954
55namespace extensions {
56
kalman6f984ae2015-09-18 17:21:5857namespace {
58
59// Pass into ServiceWorkerTest::StartTestFromBackgroundPage to indicate that
60// registration is expected to succeed.
61std::string* const kExpectSuccess = nullptr;
62
lazyboy22eddc712015-12-10 21:16:2663// Returns the newly added WebContents.
64content::WebContents* AddTab(Browser* browser, const GURL& url) {
65 int starting_tab_count = browser->tab_strip_model()->count();
66 ui_test_utils::NavigateToURLWithDisposition(
nick3b04f322016-08-31 19:29:1967 browser, url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
lazyboy22eddc712015-12-10 21:16:2668 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
69 int tab_count = browser->tab_strip_model()->count();
70 EXPECT_EQ(starting_tab_count + 1, tab_count);
71 return browser->tab_strip_model()->GetActiveWebContents();
72}
73
Istiaque Ahmedea5ed5042017-09-25 19:00:1674enum BindingsType { NATIVE_BINDINGS, JAVASCRIPT_BINDINGS };
75
lazyboy22eddc712015-12-10 21:16:2676class WebContentsLoadStopObserver : content::WebContentsObserver {
77 public:
78 explicit WebContentsLoadStopObserver(content::WebContents* web_contents)
79 : content::WebContentsObserver(web_contents),
80 load_stop_observed_(false) {}
81
82 void WaitForLoadStop() {
83 if (load_stop_observed_)
84 return;
85 message_loop_runner_ = new content::MessageLoopRunner;
86 message_loop_runner_->Run();
87 }
88
89 private:
90 void DidStopLoading() override {
91 load_stop_observed_ = true;
92 if (message_loop_runner_)
93 message_loop_runner_->Quit();
94 }
95
96 bool load_stop_observed_;
97 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
98
99 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadStopObserver);
100};
101
kalman6f984ae2015-09-18 17:21:58102} // namespace
103
Istiaque Ahmedea5ed5042017-09-25 19:00:16104class ServiceWorkerTest : public ExtensionApiTest,
105 public ::testing::WithParamInterface<BindingsType> {
annekao38685502015-07-14 17:46:39106 public:
lazyboy20167c22016-05-18 00:59:30107 ServiceWorkerTest() : current_channel_(version_info::Channel::STABLE) {}
Istiaque Ahmed7105f2a2017-10-07 01:11:59108 explicit ServiceWorkerTest(version_info::Channel channel)
109 : current_channel_(channel) {}
annekao38685502015-07-14 17:46:39110
111 ~ServiceWorkerTest() override {}
112
Devlin Cronina3fe3d602017-11-22 04:47:43113 void SetUp() override {
114 if (GetParam() == NATIVE_BINDINGS) {
115 scoped_feature_list_.InitAndEnableFeature(features::kNativeCrxBindings);
116 } else {
117 DCHECK_EQ(JAVASCRIPT_BINDINGS, GetParam());
118 scoped_feature_list_.InitAndDisableFeature(features::kNativeCrxBindings);
119 }
120 ExtensionApiTest::SetUp();
121 }
122
jam1a5b5582017-05-01 16:50:10123 void SetUpOnMainThread() override {
124 ExtensionApiTest::SetUpOnMainThread();
125 host_resolver()->AddRule("a.com", "127.0.0.1");
126 }
127
kalman6f984ae2015-09-18 17:21:58128 protected:
129 // Returns the ProcessManager for the test's profile.
130 ProcessManager* process_manager() { return ProcessManager::Get(profile()); }
131
132 // Starts running a test from the background page test extension.
133 //
134 // This registers a service worker with |script_name|, and fetches the
135 // registration result.
136 //
137 // If |error_or_null| is null (kExpectSuccess), success is expected and this
138 // will fail if there is an error.
139 // If |error_or_null| is not null, nothing is assumed, and the error (which
140 // may be empty) is written to it.
141 const Extension* StartTestFromBackgroundPage(const char* script_name,
142 std::string* error_or_null) {
143 const Extension* extension =
144 LoadExtension(test_data_dir_.AppendASCII("service_worker/background"));
145 CHECK(extension);
146 ExtensionHost* background_host =
147 process_manager()->GetBackgroundHostForExtension(extension->id());
148 CHECK(background_host);
149 std::string error;
150 CHECK(content::ExecuteScriptAndExtractString(
151 background_host->host_contents(),
152 base::StringPrintf("test.registerServiceWorker('%s')", script_name),
153 &error));
154 if (error_or_null)
155 *error_or_null = error;
156 else if (!error.empty())
157 ADD_FAILURE() << "Got unexpected error " << error;
158 return extension;
159 }
160
161 // Navigates the browser to a new tab at |url|, waits for it to load, then
162 // returns it.
163 content::WebContents* Navigate(const GURL& url) {
164 ui_test_utils::NavigateToURLWithDisposition(
nick3b04f322016-08-31 19:29:19165 browser(), url, WindowOpenDisposition::NEW_FOREGROUND_TAB,
kalman6f984ae2015-09-18 17:21:58166 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
167 content::WebContents* web_contents =
168 browser()->tab_strip_model()->GetActiveWebContents();
169 content::WaitForLoadStop(web_contents);
170 return web_contents;
171 }
172
173 // Navigates the browser to |url| and returns the new tab's page type.
174 content::PageType NavigateAndGetPageType(const GURL& url) {
175 return Navigate(url)->GetController().GetActiveEntry()->GetPageType();
176 }
177
178 // Extracts the innerText from |contents|.
179 std::string ExtractInnerText(content::WebContents* contents) {
180 std::string inner_text;
181 if (!content::ExecuteScriptAndExtractString(
182 contents,
183 "window.domAutomationController.send(document.body.innerText)",
184 &inner_text)) {
185 ADD_FAILURE() << "Failed to get inner text for "
186 << contents->GetVisibleURL();
187 }
188 return inner_text;
189 }
190
191 // Navigates the browser to |url|, then returns the innerText of the new
192 // tab's WebContents' main frame.
193 std::string NavigateAndExtractInnerText(const GURL& url) {
194 return ExtractInnerText(Navigate(url));
195 }
196
lazyboy4c82177a2016-10-18 00:04:09197 size_t GetWorkerRefCount(const GURL& origin) {
198 content::ServiceWorkerContext* sw_context =
199 content::BrowserContext::GetDefaultStoragePartition(
200 browser()->profile())
201 ->GetServiceWorkerContext();
202 base::RunLoop run_loop;
203 size_t ref_count = 0;
204 auto set_ref_count = [](size_t* ref_count, base::RunLoop* run_loop,
205 size_t external_request_count) {
206 *ref_count = external_request_count;
207 run_loop->Quit();
208 };
209 sw_context->CountExternalRequestsForTest(
Matt Falkenhagenc5cb4282017-09-07 08:43:42210 origin, base::BindOnce(set_ref_count, &ref_count, &run_loop));
lazyboy4c82177a2016-10-18 00:04:09211 run_loop.Run();
212 return ref_count;
213 }
214
annekao38685502015-07-14 17:46:39215 private:
lazyboy20167c22016-05-18 00:59:30216 // Sets the channel to "stable".
217 // Not useful after we've opened extension Service Workers to stable
218 // channel.
219 // TODO(lazyboy): Remove this when ExtensionServiceWorkersEnabled() is
220 // removed.
annekao38685502015-07-14 17:46:39221 ScopedCurrentChannel current_channel_;
kalman6f984ae2015-09-18 17:21:58222
Devlin Cronina3fe3d602017-11-22 04:47:43223 base::test::ScopedFeatureList scoped_feature_list_;
224
annekao38685502015-07-14 17:46:39225 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerTest);
226};
227
lazyboybd325ae2015-11-18 21:35:26228class ServiceWorkerBackgroundSyncTest : public ServiceWorkerTest {
229 public:
230 ServiceWorkerBackgroundSyncTest() {}
231 ~ServiceWorkerBackgroundSyncTest() override {}
232
233 void SetUpCommandLine(base::CommandLine* command_line) override {
234 // ServiceWorkerRegistration.sync requires experimental flag.
235 command_line->AppendSwitch(
Istiaque Ahmedea5ed5042017-09-25 19:00:16236 ::switches::kEnableExperimentalWebPlatformFeatures);
lazyboybd325ae2015-11-18 21:35:26237 ServiceWorkerTest::SetUpCommandLine(command_line);
238 }
239
240 void SetUp() override {
241 content::background_sync_test_util::SetIgnoreNetworkChangeNotifier(true);
242 ServiceWorkerTest::SetUp();
243 }
244
245 private:
246 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerBackgroundSyncTest);
247};
248
lazyboy561b7de2015-11-19 19:27:30249class ServiceWorkerPushMessagingTest : public ServiceWorkerTest {
250 public:
251 ServiceWorkerPushMessagingTest()
johnmea5045732016-09-08 17:23:29252 : gcm_driver_(nullptr), push_service_(nullptr) {}
lazyboy561b7de2015-11-19 19:27:30253 ~ServiceWorkerPushMessagingTest() override {}
254
255 void GrantNotificationPermissionForTest(const GURL& url) {
256 GURL origin = url.GetOrigin();
257 DesktopNotificationProfileUtil::GrantPermission(profile(), origin);
timlohc6911802017-03-01 05:37:03258 ASSERT_EQ(CONTENT_SETTING_ALLOW,
259 PermissionManager::Get(profile())
260 ->GetPermissionStatus(CONTENT_SETTINGS_TYPE_NOTIFICATIONS,
261 origin, origin)
262 .content_setting);
lazyboy561b7de2015-11-19 19:27:30263 }
264
265 PushMessagingAppIdentifier GetAppIdentifierForServiceWorkerRegistration(
avia2f4804a2015-12-24 23:11:13266 int64_t service_worker_registration_id,
lazyboy561b7de2015-11-19 19:27:30267 const GURL& origin) {
268 PushMessagingAppIdentifier app_identifier =
269 PushMessagingAppIdentifier::FindByServiceWorker(
270 profile(), origin, service_worker_registration_id);
271
272 EXPECT_FALSE(app_identifier.is_null());
273 return app_identifier;
274 }
275
276 // ExtensionApiTest overrides.
277 void SetUpCommandLine(base::CommandLine* command_line) override {
peter9de96272015-12-04 15:23:27278 command_line->AppendSwitch(
Istiaque Ahmedea5ed5042017-09-25 19:00:16279 ::switches::kEnableExperimentalWebPlatformFeatures);
lazyboy561b7de2015-11-19 19:27:30280 ServiceWorkerTest::SetUpCommandLine(command_line);
281 }
282 void SetUpOnMainThread() override {
miguelg9b502862017-04-24 18:13:53283 NotificationDisplayServiceFactory::GetInstance()->SetTestingFactory(
284 profile(), &StubNotificationDisplayService::FactoryForTests);
285
johnmea5045732016-09-08 17:23:29286 gcm::FakeGCMProfileService* gcm_service =
287 static_cast<gcm::FakeGCMProfileService*>(
288 gcm::GCMProfileServiceFactory::GetInstance()
289 ->SetTestingFactoryAndUse(profile(),
290 &gcm::FakeGCMProfileService::Build));
291 gcm_driver_ = static_cast<instance_id::FakeGCMDriverForInstanceID*>(
292 gcm_service->driver());
lazyboy561b7de2015-11-19 19:27:30293 push_service_ = PushMessagingServiceFactory::GetForProfile(profile());
294
295 ServiceWorkerTest::SetUpOnMainThread();
296 }
297
johnmea5045732016-09-08 17:23:29298 instance_id::FakeGCMDriverForInstanceID* gcm_driver() const {
299 return gcm_driver_;
300 }
lazyboy561b7de2015-11-19 19:27:30301 PushMessagingServiceImpl* push_service() const { return push_service_; }
302
303 private:
johnmea5045732016-09-08 17:23:29304 instance_id::FakeGCMDriverForInstanceID* gcm_driver_;
lazyboy561b7de2015-11-19 19:27:30305 PushMessagingServiceImpl* push_service_;
306
307 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerPushMessagingTest);
308};
309
Istiaque Ahmed805f6a83b2017-10-05 01:23:26310class ServiceWorkerLazyBackgroundTest : public ServiceWorkerTest {
311 public:
Istiaque Ahmed7105f2a2017-10-07 01:11:59312 ServiceWorkerLazyBackgroundTest()
313 : ServiceWorkerTest(
314 // Extensions APIs from SW are only enabled on trunk.
315 // It is important to set the channel early so that this change is
316 // visible in renderers running with service workers (and no
317 // extension).
318 version_info::Channel::UNKNOWN) {}
Istiaque Ahmed805f6a83b2017-10-05 01:23:26319 ~ServiceWorkerLazyBackgroundTest() override {}
320
321 void SetUpCommandLine(base::CommandLine* command_line) override {
322 ServiceWorkerTest::SetUpCommandLine(command_line);
323 // Disable background network activity as it can suddenly bring the Lazy
324 // Background Page alive.
325 command_line->AppendSwitch(::switches::kDisableBackgroundNetworking);
326 command_line->AppendSwitch(::switches::kNoProxyServer);
327 }
328
329 void SetUpInProcessBrowserTestFixture() override {
330 ServiceWorkerTest::SetUpInProcessBrowserTestFixture();
331 // Set shorter delays to prevent test timeouts.
332 ProcessManager::SetEventPageIdleTimeForTesting(1);
333 ProcessManager::SetEventPageSuspendingTimeForTesting(1);
334 }
335
336 private:
337 DISALLOW_COPY_AND_ASSIGN(ServiceWorkerLazyBackgroundTest);
338};
339
Istiaque Ahmedea5ed5042017-09-25 19:00:16340IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, RegisterSucceeds) {
kalman6f984ae2015-09-18 17:21:58341 StartTestFromBackgroundPage("register.js", kExpectSuccess);
annekao38685502015-07-14 17:46:39342}
343
Istiaque Ahmedea5ed5042017-09-25 19:00:16344IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, UpdateRefreshesServiceWorker) {
Francois Doraye6fb2d02017-10-18 21:29:13345 base::ScopedAllowBlockingForTesting allow_blocking;
lazyboyc3e763a2015-12-09 23:09:58346 base::ScopedTempDir scoped_temp_dir;
347 ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
348 base::FilePath pem_path = test_data_dir_.AppendASCII("service_worker")
349 .AppendASCII("update")
350 .AppendASCII("service_worker.pem");
vabr9142fe22016-09-08 13:19:22351 base::FilePath path_v1 =
352 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
353 .AppendASCII("update")
354 .AppendASCII("v1"),
355 scoped_temp_dir.GetPath().AppendASCII("v1.crx"),
356 pem_path, base::FilePath());
357 base::FilePath path_v2 =
358 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
359 .AppendASCII("update")
360 .AppendASCII("v2"),
361 scoped_temp_dir.GetPath().AppendASCII("v2.crx"),
362 pem_path, base::FilePath());
lazyboyc3e763a2015-12-09 23:09:58363 const char* kId = "hfaanndiiilofhfokeanhddpkfffchdi";
364
365 ExtensionTestMessageListener listener_v1("Pong from version 1", false);
366 listener_v1.set_failure_message("FAILURE_V1");
367 // Install version 1.0 of the extension.
368 ASSERT_TRUE(InstallExtension(path_v1, 1));
369 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
370 ->enabled_extensions()
371 .GetByID(kId));
372 EXPECT_TRUE(listener_v1.WaitUntilSatisfied());
373
374 ExtensionTestMessageListener listener_v2("Pong from version 2", false);
375 listener_v2.set_failure_message("FAILURE_V2");
376
377 // Update to version 2.0.
378 EXPECT_TRUE(UpdateExtension(kId, path_v2, 0));
379 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
380 ->enabled_extensions()
381 .GetByID(kId));
382 EXPECT_TRUE(listener_v2.WaitUntilSatisfied());
383}
384
[email protected]2ef85d562017-09-15 18:41:52385// TODO(crbug.com/765736) Fix the test.
Istiaque Ahmedea5ed5042017-09-25 19:00:16386IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, DISABLED_UpdateWithoutSkipWaiting) {
Francois Doraye6fb2d02017-10-18 21:29:13387 base::ScopedAllowBlockingForTesting allow_blocking;
lazyboy22eddc712015-12-10 21:16:26388 base::ScopedTempDir scoped_temp_dir;
389 ASSERT_TRUE(scoped_temp_dir.CreateUniqueTempDir());
390 base::FilePath pem_path = test_data_dir_.AppendASCII("service_worker")
391 .AppendASCII("update_without_skip_waiting")
392 .AppendASCII("update_without_skip_waiting.pem");
vabr9142fe22016-09-08 13:19:22393 base::FilePath path_v1 =
394 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
395 .AppendASCII("update_without_skip_waiting")
396 .AppendASCII("v1"),
397 scoped_temp_dir.GetPath().AppendASCII("v1.crx"),
398 pem_path, base::FilePath());
399 base::FilePath path_v2 =
400 PackExtensionWithOptions(test_data_dir_.AppendASCII("service_worker")
401 .AppendASCII("update_without_skip_waiting")
402 .AppendASCII("v2"),
403 scoped_temp_dir.GetPath().AppendASCII("v2.crx"),
404 pem_path, base::FilePath());
lazyboy22eddc712015-12-10 21:16:26405 const char* kId = "mhnnnflgagdakldgjpfcofkiocpdmogl";
406
407 // Install version 1.0 of the extension.
408 ASSERT_TRUE(InstallExtension(path_v1, 1));
409 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
410 ->enabled_extensions()
411 .GetByID(kId));
412 const Extension* extension = extensions::ExtensionRegistry::Get(profile())
413 ->enabled_extensions()
414 .GetByID(kId);
415
416 ExtensionTestMessageListener listener1("Pong from version 1", false);
417 listener1.set_failure_message("FAILURE");
418 content::WebContents* web_contents =
419 AddTab(browser(), extension->GetResourceURL("page.html"));
420 EXPECT_TRUE(listener1.WaitUntilSatisfied());
421
422 // Update to version 2.0.
423 EXPECT_TRUE(UpdateExtension(kId, path_v2, 0));
424 EXPECT_TRUE(extensions::ExtensionRegistry::Get(profile())
425 ->enabled_extensions()
426 .GetByID(kId));
427 const Extension* extension_after_update =
428 extensions::ExtensionRegistry::Get(profile())
429 ->enabled_extensions()
430 .GetByID(kId);
431
432 // Service worker version 2 would be installed but it won't be controlling
433 // the extension page yet.
434 ExtensionTestMessageListener listener2("Pong from version 1", false);
435 listener2.set_failure_message("FAILURE");
436 web_contents =
437 AddTab(browser(), extension_after_update->GetResourceURL("page.html"));
438 EXPECT_TRUE(listener2.WaitUntilSatisfied());
439
440 // Navigate the tab away from the extension page so that no clients are
441 // using the service worker.
442 // Note that just closing the tab with WebContentsDestroyedWatcher doesn't
443 // seem to be enough because it returns too early.
444 WebContentsLoadStopObserver navigate_away_observer(web_contents);
445 web_contents->GetController().LoadURL(
446 GURL(url::kAboutBlankURL), content::Referrer(), ui::PAGE_TRANSITION_TYPED,
447 std::string());
448 navigate_away_observer.WaitForLoadStop();
449
450 // Now expect service worker version 2 to control the extension page.
451 ExtensionTestMessageListener listener3("Pong from version 2", false);
452 listener3.set_failure_message("FAILURE");
453 web_contents =
454 AddTab(browser(), extension_after_update->GetResourceURL("page.html"));
455 EXPECT_TRUE(listener3.WaitUntilSatisfied());
456}
457
Istiaque Ahmedea5ed5042017-09-25 19:00:16458IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, FetchArbitraryPaths) {
kalman6f984ae2015-09-18 17:21:58459 const Extension* extension =
460 StartTestFromBackgroundPage("fetch.js", kExpectSuccess);
annekao1db36fd2015-07-29 17:09:16461
kalman6f984ae2015-09-18 17:21:58462 // Open some arbirary paths. Their contents should be what the service worker
463 // responds with, which in this case is the path of the fetch.
464 EXPECT_EQ(
465 "Caught a fetch for /index.html",
466 NavigateAndExtractInnerText(extension->GetResourceURL("index.html")));
467 EXPECT_EQ("Caught a fetch for /path/to/other.html",
468 NavigateAndExtractInnerText(
469 extension->GetResourceURL("path/to/other.html")));
470 EXPECT_EQ("Caught a fetch for /some/text/file.txt",
471 NavigateAndExtractInnerText(
472 extension->GetResourceURL("some/text/file.txt")));
473 EXPECT_EQ("Caught a fetch for /no/file/extension",
474 NavigateAndExtractInnerText(
475 extension->GetResourceURL("no/file/extension")));
476 EXPECT_EQ("Caught a fetch for /",
477 NavigateAndExtractInnerText(extension->GetResourceURL("")));
annekao1db36fd2015-07-29 17:09:16478}
479
Istiaque Ahmedea5ed5042017-09-25 19:00:16480IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, SWServedBackgroundPageReceivesEvent) {
lazyboy52c3bcf2016-01-08 00:11:29481 const Extension* extension =
482 StartTestFromBackgroundPage("replace_background.js", kExpectSuccess);
483 ExtensionHost* background_page =
484 process_manager()->GetBackgroundHostForExtension(extension->id());
485 ASSERT_TRUE(background_page);
486
487 // Close the background page and start it again so that the service worker
488 // will start controlling pages.
489 background_page->Close();
490 BackgroundPageWatcher(process_manager(), extension).WaitForClose();
491 background_page = nullptr;
Peter Kasting341e1fb2018-02-24 00:03:01492 process_manager()->WakeEventPage(extension->id(), base::DoNothing());
lazyboy52c3bcf2016-01-08 00:11:29493 BackgroundPageWatcher(process_manager(), extension).WaitForOpen();
494
495 // Since the SW is now controlling the extension, the SW serves the background
496 // script. page.html sends a message to the background script and we verify
497 // that the SW served background script correctly receives the message/event.
498 ExtensionTestMessageListener listener("onMessage/SW BG.", false);
499 listener.set_failure_message("onMessage/original BG.");
500 content::WebContents* web_contents =
501 AddTab(browser(), extension->GetResourceURL("page.html"));
502 ASSERT_TRUE(web_contents);
503 EXPECT_TRUE(listener.WaitUntilSatisfied());
504}
505
Istiaque Ahmedea5ed5042017-09-25 19:00:16506IN_PROC_BROWSER_TEST_P(ServiceWorkerTest,
kalman6f984ae2015-09-18 17:21:58507 LoadingBackgroundPageBypassesServiceWorker) {
508 const Extension* extension =
509 StartTestFromBackgroundPage("fetch.js", kExpectSuccess);
annekao49241182015-08-18 17:14:01510
kalman6f984ae2015-09-18 17:21:58511 std::string kExpectedInnerText = "background.html contents for testing.";
annekao49241182015-08-18 17:14:01512
kalman6f984ae2015-09-18 17:21:58513 // Sanity check that the background page has the expected content.
514 ExtensionHost* background_page =
515 process_manager()->GetBackgroundHostForExtension(extension->id());
516 ASSERT_TRUE(background_page);
517 EXPECT_EQ(kExpectedInnerText,
518 ExtractInnerText(background_page->host_contents()));
annekao49241182015-08-18 17:14:01519
kalman6f984ae2015-09-18 17:21:58520 // Close the background page.
521 background_page->Close();
522 BackgroundPageWatcher(process_manager(), extension).WaitForClose();
523 background_page = nullptr;
524
525 // Start it again.
Peter Kasting341e1fb2018-02-24 00:03:01526 process_manager()->WakeEventPage(extension->id(), base::DoNothing());
kalman6f984ae2015-09-18 17:21:58527 BackgroundPageWatcher(process_manager(), extension).WaitForOpen();
528
529 // Content should not have been affected by the fetch, which would otherwise
530 // be "Caught fetch for...".
531 background_page =
532 process_manager()->GetBackgroundHostForExtension(extension->id());
533 ASSERT_TRUE(background_page);
534 content::WaitForLoadStop(background_page->host_contents());
535
536 // TODO(kalman): Everything you've read has been a LIE! It should be:
537 //
538 // EXPECT_EQ(kExpectedInnerText,
539 // ExtractInnerText(background_page->host_contents()));
540 //
541 // but there is a bug, and we're actually *not* bypassing the service worker
542 // for background page loads! For now, let it pass (assert wrong behavior)
543 // because it's not a regression, but this must be fixed eventually.
544 //
545 // Tracked in crbug.com/532720.
546 EXPECT_EQ("Caught a fetch for /background.html",
547 ExtractInnerText(background_page->host_contents()));
annekao49241182015-08-18 17:14:01548}
549
Istiaque Ahmedea5ed5042017-09-25 19:00:16550IN_PROC_BROWSER_TEST_P(ServiceWorkerTest,
kalman6f984ae2015-09-18 17:21:58551 ServiceWorkerPostsMessageToBackgroundClient) {
552 const Extension* extension = StartTestFromBackgroundPage(
553 "post_message_to_background_client.js", kExpectSuccess);
annekao533482222015-08-21 23:23:53554
kalman6f984ae2015-09-18 17:21:58555 // The service worker in this test simply posts a message to the background
556 // client it receives from getBackgroundClient().
557 const char* kScript =
558 "var messagePromise = null;\n"
559 "if (test.lastMessageFromServiceWorker) {\n"
560 " messagePromise = Promise.resolve(test.lastMessageFromServiceWorker);\n"
561 "} else {\n"
562 " messagePromise = test.waitForMessage(navigator.serviceWorker);\n"
563 "}\n"
564 "messagePromise.then(function(message) {\n"
565 " window.domAutomationController.send(String(message == 'success'));\n"
566 "})\n";
567 EXPECT_EQ("true", ExecuteScriptInBackgroundPage(extension->id(), kScript));
annekao533482222015-08-21 23:23:53568}
569
Istiaque Ahmedea5ed5042017-09-25 19:00:16570IN_PROC_BROWSER_TEST_P(ServiceWorkerTest,
kalman6f984ae2015-09-18 17:21:58571 BackgroundPagePostsMessageToServiceWorker) {
572 const Extension* extension =
573 StartTestFromBackgroundPage("post_message_to_sw.js", kExpectSuccess);
annekao533482222015-08-21 23:23:53574
kalman6f984ae2015-09-18 17:21:58575 // The service worker in this test waits for a message, then echoes it back
576 // by posting a message to the background page via getBackgroundClient().
577 const char* kScript =
578 "var mc = new MessageChannel();\n"
579 "test.waitForMessage(mc.port1).then(function(message) {\n"
580 " window.domAutomationController.send(String(message == 'hello'));\n"
581 "});\n"
582 "test.registeredServiceWorker.postMessage(\n"
583 " {message: 'hello', port: mc.port2}, [mc.port2])\n";
584 EXPECT_EQ("true", ExecuteScriptInBackgroundPage(extension->id(), kScript));
annekao533482222015-08-21 23:23:53585}
586
Istiaque Ahmedea5ed5042017-09-25 19:00:16587IN_PROC_BROWSER_TEST_P(ServiceWorkerTest,
rdevlin.croninf5863da2015-09-10 19:21:45588 ServiceWorkerSuspensionOnExtensionUnload) {
kalman6f984ae2015-09-18 17:21:58589 // For this test, only hold onto the extension's ID and URL + a function to
590 // get a resource URL, because we're going to be disabling and uninstalling
591 // it, which will invalidate the pointer.
592 std::string extension_id;
593 GURL extension_url;
594 {
595 const Extension* extension =
596 StartTestFromBackgroundPage("fetch.js", kExpectSuccess);
597 extension_id = extension->id();
598 extension_url = extension->url();
599 }
600 auto get_resource_url = [&extension_url](const std::string& path) {
601 return Extension::GetResourceURL(extension_url, path);
602 };
rdevlin.croninf5863da2015-09-10 19:21:45603
kalman6f984ae2015-09-18 17:21:58604 // Fetch should route to the service worker.
605 EXPECT_EQ("Caught a fetch for /index.html",
606 NavigateAndExtractInnerText(get_resource_url("index.html")));
rdevlin.croninf5863da2015-09-10 19:21:45607
kalman6f984ae2015-09-18 17:21:58608 // Disable the extension. Opening the page should fail.
609 extension_service()->DisableExtension(extension_id,
Minh X. Nguyen45479012017-08-18 21:35:36610 disable_reason::DISABLE_USER_ACTION);
rdevlin.croninf5863da2015-09-10 19:21:45611 base::RunLoop().RunUntilIdle();
rdevlin.croninf5863da2015-09-10 19:21:45612
kalman6f984ae2015-09-18 17:21:58613 EXPECT_EQ(content::PAGE_TYPE_ERROR,
614 NavigateAndGetPageType(get_resource_url("index.html")));
615 EXPECT_EQ(content::PAGE_TYPE_ERROR,
616 NavigateAndGetPageType(get_resource_url("other.html")));
617
618 // Re-enable the extension. Opening pages should immediately start to succeed
619 // again.
rdevlin.croninf5863da2015-09-10 19:21:45620 extension_service()->EnableExtension(extension_id);
621 base::RunLoop().RunUntilIdle();
622
kalman6f984ae2015-09-18 17:21:58623 EXPECT_EQ("Caught a fetch for /index.html",
624 NavigateAndExtractInnerText(get_resource_url("index.html")));
625 EXPECT_EQ("Caught a fetch for /other.html",
626 NavigateAndExtractInnerText(get_resource_url("other.html")));
627 EXPECT_EQ("Caught a fetch for /another.html",
628 NavigateAndExtractInnerText(get_resource_url("another.html")));
rdevlin.croninf5863da2015-09-10 19:21:45629
kalman6f984ae2015-09-18 17:21:58630 // Uninstall the extension. Opening pages should fail again.
631 base::string16 error;
632 extension_service()->UninstallExtension(
Devlin Cronin218df7f2017-11-21 21:41:31633 extension_id, UninstallReason::UNINSTALL_REASON_FOR_TESTING, &error);
kalman6f984ae2015-09-18 17:21:58634 base::RunLoop().RunUntilIdle();
635
636 EXPECT_EQ(content::PAGE_TYPE_ERROR,
637 NavigateAndGetPageType(get_resource_url("index.html")));
638 EXPECT_EQ(content::PAGE_TYPE_ERROR,
639 NavigateAndGetPageType(get_resource_url("other.html")));
640 EXPECT_EQ(content::PAGE_TYPE_ERROR,
641 NavigateAndGetPageType(get_resource_url("anotherother.html")));
642 EXPECT_EQ(content::PAGE_TYPE_ERROR,
643 NavigateAndGetPageType(get_resource_url("final.html")));
644}
645
Istiaque Ahmedea5ed5042017-09-25 19:00:16646IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, BackgroundPageIsWokenIfAsleep) {
kalman6f984ae2015-09-18 17:21:58647 const Extension* extension =
648 StartTestFromBackgroundPage("wake_on_fetch.js", kExpectSuccess);
649
650 // Navigate to special URLs that this test's service worker recognises, each
651 // making a check then populating the response with either "true" or "false".
652 EXPECT_EQ("true", NavigateAndExtractInnerText(extension->GetResourceURL(
653 "background-client-is-awake")));
654 EXPECT_EQ("true", NavigateAndExtractInnerText(
655 extension->GetResourceURL("ping-background-client")));
656 // Ping more than once for good measure.
657 EXPECT_EQ("true", NavigateAndExtractInnerText(
658 extension->GetResourceURL("ping-background-client")));
659
660 // Shut down the event page. The SW should detect that it's closed, but still
661 // be able to ping it.
662 ExtensionHost* background_page =
663 process_manager()->GetBackgroundHostForExtension(extension->id());
664 ASSERT_TRUE(background_page);
665 background_page->Close();
666 BackgroundPageWatcher(process_manager(), extension).WaitForClose();
667
668 EXPECT_EQ("false", NavigateAndExtractInnerText(extension->GetResourceURL(
669 "background-client-is-awake")));
670 EXPECT_EQ("true", NavigateAndExtractInnerText(
671 extension->GetResourceURL("ping-background-client")));
672 EXPECT_EQ("true", NavigateAndExtractInnerText(
673 extension->GetResourceURL("ping-background-client")));
674 EXPECT_EQ("true", NavigateAndExtractInnerText(extension->GetResourceURL(
675 "background-client-is-awake")));
676}
677
Istiaque Ahmedea5ed5042017-09-25 19:00:16678IN_PROC_BROWSER_TEST_P(ServiceWorkerTest,
kalman6f984ae2015-09-18 17:21:58679 GetBackgroundClientFailsWithNoBackgroundPage) {
680 // This extension doesn't have a background page, only a tab at page.html.
681 // The service worker it registers tries to call getBackgroundClient() and
682 // should fail.
683 // Note that this also tests that service workers can be registered from tabs.
684 EXPECT_TRUE(RunExtensionSubtest("service_worker/no_background", "page.html"));
rdevlin.croninf5863da2015-09-10 19:21:45685}
686
Istiaque Ahmedea5ed5042017-09-25 19:00:16687IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, NotificationAPI) {
lazyboy6ddb7d62015-11-10 23:15:27688 EXPECT_TRUE(RunExtensionSubtest("service_worker/notifications/has_permission",
689 "page.html"));
690}
691
Istiaque Ahmedea5ed5042017-09-25 19:00:16692IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, WebAccessibleResourcesFetch) {
lazyboyaea32c22016-01-04 21:37:07693 EXPECT_TRUE(RunExtensionSubtest(
694 "service_worker/web_accessible_resources/fetch/", "page.html"));
695}
696
Olga Sharonova3e13cd92018-02-08 16:43:56697// Flaky on Linux: http://crbug/810397.
698#if defined(OS_LINUX)
699#define MAYBE_TabsCreate DISABLED_TabsCreate
700#else
701#define MAYBE_TabsCreate TabsCreate
702#endif
703IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, MAYBE_TabsCreate) {
lazyboyee4adef2016-05-24 00:55:16704 // Extensions APIs from SW are only enabled on trunk.
705 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
706 const Extension* extension = LoadExtensionWithFlags(
707 test_data_dir_.AppendASCII("service_worker/tabs_create"), kFlagNone);
708 ASSERT_TRUE(extension);
709 ui_test_utils::NavigateToURL(browser(),
710 extension->GetResourceURL("page.html"));
711 content::WebContents* web_contents =
712 browser()->tab_strip_model()->GetActiveWebContents();
713
714 int starting_tab_count = browser()->tab_strip_model()->count();
715 std::string result;
716 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
717 web_contents, "window.runServiceWorker()", &result));
718 ASSERT_EQ("chrome.tabs.create callback", result);
719 EXPECT_EQ(starting_tab_count + 1, browser()->tab_strip_model()->count());
720
721 // Check extension shutdown path.
722 UnloadExtension(extension->id());
723 EXPECT_EQ(starting_tab_count, browser()->tab_strip_model()->count());
724}
725
Istiaque Ahmedea5ed5042017-09-25 19:00:16726IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, Events) {
lazyboye7847242017-06-07 23:29:18727 // Extensions APIs from SW are only enabled on trunk.
728 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
729 const Extension* extension = LoadExtensionWithFlags(
730 test_data_dir_.AppendASCII("service_worker/events"), kFlagNone);
731 ASSERT_TRUE(extension);
732 ui_test_utils::NavigateToURL(browser(),
733 extension->GetResourceURL("page.html"));
734 content::WebContents* web_contents =
735 browser()->tab_strip_model()->GetActiveWebContents();
736 std::string result;
737 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
738 web_contents, "window.runEventTest()", &result));
739 ASSERT_EQ("chrome.tabs.onUpdated callback", result);
740}
741
Istiaque Ahmedea5ed5042017-09-25 19:00:16742IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, EventsToStoppedWorker) {
lazyboy63b994a2017-06-30 21:20:23743 // Extensions APIs from SW are only enabled on trunk.
744 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
745 const Extension* extension = LoadExtensionWithFlags(
746 test_data_dir_.AppendASCII("service_worker/events_to_stopped_worker"),
747 kFlagNone);
748 ASSERT_TRUE(extension);
749 ui_test_utils::NavigateToURL(browser(),
750 extension->GetResourceURL("page.html"));
751 content::WebContents* web_contents =
752 browser()->tab_strip_model()->GetActiveWebContents();
753 {
754 std::string result;
755 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
756 web_contents, "window.runServiceWorker()", &result));
757 ASSERT_EQ("ready", result);
758
759 base::RunLoop run_loop;
760 content::StoragePartition* storage_partition =
761 content::BrowserContext::GetDefaultStoragePartition(
762 browser()->profile());
763 content::StopServiceWorkerForPattern(
764 storage_partition->GetServiceWorkerContext(),
765 // The service worker is registered at the top level scope.
766 extension->url(), run_loop.QuitClosure());
767 run_loop.Run();
768 }
769
770 std::string result;
771 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
772 web_contents, "window.createTabThenUpdate()", &result));
773 ASSERT_EQ("chrome.tabs.onUpdated callback", result);
774}
775
Istiaque Ahmed805f6a83b2017-10-05 01:23:26776// Tests that events to service worker arrives correctly event if the owner
777// extension of the worker is not running.
778IN_PROC_BROWSER_TEST_P(ServiceWorkerLazyBackgroundTest,
779 EventsToStoppedExtension) {
Istiaque Ahmed805f6a83b2017-10-05 01:23:26780 LazyBackgroundObserver lazy_observer;
781 ResultCatcher catcher;
782 const Extension* extension = LoadExtensionWithFlags(
783 test_data_dir_.AppendASCII("service_worker/events_to_stopped_extension"),
784 kFlagNone);
785 ASSERT_TRUE(extension);
786 EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
787
788 ProcessManager* pm = ProcessManager::Get(browser()->profile());
789 EXPECT_GT(pm->GetLazyKeepaliveCount(extension), 0);
790
791 // |extension|'s background page opens a tab to its resource.
792 content::WebContents* extension_web_contents =
793 browser()->tab_strip_model()->GetActiveWebContents();
794 EXPECT_TRUE(content::WaitForLoadStop(extension_web_contents));
795 EXPECT_EQ(extension->GetResourceURL("page.html").spec(),
796 extension_web_contents->GetURL().spec());
797 {
798 // Let the service worker start and register a listener to
799 // chrome.tabs.onCreated event.
800 ExtensionTestMessageListener add_listener_done("listener-added", false);
801 content::ExecuteScriptAsync(extension_web_contents,
802 "window.runServiceWorkerAsync()");
803 EXPECT_TRUE(add_listener_done.WaitUntilSatisfied());
804
805 base::RunLoop run_loop;
806 content::StoragePartition* storage_partition =
807 content::BrowserContext::GetDefaultStoragePartition(
808 browser()->profile());
809 content::StopServiceWorkerForPattern(
810 storage_partition->GetServiceWorkerContext(),
811 // The service worker is registered at the top level scope.
812 extension->url(), run_loop.QuitClosure());
813 run_loop.Run();
814 }
815
816 // Close the tab to |extension|'s resource. This will also close the
817 // extension's event page.
818 browser()->tab_strip_model()->CloseWebContentsAt(
819 browser()->tab_strip_model()->active_index(), TabStripModel::CLOSE_NONE);
820 lazy_observer.Wait();
821
822 // At this point both the extension worker and extension event page is not
823 // running. Since the worker registered a listener for tabs.onCreated, it
824 // will be started to dispatch the event once we create a tab.
825 ExtensionTestMessageListener newtab_listener("hello-newtab", false);
826 newtab_listener.set_failure_message("WRONG_NEWTAB");
827 content::WebContents* new_web_contents =
Istiaque Ahmed7105f2a2017-10-07 01:11:59828 AddTab(browser(), GURL(url::kAboutBlankURL));
829 EXPECT_TRUE(new_web_contents);
830 EXPECT_TRUE(newtab_listener.WaitUntilSatisfied());
831}
832
833// Tests that events to service worker correctly after browser restart.
834// This test is similar to EventsToStoppedExtension, except that the event
835// delivery is verified after a browser restart.
836IN_PROC_BROWSER_TEST_P(ServiceWorkerLazyBackgroundTest,
837 PRE_EventsAfterRestart) {
838 LazyBackgroundObserver lazy_observer;
839 ResultCatcher catcher;
840 const Extension* extension = LoadExtensionWithFlags(
841 test_data_dir_.AppendASCII("service_worker/events_to_stopped_extension"),
842 kFlagNone);
843 ASSERT_TRUE(extension);
844 EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
845
846 ProcessManager* pm = ProcessManager::Get(browser()->profile());
847 EXPECT_GT(pm->GetLazyKeepaliveCount(extension), 0);
848
849 // |extension|'s background page opens a tab to its resource.
850 content::WebContents* extension_web_contents =
851 browser()->tab_strip_model()->GetActiveWebContents();
852 EXPECT_TRUE(content::WaitForLoadStop(extension_web_contents));
853 EXPECT_EQ(extension->GetResourceURL("page.html").spec(),
854 extension_web_contents->GetURL().spec());
855 {
856 // Let the service worker start and register a listener to
857 // chrome.tabs.onCreated event.
858 ExtensionTestMessageListener add_listener_done("listener-added", false);
859 content::ExecuteScriptAsync(extension_web_contents,
860 "window.runServiceWorkerAsync()");
861 EXPECT_TRUE(add_listener_done.WaitUntilSatisfied());
862
863 base::RunLoop run_loop;
864 content::StoragePartition* storage_partition =
865 content::BrowserContext::GetDefaultStoragePartition(
866 browser()->profile());
867 content::StopServiceWorkerForPattern(
868 storage_partition->GetServiceWorkerContext(),
869 // The service worker is registered at the top level scope.
870 extension->url(), run_loop.QuitClosure());
871 run_loop.Run();
872 }
873
874 // Close the tab to |extension|'s resource. This will also close the
875 // extension's event page.
876 browser()->tab_strip_model()->CloseWebContentsAt(
877 browser()->tab_strip_model()->active_index(), TabStripModel::CLOSE_NONE);
878 lazy_observer.Wait();
879}
880
881IN_PROC_BROWSER_TEST_P(ServiceWorkerLazyBackgroundTest, EventsAfterRestart) {
882 ExtensionTestMessageListener newtab_listener("hello-newtab", false);
883 content::WebContents* new_web_contents =
884 AddTab(browser(), GURL(url::kAboutBlankURL));
Istiaque Ahmed805f6a83b2017-10-05 01:23:26885 EXPECT_TRUE(new_web_contents);
886 EXPECT_TRUE(newtab_listener.WaitUntilSatisfied());
887}
888
lazyboy4c82177a2016-10-18 00:04:09889// Tests that worker ref count increments while extension API function is
890// active.
Istiaque Ahmedea5ed5042017-09-25 19:00:16891IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, WorkerRefCount) {
lazyboy4c82177a2016-10-18 00:04:09892 // Extensions APIs from SW are only enabled on trunk.
893 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
894 const Extension* extension = LoadExtensionWithFlags(
895 test_data_dir_.AppendASCII("service_worker/api_worker_ref_count"),
896 kFlagNone);
897 ASSERT_TRUE(extension);
898 ui_test_utils::NavigateToURL(browser(),
899 extension->GetResourceURL("page.html"));
900 content::WebContents* web_contents =
901 browser()->tab_strip_model()->GetActiveWebContents();
902
903 ExtensionTestMessageListener worker_start_listener("WORKER STARTED", false);
904 worker_start_listener.set_failure_message("FAILURE");
905 ASSERT_TRUE(
906 content::ExecuteScript(web_contents, "window.runServiceWorker()"));
907 ASSERT_TRUE(worker_start_listener.WaitUntilSatisfied());
908
909 // Service worker should have no pending requests because it hasn't peformed
910 // any extension API request yet.
911 EXPECT_EQ(0u, GetWorkerRefCount(extension->url()));
912
913 ExtensionTestMessageListener worker_listener("CHECK_REF_COUNT", true);
914 worker_listener.set_failure_message("FAILURE");
915 ASSERT_TRUE(content::ExecuteScript(web_contents, "window.testSendMessage()"));
916 ASSERT_TRUE(worker_listener.WaitUntilSatisfied());
917
918 // Service worker should have exactly one pending request because
919 // chrome.test.sendMessage() API call is in-flight.
920 EXPECT_EQ(1u, GetWorkerRefCount(extension->url()));
921
922 // Peform another extension API request while one is ongoing.
923 {
924 ExtensionTestMessageListener listener("CHECK_REF_COUNT", true);
925 listener.set_failure_message("FAILURE");
926 ASSERT_TRUE(
927 content::ExecuteScript(web_contents, "window.testSendMessage()"));
928 ASSERT_TRUE(listener.WaitUntilSatisfied());
929
930 // Service worker currently has two extension API requests in-flight.
931 EXPECT_EQ(2u, GetWorkerRefCount(extension->url()));
932 // Finish executing the nested chrome.test.sendMessage() first.
933 listener.Reply("Hello world");
934 }
935
Istiaque Ahmedb57c9752017-08-20 19:08:57936 ExtensionTestMessageListener worker_completion_listener("SUCCESS_FROM_WORKER",
937 false);
lazyboy4c82177a2016-10-18 00:04:09938 // Finish executing chrome.test.sendMessage().
939 worker_listener.Reply("Hello world");
Istiaque Ahmedb57c9752017-08-20 19:08:57940 EXPECT_TRUE(worker_completion_listener.WaitUntilSatisfied());
941
942 // The following block makes sure we have received all the IPCs related to
943 // ref-count from the worker.
944 {
945 // The following roundtrip:
946 // browser->extension->worker->extension->browser
947 // will ensure that the worker sent the relevant ref count IPCs.
948 std::string result;
949 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
950 web_contents, "window.roundtripToWorker();", &result));
951 EXPECT_EQ("roundtrip-succeeded", result);
952
953 // Ensure IO thread IPCs run.
Gabriel Charette01507a22017-09-27 21:30:08954 content::RunAllTasksUntilIdle();
Istiaque Ahmedb57c9752017-08-20 19:08:57955 }
lazyboy4c82177a2016-10-18 00:04:09956
957 // The ref count should drop to 0.
958 EXPECT_EQ(0u, GetWorkerRefCount(extension->url()));
959}
960
lazyboyaea32c22016-01-04 21:37:07961// This test loads a web page that has an iframe pointing to a
962// chrome-extension:// URL. The URL is listed in the extension's
963// web_accessible_resources. Initially the iframe is served from the extension's
964// resource file. After verifying that, we register a Service Worker that
965// controls the extension. Further requests to the same resource as before
966// should now be served by the Service Worker.
967// This test also verifies that if the requested resource exists in the manifest
968// but is not present in the extension directory, the Service Worker can still
969// serve the resource file.
Istiaque Ahmedea5ed5042017-09-25 19:00:16970IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, WebAccessibleResourcesIframeSrc) {
lazyboyaea32c22016-01-04 21:37:07971 const Extension* extension = LoadExtensionWithFlags(
972 test_data_dir_.AppendASCII(
973 "service_worker/web_accessible_resources/iframe_src"),
974 kFlagNone);
975 ASSERT_TRUE(extension);
976 ASSERT_TRUE(StartEmbeddedTestServer());
falkenad185092016-06-16 06:10:02977
978 // Service workers can only control secure contexts
979 // (https://w3c.github.io/webappsec-secure-contexts/). For documents, this
980 // typically means the document must have a secure origin AND all its ancestor
981 // frames must have documents with secure origins. However, extension pages
982 // are considered secure, even if they have an ancestor document that is an
983 // insecure context (see GetSchemesBypassingSecureContextCheckWhitelist). So
984 // extension service workers must be able to control an extension page
985 // embedded in an insecure context. To test this, set up an insecure
986 // (non-localhost, non-https) URL for the web page. This page will create
987 // iframes that load extension pages that must be controllable by service
988 // worker.
falkenad185092016-06-16 06:10:02989 GURL page_url =
990 embedded_test_server()->GetURL("a.com",
991 "/extensions/api_test/service_worker/"
992 "web_accessible_resources/webpage.html");
993 EXPECT_FALSE(content::IsOriginSecure(page_url));
lazyboyaea32c22016-01-04 21:37:07994
995 content::WebContents* web_contents = AddTab(browser(), page_url);
996 std::string result;
997 // webpage.html will create an iframe pointing to a resource from |extension|.
998 // Expect the resource to be served by the extension.
999 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1000 web_contents, base::StringPrintf("window.testIframe('%s', 'iframe.html')",
1001 extension->id().c_str()),
1002 &result));
1003 EXPECT_EQ("FROM_EXTENSION_RESOURCE", result);
1004
1005 ExtensionTestMessageListener service_worker_ready_listener("SW_READY", false);
1006 EXPECT_TRUE(ExecuteScriptInBackgroundPageNoWait(
1007 extension->id(), "window.registerServiceWorker()"));
1008 EXPECT_TRUE(service_worker_ready_listener.WaitUntilSatisfied());
1009
1010 result.clear();
1011 // webpage.html will create another iframe pointing to a resource from
1012 // |extension| as before. But this time, the resource should be be served
1013 // from the Service Worker.
1014 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1015 web_contents, base::StringPrintf("window.testIframe('%s', 'iframe.html')",
1016 extension->id().c_str()),
1017 &result));
1018 EXPECT_EQ("FROM_SW_RESOURCE", result);
1019
1020 result.clear();
1021 // webpage.html will create yet another iframe pointing to a resource that
1022 // exists in the extension manifest's web_accessible_resources, but is not
1023 // present in the extension directory. Expect the resources of the iframe to
1024 // be served by the Service Worker.
1025 EXPECT_TRUE(content::ExecuteScriptAndExtractString(
1026 web_contents,
1027 base::StringPrintf("window.testIframe('%s', 'iframe_non_existent.html')",
1028 extension->id().c_str()),
1029 &result));
1030 EXPECT_EQ("FROM_SW_RESOURCE", result);
1031}
1032
Istiaque Ahmedea5ed5042017-09-25 19:00:161033IN_PROC_BROWSER_TEST_P(ServiceWorkerBackgroundSyncTest, Sync) {
lazyboybd325ae2015-11-18 21:35:261034 const Extension* extension = LoadExtensionWithFlags(
1035 test_data_dir_.AppendASCII("service_worker/sync"), kFlagNone);
1036 ASSERT_TRUE(extension);
1037 ui_test_utils::NavigateToURL(browser(),
1038 extension->GetResourceURL("page.html"));
1039 content::WebContents* web_contents =
1040 browser()->tab_strip_model()->GetActiveWebContents();
1041
1042 // Prevent firing by going offline.
1043 content::background_sync_test_util::SetOnline(web_contents, false);
1044
1045 ExtensionTestMessageListener sync_listener("SYNC: send-chats", false);
1046 sync_listener.set_failure_message("FAIL");
1047
1048 std::string result;
1049 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
1050 web_contents, "window.runServiceWorker()", &result));
1051 ASSERT_EQ("SERVICE_WORKER_READY", result);
1052
1053 EXPECT_FALSE(sync_listener.was_satisfied());
1054 // Resume firing by going online.
1055 content::background_sync_test_util::SetOnline(web_contents, true);
1056 EXPECT_TRUE(sync_listener.WaitUntilSatisfied());
1057}
1058
Istiaque Ahmedea5ed5042017-09-25 19:00:161059IN_PROC_BROWSER_TEST_P(ServiceWorkerTest,
horo1eeddde2015-11-19 05:59:251060 FetchFromContentScriptShouldNotGoToServiceWorkerOfPage) {
1061 ASSERT_TRUE(StartEmbeddedTestServer());
1062 GURL page_url = embedded_test_server()->GetURL(
1063 "/extensions/api_test/service_worker/content_script_fetch/"
1064 "controlled_page/index.html");
1065 content::WebContents* tab =
1066 browser()->tab_strip_model()->GetActiveWebContents();
1067 ui_test_utils::NavigateToURL(browser(), page_url);
1068 content::WaitForLoadStop(tab);
1069
1070 std::string value;
1071 ASSERT_TRUE(
1072 content::ExecuteScriptAndExtractString(tab, "register();", &value));
1073 EXPECT_EQ("SW controlled", value);
1074
1075 ASSERT_TRUE(RunExtensionTest("service_worker/content_script_fetch"))
1076 << message_;
1077}
1078
Istiaque Ahmedea5ed5042017-09-25 19:00:161079IN_PROC_BROWSER_TEST_P(ServiceWorkerPushMessagingTest, OnPush) {
lazyboy561b7de2015-11-19 19:27:301080 const Extension* extension = LoadExtensionWithFlags(
1081 test_data_dir_.AppendASCII("service_worker/push_messaging"), kFlagNone);
1082 ASSERT_TRUE(extension);
1083 GURL extension_url = extension->url();
1084
1085 ASSERT_NO_FATAL_FAILURE(GrantNotificationPermissionForTest(extension_url));
1086
1087 GURL url = extension->GetResourceURL("page.html");
1088 ui_test_utils::NavigateToURL(browser(), url);
1089
1090 content::WebContents* web_contents =
1091 browser()->tab_strip_model()->GetActiveWebContents();
1092
1093 // Start the ServiceWorker.
1094 ExtensionTestMessageListener ready_listener("SERVICE_WORKER_READY", false);
1095 ready_listener.set_failure_message("SERVICE_WORKER_FAILURE");
1096 const char* kScript = "window.runServiceWorker()";
1097 EXPECT_TRUE(content::ExecuteScript(web_contents->GetMainFrame(), kScript));
1098 EXPECT_TRUE(ready_listener.WaitUntilSatisfied());
1099
1100 PushMessagingAppIdentifier app_identifier =
1101 GetAppIdentifierForServiceWorkerRegistration(0LL, extension_url);
johnmea5045732016-09-08 17:23:291102 ASSERT_EQ(app_identifier.app_id(), gcm_driver()->last_gettoken_app_id());
1103 EXPECT_EQ("1234567890", gcm_driver()->last_gettoken_authorized_entity());
lazyboy561b7de2015-11-19 19:27:301104
lazyboyd429e2582016-05-20 20:18:521105 base::RunLoop run_loop;
lazyboy561b7de2015-11-19 19:27:301106 // Send a push message via gcm and expect the ServiceWorker to receive it.
1107 ExtensionTestMessageListener push_message_listener("OK", false);
1108 push_message_listener.set_failure_message("FAIL");
1109 gcm::IncomingMessage message;
1110 message.sender_id = "1234567890";
1111 message.raw_data = "testdata";
1112 message.decrypted = true;
lazyboyd429e2582016-05-20 20:18:521113 push_service()->SetMessageCallbackForTesting(run_loop.QuitClosure());
lazyboy561b7de2015-11-19 19:27:301114 push_service()->OnMessage(app_identifier.app_id(), message);
1115 EXPECT_TRUE(push_message_listener.WaitUntilSatisfied());
lazyboyd429e2582016-05-20 20:18:521116 run_loop.Run(); // Wait until the message is handled by push service.
lazyboy561b7de2015-11-19 19:27:301117}
1118
Istiaque Ahmedea5ed5042017-09-25 19:00:161119IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, FilteredEvents) {
Istiaque Ahmed9d1666182017-09-21 23:58:181120 // Extensions APIs from SW are only enabled on trunk.
1121 ScopedCurrentChannel current_channel_override(version_info::Channel::UNKNOWN);
1122 ASSERT_TRUE(RunExtensionTest("service_worker/filtered_events"));
1123}
1124
Rob Wue89b90032018-02-16 19:46:081125IN_PROC_BROWSER_TEST_P(ServiceWorkerTest, MimeHandlerView) {
1126 ASSERT_TRUE(RunExtensionTest("service_worker/mime_handler_view"));
1127}
1128
Istiaque Ahmed9ce21b32017-10-10 20:43:181129IN_PROC_BROWSER_TEST_P(ServiceWorkerLazyBackgroundTest,
1130 PRE_FilteredEventsAfterRestart) {
1131 LazyBackgroundObserver lazy_observer;
1132 ResultCatcher catcher;
1133 const Extension* extension = LoadExtensionWithFlags(
1134 test_data_dir_.AppendASCII(
1135 "service_worker/filtered_events_after_restart"),
1136 kFlagNone);
1137 ASSERT_TRUE(extension);
1138 EXPECT_TRUE(catcher.GetNextResult()) << catcher.message();
1139
1140 // |extension|'s background page opens a tab to its resource.
1141 content::WebContents* extension_web_contents =
1142 browser()->tab_strip_model()->GetActiveWebContents();
1143 EXPECT_TRUE(content::WaitForLoadStop(extension_web_contents));
1144 EXPECT_EQ(extension->GetResourceURL("page.html").spec(),
1145 extension_web_contents->GetURL().spec());
1146 {
1147 // Let the service worker start and register a filtered listener to
1148 // chrome.webNavigation.onCommitted event.
1149 ExtensionTestMessageListener add_listener_done("listener-added", false);
1150 add_listener_done.set_failure_message("FAILURE");
1151 content::ExecuteScriptAsync(extension_web_contents,
1152 "window.runServiceWorkerAsync()");
1153 EXPECT_TRUE(add_listener_done.WaitUntilSatisfied());
1154
1155 base::RunLoop run_loop;
1156 content::StoragePartition* storage_partition =
1157 content::BrowserContext::GetDefaultStoragePartition(
1158 browser()->profile());
1159 content::StopServiceWorkerForPattern(
1160 storage_partition->GetServiceWorkerContext(),
1161 // The service worker is registered at the top level scope.
1162 extension->url(), run_loop.QuitClosure());
1163 run_loop.Run();
1164 }
1165
1166 // Close the tab to |extension|'s resource. This will also close the
1167 // extension's event page.
1168 browser()->tab_strip_model()->CloseWebContentsAt(
1169 browser()->tab_strip_model()->active_index(), TabStripModel::CLOSE_NONE);
1170 lazy_observer.Wait();
1171}
1172
1173IN_PROC_BROWSER_TEST_P(ServiceWorkerLazyBackgroundTest,
1174 FilteredEventsAfterRestart) {
1175 // Create a tab to a.html, expect it to navigate to b.html. The service worker
1176 // will see two webNavigation.onCommitted events.
1177 ASSERT_TRUE(StartEmbeddedTestServer());
1178 GURL page_url = embedded_test_server()->GetURL(
1179 "/extensions/api_test/service_worker/filtered_events_after_restart/"
1180 "a.html");
1181 ExtensionTestMessageListener worker_filtered_event_listener(
1182 "PASS_FROM_WORKER", false);
1183 worker_filtered_event_listener.set_failure_message("FAIL_FROM_WORKER");
1184 content::WebContents* web_contents = AddTab(browser(), page_url);
1185 EXPECT_TRUE(web_contents);
1186 EXPECT_TRUE(worker_filtered_event_listener.WaitUntilSatisfied());
1187}
1188
Istiaque Ahmedea5ed5042017-09-25 19:00:161189// Run with both native and JS-based bindings. This ensures that both stable
1190// (JS) and experimental (native) phases work correctly with worker scripts
1191// while we launch native bindings to stable.
1192INSTANTIATE_TEST_CASE_P(ServiceWorkerTestWithNativeBindings,
1193 ServiceWorkerTest,
1194 ::testing::Values(NATIVE_BINDINGS));
1195INSTANTIATE_TEST_CASE_P(ServiceWorkerTestWithJSBindings,
1196 ServiceWorkerTest,
1197 ::testing::Values(JAVASCRIPT_BINDINGS));
1198INSTANTIATE_TEST_CASE_P(ServiceWorkerBackgroundSyncTestWithNativeBindings,
1199 ServiceWorkerBackgroundSyncTest,
1200 ::testing::Values(NATIVE_BINDINGS));
1201INSTANTIATE_TEST_CASE_P(ServiceWorkerBackgroundSyncTestWithJSBindings,
1202 ServiceWorkerBackgroundSyncTest,
1203 ::testing::Values(JAVASCRIPT_BINDINGS));
1204INSTANTIATE_TEST_CASE_P(ServiceWorkerPushMessagingTestWithNativeBindings,
1205 ServiceWorkerPushMessagingTest,
1206 ::testing::Values(NATIVE_BINDINGS));
1207INSTANTIATE_TEST_CASE_P(ServiceWorkerPushMessagingTestWithJSBindings,
1208 ServiceWorkerPushMessagingTest,
1209 ::testing::Values(JAVASCRIPT_BINDINGS));
Istiaque Ahmed805f6a83b2017-10-05 01:23:261210INSTANTIATE_TEST_CASE_P(ServiceWorkerLazyBackgroundTestWithNativeBindings,
1211 ServiceWorkerLazyBackgroundTest,
1212 ::testing::Values(NATIVE_BINDINGS));
1213INSTANTIATE_TEST_CASE_P(ServiceWorkerLazyBackgroundTestWithJSBindings,
1214 ServiceWorkerLazyBackgroundTest,
1215 ::testing::Values(JAVASCRIPT_BINDINGS));
Istiaque Ahmedea5ed5042017-09-25 19:00:161216
annekao38685502015-07-14 17:46:391217} // namespace extensions