[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 1 | // Copyright 2014 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 | |
| 5 | // This file tests that Service Workers (a Content feature) work in the Chromium |
| 6 | // embedder. |
| 7 | |
| 8 | #include "base/bind.h" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 9 | #include "base/command_line.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 10 | #include "base/files/scoped_temp_dir.h" |
| 11 | #include "base/numerics/safe_conversions.h" |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 12 | #include "base/path_service.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 13 | #include "base/run_loop.h" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 14 | #include "base/strings/stringprintf.h" |
| 15 | #include "base/strings/utf_string_conversions.h" |
Eric Seckler | 8652dcd5 | 2018-09-20 10:42:28 | [diff] [blame] | 16 | #include "base/task/post_task.h" |
Devlin Cronin | 626d80c | 2018-06-01 01:08:36 | [diff] [blame] | 17 | #include "base/test/metrics/histogram_tester.h" |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 18 | #include "base/test/scoped_feature_list.h" |
jam | 3f2d393 | 2017-04-26 20:28:51 | [diff] [blame] | 19 | #include "base/threading/thread_restrictions.h" |
grt | 56c07a2 | 2016-07-19 11:52:20 | [diff] [blame] | 20 | #include "build/build_config.h" |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 21 | #include "chrome/browser/content_settings/host_content_settings_map_factory.h" |
| 22 | #include "chrome/browser/content_settings/tab_specific_content_settings.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 23 | #include "chrome/browser/profiles/profile.h" |
| 24 | #include "chrome/browser/ui/browser.h" |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 25 | #include "chrome/browser/ui/browser_window.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 26 | #include "chrome/browser/ui/tabs/tab_strip_model.h" |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 27 | #include "chrome/common/chrome_paths.h" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 28 | #include "chrome/common/chrome_switches.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 29 | #include "chrome/test/base/in_process_browser_test.h" |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 30 | #include "chrome/test/base/test_chrome_web_ui_controller_factory.h" |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 31 | #include "chrome/test/base/ui_test_utils.h" |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 32 | #include "components/content_settings/core/browser/host_content_settings_map.h" |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 33 | #include "components/content_settings/core/common/pref_names.h" |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 34 | #include "components/favicon/content/content_favicon_driver.h" |
| 35 | #include "components/favicon/core/favicon_driver_observer.h" |
Scott Violet | 9ae8289 | 2018-03-01 18:38:12 | [diff] [blame] | 36 | #include "components/nacl/common/buildflags.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 37 | #include "content/public/browser/browser_context.h" |
Eric Seckler | 8652dcd5 | 2018-09-20 10:42:28 | [diff] [blame] | 38 | #include "content/public/browser/browser_task_traits.h" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 39 | #include "content/public/browser/render_frame_host.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 40 | #include "content/public/browser/service_worker_context.h" |
| 41 | #include "content/public/browser/storage_partition.h" |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 42 | #include "content/public/browser/url_data_source.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 43 | #include "content/public/browser/web_contents.h" |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 44 | #include "content/public/browser/web_ui_controller.h" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 45 | #include "content/public/test/browser_test_utils.h" |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 46 | #include "net/dns/mock_host_resolver.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 47 | #include "net/test/embedded_test_server/embedded_test_server.h" |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 48 | #include "net/test/embedded_test_server/http_request.h" |
| 49 | #include "net/test/embedded_test_server/http_response.h" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 50 | #include "ppapi/shared_impl/ppapi_switches.h" |
Zhuoyu Qian | 47ed0fc5 | 2018-09-06 02:13:40 | [diff] [blame] | 51 | #include "third_party/blink/public/common/messaging/string_message_codec.h" |
Leon Han | d0da472 | 2019-07-11 08:12:04 | [diff] [blame] | 52 | #include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h" |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 53 | |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 54 | namespace chrome_service_worker_browser_test { |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 55 | |
Nico Weber | af3b00b | 2017-09-11 17:58:17 | [diff] [blame] | 56 | const char kInstallAndWaitForActivatedPage[] = |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 57 | "<script>" |
| 58 | "navigator.serviceWorker.register('./sw.js', {scope: './scope/'})" |
| 59 | " .then(function(reg) {" |
| 60 | " reg.addEventListener('updatefound', function() {" |
| 61 | " var worker = reg.installing;" |
| 62 | " worker.addEventListener('statechange', function() {" |
| 63 | " if (worker.state == 'activated')" |
| 64 | " document.title = 'READY';" |
| 65 | " });" |
| 66 | " });" |
| 67 | " });" |
| 68 | "</script>"; |
| 69 | |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 70 | class ChromeServiceWorkerTest : public InProcessBrowserTest { |
| 71 | protected: |
| 72 | ChromeServiceWorkerTest() { |
| 73 | EXPECT_TRUE(service_worker_dir_.CreateUniqueTempDir()); |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 74 | EXPECT_TRUE(base::CreateDirectoryAndGetError( |
| 75 | service_worker_dir_.GetPath().Append( |
| 76 | FILE_PATH_LITERAL("scope")), nullptr)); |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 77 | } |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 78 | ~ChromeServiceWorkerTest() override {} |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 79 | |
| 80 | void WriteFile(const base::FilePath::StringType& filename, |
| 81 | base::StringPiece contents) { |
Francois Doray | e6fb2d0 | 2017-10-18 21:29:13 | [diff] [blame] | 82 | base::ScopedAllowBlockingForTesting allow_blocking; |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 83 | EXPECT_EQ(base::checked_cast<int>(contents.size()), |
vabr | 96fd0c0f | 2016-09-13 14:21:31 | [diff] [blame] | 84 | base::WriteFile(service_worker_dir_.GetPath().Append(filename), |
| 85 | contents.data(), contents.size())); |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 86 | } |
| 87 | |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 88 | void NavigateToPageAndWaitForReadyTitle(const std::string path) { |
| 89 | const base::string16 expected_title1 = base::ASCIIToUTF16("READY"); |
| 90 | content::TitleWatcher title_watcher1( |
| 91 | browser()->tab_strip_model()->GetActiveWebContents(), expected_title1); |
| 92 | ui_test_utils::NavigateToURL(browser(), |
| 93 | embedded_test_server()->GetURL(path)); |
| 94 | EXPECT_EQ(expected_title1, title_watcher1.WaitAndGetTitle()); |
| 95 | } |
| 96 | |
| 97 | void InitializeServer() { |
| 98 | embedded_test_server()->ServeFilesFromDirectory( |
| 99 | service_worker_dir_.GetPath()); |
| 100 | ASSERT_TRUE(embedded_test_server()->Start()); |
| 101 | } |
| 102 | |
| 103 | content::ServiceWorkerContext* GetServiceWorkerContext() { |
| 104 | return content::BrowserContext::GetDefaultStoragePartition( |
| 105 | browser()->profile()) |
| 106 | ->GetServiceWorkerContext(); |
| 107 | } |
| 108 | |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 109 | base::ScopedTempDir service_worker_dir_; |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 110 | |
| 111 | private: |
| 112 | DISALLOW_COPY_AND_ASSIGN(ChromeServiceWorkerTest); |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 113 | }; |
| 114 | |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 115 | template <typename T> |
| 116 | static void ExpectResultAndRun(T expected, |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 117 | const base::Closure& continuation, |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 118 | T actual) { |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 119 | EXPECT_EQ(expected, actual); |
| 120 | continuation.Run(); |
| 121 | } |
| 122 | |
| 123 | // http://crbug.com/368570 |
| 124 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerTest, |
| 125 | CanShutDownWithRegisteredServiceWorker) { |
| 126 | WriteFile(FILE_PATH_LITERAL("service_worker.js"), ""); |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 127 | |
vabr | 96fd0c0f | 2016-09-13 14:21:31 | [diff] [blame] | 128 | embedded_test_server()->ServeFilesFromDirectory( |
| 129 | service_worker_dir_.GetPath()); |
svaldez | a01f7d9 | 2015-11-18 17:47:56 | [diff] [blame] | 130 | ASSERT_TRUE(embedded_test_server()->Start()); |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 131 | |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 132 | base::RunLoop run_loop; |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 133 | blink::mojom::ServiceWorkerRegistrationOptions options( |
Asami Doi | 5de8dea | 2018-09-13 10:01:07 | [diff] [blame] | 134 | embedded_test_server()->GetURL("/"), blink::mojom::ScriptType::kClassic, |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 135 | blink::mojom::ServiceWorkerUpdateViaCache::kImports); |
| 136 | GetServiceWorkerContext()->RegisterServiceWorker( |
| 137 | embedded_test_server()->GetURL("/service_worker.js"), options, |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 138 | base::Bind(&ExpectResultAndRun<bool>, true, run_loop.QuitClosure())); |
[email protected] | 294bdb3 | 2014-05-30 07:01:54 | [diff] [blame] | 139 | run_loop.Run(); |
| 140 | |
| 141 | // Leave the Service Worker registered, and make sure that the browser can |
| 142 | // shut down without DCHECK'ing. It'd be nice to check here that the SW is |
| 143 | // actually occupying a process, but we don't yet have the public interface to |
| 144 | // do that. |
| 145 | } |
| 146 | |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 147 | // http://crbug.com/419290 |
| 148 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerTest, |
| 149 | CanCloseIncognitoWindowWithServiceWorkerController) { |
| 150 | WriteFile(FILE_PATH_LITERAL("service_worker.js"), ""); |
| 151 | WriteFile(FILE_PATH_LITERAL("service_worker.js.mock-http-headers"), |
zmo | 9528c9f4 | 2015-08-04 22:12:08 | [diff] [blame] | 152 | "HTTP/1.1 200 OK\nContent-Type: text/javascript"); |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 153 | WriteFile(FILE_PATH_LITERAL("test.html"), ""); |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 154 | InitializeServer(); |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 155 | |
| 156 | Browser* incognito = CreateIncognitoBrowser(); |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 157 | |
| 158 | base::RunLoop run_loop; |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 159 | blink::mojom::ServiceWorkerRegistrationOptions options( |
Asami Doi | 5de8dea | 2018-09-13 10:01:07 | [diff] [blame] | 160 | embedded_test_server()->GetURL("/"), blink::mojom::ScriptType::kClassic, |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 161 | blink::mojom::ServiceWorkerUpdateViaCache::kImports); |
| 162 | GetServiceWorkerContext()->RegisterServiceWorker( |
| 163 | embedded_test_server()->GetURL("/service_worker.js"), options, |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 164 | base::Bind(&ExpectResultAndRun<bool>, true, run_loop.QuitClosure())); |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 165 | run_loop.Run(); |
| 166 | |
| 167 | ui_test_utils::NavigateToURL(incognito, |
| 168 | embedded_test_server()->GetURL("/test.html")); |
| 169 | |
Qiang Xu | 2a41181f | 2018-04-11 22:38:32 | [diff] [blame] | 170 | CloseBrowserSynchronously(incognito); |
falken | 41f417516 | 2014-10-29 07:03:41 | [diff] [blame] | 171 | |
| 172 | // Test passes if we don't crash. |
| 173 | } |
| 174 | |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 175 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerTest, |
| 176 | FailRegisterServiceWorkerWhenJSDisabled) { |
| 177 | WriteFile(FILE_PATH_LITERAL("service_worker.js"), ""); |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 178 | InitializeServer(); |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 179 | |
| 180 | HostContentSettingsMapFactory::GetForProfile(browser()->profile()) |
Darin Fisher | 42f5e7d | 2019-10-30 07:15:45 | [diff] [blame] | 181 | ->SetDefaultContentSetting(ContentSettingsType::JAVASCRIPT, |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 182 | CONTENT_SETTING_BLOCK); |
| 183 | |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 184 | base::RunLoop run_loop; |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 185 | blink::mojom::ServiceWorkerRegistrationOptions options( |
Asami Doi | 5de8dea | 2018-09-13 10:01:07 | [diff] [blame] | 186 | embedded_test_server()->GetURL("/"), blink::mojom::ScriptType::kClassic, |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 187 | blink::mojom::ServiceWorkerUpdateViaCache::kImports); |
| 188 | GetServiceWorkerContext()->RegisterServiceWorker( |
| 189 | embedded_test_server()->GetURL("/service_worker.js"), options, |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 190 | base::Bind(&ExpectResultAndRun<bool>, false, run_loop.QuitClosure())); |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 191 | run_loop.Run(); |
| 192 | } |
| 193 | |
| 194 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerTest, |
| 195 | FallbackMainResourceRequestWhenJSDisabled) { |
| 196 | WriteFile( |
| 197 | FILE_PATH_LITERAL("sw.js"), |
| 198 | "self.onfetch = function(e) {" |
| 199 | " e.respondWith(new Response('<title>Fail</title>'," |
| 200 | " {headers: {'Content-Type': 'text/html'}}));" |
| 201 | "};"); |
| 202 | WriteFile(FILE_PATH_LITERAL("scope/done.html"), "<title>Done</title>"); |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 203 | WriteFile(FILE_PATH_LITERAL("test.html"), kInstallAndWaitForActivatedPage); |
| 204 | InitializeServer(); |
| 205 | NavigateToPageAndWaitForReadyTitle("/test.html"); |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 206 | |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 207 | GetServiceWorkerContext()->StopAllServiceWorkersForOrigin( |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 208 | embedded_test_server()->base_url()); |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 209 | HostContentSettingsMapFactory::GetForProfile(browser()->profile()) |
Darin Fisher | 42f5e7d | 2019-10-30 07:15:45 | [diff] [blame] | 210 | ->SetDefaultContentSetting(ContentSettingsType::JAVASCRIPT, |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 211 | CONTENT_SETTING_BLOCK); |
| 212 | |
| 213 | const base::string16 expected_title2 = base::ASCIIToUTF16("Done"); |
| 214 | content::TitleWatcher title_watcher2( |
| 215 | browser()->tab_strip_model()->GetActiveWebContents(), expected_title2); |
| 216 | ui_test_utils::NavigateToURL( |
| 217 | browser(), |
| 218 | embedded_test_server()->GetURL("/scope/done.html")); |
| 219 | EXPECT_EQ(expected_title2, title_watcher2.WaitAndGetTitle()); |
| 220 | |
| 221 | content::WebContents* web_contents = |
| 222 | browser()->tab_strip_model()->GetActiveWebContents(); |
Darin Fisher | 42f5e7d | 2019-10-30 07:15:45 | [diff] [blame] | 223 | EXPECT_TRUE(TabSpecificContentSettings::FromWebContents(web_contents) |
| 224 | ->IsContentBlocked(ContentSettingsType::JAVASCRIPT)); |
shimazu | ce8af8812 | 2016-10-06 23:49:21 | [diff] [blame] | 225 | } |
| 226 | |
Jon Mann | b528b40 | 2018-08-10 21:05:37 | [diff] [blame] | 227 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerTest, |
Azeem Arshad | 336e5af | 2019-01-16 22:27:25 | [diff] [blame] | 228 | StartServiceWorkerAndDispatchMessage) { |
| 229 | base::RunLoop run_loop; |
| 230 | blink::TransferableMessage msg; |
| 231 | const base::string16 message_data = base::UTF8ToUTF16("testMessage"); |
| 232 | |
| 233 | WriteFile(FILE_PATH_LITERAL("sw.js"), "self.onfetch = function(e) {};"); |
| 234 | WriteFile(FILE_PATH_LITERAL("test.html"), kInstallAndWaitForActivatedPage); |
| 235 | InitializeServer(); |
| 236 | NavigateToPageAndWaitForReadyTitle("/test.html"); |
| 237 | msg.owned_encoded_message = blink::EncodeStringMessage(message_data); |
| 238 | msg.encoded_message = msg.owned_encoded_message; |
| 239 | |
Sami Kyostila | 5e1306d | 2019-08-14 11:01:29 | [diff] [blame] | 240 | base::PostTask( |
Azeem Arshad | 336e5af | 2019-01-16 22:27:25 | [diff] [blame] | 241 | FROM_HERE, {content::BrowserThread::IO}, |
| 242 | base::BindOnce( |
| 243 | &content::ServiceWorkerContext::StartServiceWorkerAndDispatchMessage, |
| 244 | base::Unretained(GetServiceWorkerContext()), |
| 245 | embedded_test_server()->GetURL("/scope/"), std::move(msg), |
| 246 | base::BindRepeating(&ExpectResultAndRun<bool>, true, |
| 247 | run_loop.QuitClosure()))); |
| 248 | |
| 249 | run_loop.Run(); |
| 250 | } |
| 251 | |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 252 | class ChromeServiceWorkerFetchTest : public ChromeServiceWorkerTest { |
| 253 | protected: |
| 254 | ChromeServiceWorkerFetchTest() {} |
| 255 | ~ChromeServiceWorkerFetchTest() override {} |
| 256 | |
| 257 | void SetUpOnMainThread() override { |
| 258 | WriteServiceWorkerFetchTestFiles(); |
vabr | 96fd0c0f | 2016-09-13 14:21:31 | [diff] [blame] | 259 | embedded_test_server()->ServeFilesFromDirectory( |
| 260 | service_worker_dir_.GetPath()); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 261 | ASSERT_TRUE(embedded_test_server()->Start()); |
| 262 | InitializeServiceWorkerFetchTestPage(); |
| 263 | } |
| 264 | |
| 265 | std::string ExecuteScriptAndExtractString(const std::string& js) { |
| 266 | std::string result; |
| 267 | EXPECT_TRUE(content::ExecuteScriptAndExtractString( |
| 268 | browser()->tab_strip_model()->GetActiveWebContents(), js, &result)); |
| 269 | return result; |
| 270 | } |
| 271 | |
| 272 | std::string RequestString(const std::string& url, |
| 273 | const std::string& mode, |
| 274 | const std::string& credentials) const { |
| 275 | return base::StringPrintf("url:%s, mode:%s, credentials:%s\n", url.c_str(), |
| 276 | mode.c_str(), credentials.c_str()); |
| 277 | } |
| 278 | |
| 279 | std::string GetURL(const std::string& relative_url) const { |
| 280 | return embedded_test_server()->GetURL(relative_url).spec(); |
| 281 | } |
| 282 | |
| 283 | private: |
| 284 | void WriteServiceWorkerFetchTestFiles() { |
| 285 | WriteFile(FILE_PATH_LITERAL("sw.js"), |
| 286 | "this.onactivate = function(event) {" |
| 287 | " event.waitUntil(self.clients.claim());" |
| 288 | "};" |
| 289 | "this.onfetch = function(event) {" |
Tsuyoshi Horo | 49dd35bd | 2018-12-11 09:30:06 | [diff] [blame] | 290 | // Ignore the default favicon request. The default favicon request |
| 291 | // is sent after the page loading is finished, and we can't |
| 292 | // control the timing of the request. If the request is sent after |
| 293 | // clients.claim() is called, fetch event for the default favicon |
| 294 | // request is triggered and the tests become flaky. See |
| 295 | // https://crbug.com/912543. |
| 296 | " if (event.request.url.endsWith('/favicon.ico')) {" |
| 297 | " return;" |
| 298 | " }" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 299 | " event.respondWith(" |
| 300 | " self.clients.matchAll().then(function(clients) {" |
| 301 | " clients.forEach(function(client) {" |
| 302 | " client.postMessage(" |
| 303 | " 'url:' + event.request.url + ', ' +" |
| 304 | " 'mode:' + event.request.mode + ', ' +" |
| 305 | " 'credentials:' + event.request.credentials" |
| 306 | " );" |
| 307 | " });" |
| 308 | " return fetch(event.request);" |
| 309 | " }));" |
| 310 | "};"); |
| 311 | WriteFile(FILE_PATH_LITERAL("test.html"), |
| 312 | "<script>" |
| 313 | "navigator.serviceWorker.register('./sw.js', {scope: './'})" |
| 314 | " .then(function(reg) {" |
| 315 | " reg.addEventListener('updatefound', function() {" |
| 316 | " var worker = reg.installing;" |
| 317 | " worker.addEventListener('statechange', function() {" |
| 318 | " if (worker.state == 'activated')" |
| 319 | " document.title = 'READY';" |
| 320 | " });" |
| 321 | " });" |
| 322 | " });" |
| 323 | "var reportOnFetch = true;" |
| 324 | "var issuedRequests = [];" |
| 325 | "function reportRequests() {" |
| 326 | " var str = '';" |
| 327 | " issuedRequests.forEach(function(data) {" |
| 328 | " str += data + '\\n';" |
| 329 | " });" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 330 | " window.domAutomationController.send(str);" |
| 331 | "}" |
| 332 | "navigator.serviceWorker.addEventListener(" |
| 333 | " 'message'," |
| 334 | " function(event) {" |
| 335 | " issuedRequests.push(event.data);" |
| 336 | " if (reportOnFetch) {" |
| 337 | " reportRequests();" |
| 338 | " }" |
| 339 | " }, false);" |
| 340 | "</script>"); |
| 341 | } |
| 342 | |
| 343 | void InitializeServiceWorkerFetchTestPage() { |
| 344 | // The message "READY" will be sent when the service worker is activated. |
| 345 | const base::string16 expected_title = base::ASCIIToUTF16("READY"); |
| 346 | content::TitleWatcher title_watcher( |
| 347 | browser()->tab_strip_model()->GetActiveWebContents(), expected_title); |
| 348 | ui_test_utils::NavigateToURL(browser(), |
| 349 | embedded_test_server()->GetURL("/test.html")); |
| 350 | EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle()); |
| 351 | } |
| 352 | |
| 353 | DISALLOW_COPY_AND_ASSIGN(ChromeServiceWorkerFetchTest); |
| 354 | }; |
| 355 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 356 | class FaviconUpdateWaiter : public favicon::FaviconDriverObserver { |
| 357 | public: |
Evan Stade | 22e3f9b | 2019-10-01 21:12:17 | [diff] [blame] | 358 | explicit FaviconUpdateWaiter(content::WebContents* web_contents) { |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 359 | scoped_observer_.Add( |
| 360 | favicon::ContentFaviconDriver::FromWebContents(web_contents)); |
| 361 | } |
Evan Stade | 22e3f9b | 2019-10-01 21:12:17 | [diff] [blame] | 362 | ~FaviconUpdateWaiter() override = default; |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 363 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 364 | void Wait() { |
| 365 | if (updated_) |
| 366 | return; |
| 367 | |
| 368 | base::RunLoop run_loop; |
| 369 | quit_closure_ = run_loop.QuitClosure(); |
| 370 | run_loop.Run(); |
| 371 | } |
| 372 | |
| 373 | private: |
| 374 | void OnFaviconUpdated(favicon::FaviconDriver* favicon_driver, |
| 375 | NotificationIconType notification_icon_type, |
| 376 | const GURL& icon_url, |
| 377 | bool icon_url_changed, |
| 378 | const gfx::Image& image) override { |
| 379 | updated_ = true; |
| 380 | if (!quit_closure_.is_null()) |
| 381 | std::move(quit_closure_).Run(); |
| 382 | } |
| 383 | |
Evan Stade | 22e3f9b | 2019-10-01 21:12:17 | [diff] [blame] | 384 | bool updated_ = false; |
| 385 | ScopedObserver<favicon::FaviconDriver, favicon::FaviconDriverObserver> |
| 386 | scoped_observer_{this}; |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 387 | base::OnceClosure quit_closure_; |
| 388 | |
| 389 | DISALLOW_COPY_AND_ASSIGN(FaviconUpdateWaiter); |
| 390 | }; |
| 391 | |
| 392 | class ChromeServiceWorkerLinkFetchTest : public ChromeServiceWorkerFetchTest { |
| 393 | protected: |
| 394 | ChromeServiceWorkerLinkFetchTest() {} |
| 395 | ~ChromeServiceWorkerLinkFetchTest() override {} |
| 396 | void SetUpOnMainThread() override { |
| 397 | // Map all hosts to localhost and setup the EmbeddedTestServer for |
| 398 | // redirects. |
| 399 | host_resolver()->AddRule("*", "127.0.0.1"); |
| 400 | ChromeServiceWorkerFetchTest::SetUpOnMainThread(); |
| 401 | } |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 402 | std::string ExecuteManifestFetchTest(const std::string& url, |
| 403 | const std::string& cross_origin) { |
| 404 | std::string js( |
| 405 | base::StringPrintf("reportOnFetch = false;" |
| 406 | "var link = document.createElement('link');" |
| 407 | "link.rel = 'manifest';" |
| 408 | "link.href = '%s';", |
| 409 | url.c_str())); |
| 410 | if (!cross_origin.empty()) { |
| 411 | js += |
| 412 | base::StringPrintf("link.crossOrigin = '%s';", cross_origin.c_str()); |
| 413 | } |
| 414 | js += "document.head.appendChild(link);"; |
| 415 | ExecuteJavaScriptForTests(js); |
horo | 482eeff | 2016-07-19 23:06:58 | [diff] [blame] | 416 | return GetManifestAndIssuedRequests(); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 417 | } |
| 418 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 419 | std::string ExecuteFaviconFetchTest(const std::string& url) { |
| 420 | FaviconUpdateWaiter waiter( |
| 421 | browser()->tab_strip_model()->GetActiveWebContents()); |
| 422 | std::string js( |
| 423 | base::StringPrintf("reportOnFetch = false;" |
| 424 | "var link = document.createElement('link');" |
| 425 | "link.rel = 'icon';" |
| 426 | "link.href = '%s';" |
| 427 | "document.head.appendChild(link);", |
| 428 | url.c_str())); |
| 429 | ExecuteJavaScriptForTests(js); |
| 430 | waiter.Wait(); |
| 431 | return ExecuteScriptAndExtractString("reportRequests();"); |
| 432 | } |
| 433 | |
| 434 | void CopyTestFile(const std::string& src, const std::string& dst) { |
| 435 | base::ScopedAllowBlockingForTesting allow_blocking; |
| 436 | base::FilePath test_data_dir; |
| 437 | base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_dir); |
| 438 | EXPECT_TRUE(base::CopyFile(test_data_dir.AppendASCII(src), |
| 439 | service_worker_dir_.GetPath().AppendASCII(dst))); |
| 440 | } |
| 441 | |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 442 | private: |
| 443 | void ExecuteJavaScriptForTests(const std::string& js) { |
Sam McNally | cfe7a06 | 2017-11-02 00:40:07 | [diff] [blame] | 444 | base::RunLoop run_loop; |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 445 | browser() |
| 446 | ->tab_strip_model() |
| 447 | ->GetActiveWebContents() |
| 448 | ->GetMainFrame() |
Sam McNally | cfe7a06 | 2017-11-02 00:40:07 | [diff] [blame] | 449 | ->ExecuteJavaScriptForTests( |
| 450 | base::ASCIIToUTF16(js), |
Avi Drissman | 8e888000 | 2019-03-12 00:33:27 | [diff] [blame] | 451 | base::BindOnce([](const base::Closure& quit_callback, |
| 452 | base::Value result) { quit_callback.Run(); }, |
| 453 | run_loop.QuitClosure())); |
Sam McNally | cfe7a06 | 2017-11-02 00:40:07 | [diff] [blame] | 454 | run_loop.Run(); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 455 | } |
| 456 | |
horo | 482eeff | 2016-07-19 23:06:58 | [diff] [blame] | 457 | std::string GetManifestAndIssuedRequests() { |
| 458 | base::RunLoop run_loop; |
| 459 | browser()->tab_strip_model()->GetActiveWebContents()->GetManifest( |
| 460 | base::Bind(&ManifestCallbackAndRun, run_loop.QuitClosure())); |
| 461 | run_loop.Run(); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 462 | return ExecuteScriptAndExtractString( |
| 463 | "if (issuedRequests.length != 0) reportRequests();" |
| 464 | "else reportOnFetch = true;"); |
| 465 | } |
horo | 482eeff | 2016-07-19 23:06:58 | [diff] [blame] | 466 | |
| 467 | static void ManifestCallbackAndRun(const base::Closure& continuation, |
| 468 | const GURL&, |
Dmitry Gozman | 88ca5a99 | 2018-05-18 00:13:33 | [diff] [blame] | 469 | const blink::Manifest&) { |
horo | 482eeff | 2016-07-19 23:06:58 | [diff] [blame] | 470 | continuation.Run(); |
| 471 | } |
| 472 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 473 | DISALLOW_COPY_AND_ASSIGN(ChromeServiceWorkerLinkFetchTest); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 474 | }; |
| 475 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 476 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerLinkFetchTest, ManifestSameOrigin) { |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 477 | // <link rel="manifest" href="manifest.json"> |
Takeshi Yoshino | 2e231cf | 2017-06-21 04:40:12 | [diff] [blame] | 478 | EXPECT_EQ(RequestString(GetURL("/manifest.json"), "cors", "omit"), |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 479 | ExecuteManifestFetchTest("manifest.json", "")); |
| 480 | } |
| 481 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 482 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerLinkFetchTest, |
| 483 | ManifestSameOriginUseCredentials) { |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 484 | // <link rel="manifest" href="manifest.json" crossorigin="use-credentials"> |
| 485 | EXPECT_EQ(RequestString(GetURL("/manifest.json"), "cors", "include"), |
| 486 | ExecuteManifestFetchTest("manifest.json", "use-credentials")); |
| 487 | } |
| 488 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 489 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerLinkFetchTest, ManifestOtherOrigin) { |
| 490 | // <link rel="manifest" href="http://www.example.com:PORT/manifest.json"> |
| 491 | const std::string url = embedded_test_server() |
| 492 | ->GetURL("www.example.com", "/manifest.json") |
| 493 | .spec(); |
| 494 | EXPECT_EQ(RequestString(url, "cors", "omit"), |
| 495 | ExecuteManifestFetchTest(url, "")); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 496 | } |
| 497 | |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 498 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerLinkFetchTest, |
| 499 | ManifestOtherOriginUseCredentials) { |
| 500 | // <link rel="manifest" href="http://www.example.com:PORT/manifest.json" |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 501 | // crossorigin="use-credentials"> |
Tsuyoshi Horo | 75783543 | 2018-11-15 00:21:35 | [diff] [blame] | 502 | const std::string url = embedded_test_server() |
| 503 | ->GetURL("www.example.com", "/manifest.json") |
| 504 | .spec(); |
| 505 | EXPECT_EQ(RequestString(url, "cors", "include"), |
| 506 | ExecuteManifestFetchTest(url, "use-credentials")); |
| 507 | } |
| 508 | |
| 509 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerLinkFetchTest, FaviconSameOrigin) { |
| 510 | // <link rel="favicon" href="fav.png"> |
| 511 | CopyTestFile("favicon/icon.png", "fav.png"); |
| 512 | EXPECT_EQ(RequestString(GetURL("/fav.png"), "no-cors", "include"), |
| 513 | ExecuteFaviconFetchTest("/fav.png")); |
| 514 | } |
| 515 | |
| 516 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerLinkFetchTest, FaviconOtherOrigin) { |
| 517 | // <link rel="favicon" href="http://www.example.com:PORT/fav.png"> |
| 518 | CopyTestFile("favicon/icon.png", "fav.png"); |
| 519 | const std::string url = |
| 520 | embedded_test_server()->GetURL("www.example.com", "/fav.png").spec(); |
| 521 | EXPECT_EQ("", ExecuteFaviconFetchTest(url)); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 522 | } |
| 523 | |
Nico Weber | af3b00b | 2017-09-11 17:58:17 | [diff] [blame] | 524 | #if BUILDFLAG(ENABLE_NACL) |
Matt Falkenhagen | 7031e8b | 2018-02-20 03:30:33 | [diff] [blame] | 525 | // This test registers a service worker and then loads a controlled iframe that |
| 526 | // creates a PNaCl plugin in an <embed> element. Once loaded, the PNaCl plugin |
| 527 | // is ordered to do a resource request for "/echo". The service worker records |
| 528 | // all the fetch events it sees. Since requests for plug-ins and requests |
| 529 | // initiated by plug-ins should not be interecepted by service workers, we |
| 530 | // expect that the the service worker only see the navigation request for the |
| 531 | // iframe. |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 532 | class ChromeServiceWorkerFetchPPAPITest : public ChromeServiceWorkerFetchTest { |
| 533 | protected: |
| 534 | ChromeServiceWorkerFetchPPAPITest() {} |
| 535 | ~ChromeServiceWorkerFetchPPAPITest() override {} |
| 536 | |
Derek Schuff | d71a0582 | 2019-05-30 19:50:13 | [diff] [blame] | 537 | void SetUpCommandLine(base::CommandLine* command_line) override { |
| 538 | ChromeServiceWorkerFetchTest::SetUpCommandLine(command_line); |
| 539 | // Use --enable-nacl flag to ensure the PNaCl module can load (without |
| 540 | // needing to use an OT token) |
| 541 | command_line->AppendSwitch(switches::kEnableNaCl); |
| 542 | } |
| 543 | |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 544 | void SetUpOnMainThread() override { |
| 545 | base::FilePath document_root; |
| 546 | ASSERT_TRUE(ui_test_utils::GetRelativeBuildDirectory(&document_root)); |
| 547 | embedded_test_server()->AddDefaultHandlers( |
| 548 | document_root.Append(FILE_PATH_LITERAL("nacl_test_data")) |
| 549 | .Append(FILE_PATH_LITERAL("pnacl"))); |
| 550 | ChromeServiceWorkerFetchTest::SetUpOnMainThread(); |
| 551 | test_page_url_ = GetURL("/pnacl_url_loader.html"); |
| 552 | } |
| 553 | |
Matt Falkenhagen | 7031e8b | 2018-02-20 03:30:33 | [diff] [blame] | 554 | std::string GetNavigationRequestString(const std::string& fragment) const { |
| 555 | return RequestString(test_page_url_ + fragment, "navigate", "include"); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 556 | } |
| 557 | |
| 558 | std::string ExecutePNACLUrlLoaderTest(const std::string& mode) { |
| 559 | std::string result(ExecuteScriptAndExtractString( |
| 560 | base::StringPrintf("reportOnFetch = false;" |
| 561 | "var iframe = document.createElement('iframe');" |
| 562 | "iframe.src='%s#%s';" |
| 563 | "document.body.appendChild(iframe);", |
| 564 | test_page_url_.c_str(), mode.c_str()))); |
| 565 | EXPECT_EQ(base::StringPrintf("OnOpen%s", mode.c_str()), result); |
| 566 | return ExecuteScriptAndExtractString("reportRequests();"); |
| 567 | } |
| 568 | |
| 569 | private: |
| 570 | std::string test_page_url_; |
| 571 | |
| 572 | DISALLOW_COPY_AND_ASSIGN(ChromeServiceWorkerFetchPPAPITest); |
| 573 | }; |
| 574 | |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 575 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerFetchPPAPITest, |
Matt Falkenhagen | 7031e8b | 2018-02-20 03:30:33 | [diff] [blame] | 576 | NotInterceptedByServiceWorker) { |
| 577 | // Only the navigation to the iframe should be intercepted by the service |
| 578 | // worker. The request for the PNaCl manifest ("/pnacl_url_loader.nmf"), |
| 579 | // the request for the compiled code ("/pnacl_url_loader_newlib_pnacl.pexe"), |
| 580 | // and any other requests initiated by the plug-in ("/echo") should not be |
| 581 | // seen by the service worker. |
| 582 | const std::string fragment = |
| 583 | "NotIntercepted"; // this string is not important. |
| 584 | EXPECT_EQ(GetNavigationRequestString("#" + fragment), |
| 585 | ExecutePNACLUrlLoaderTest(fragment)); |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 586 | } |
Nico Weber | af3b00b | 2017-09-11 17:58:17 | [diff] [blame] | 587 | #endif // BUILDFLAG(ENABLE_NACL) |
horo | 61f3f4f | 2016-03-09 01:26:14 | [diff] [blame] | 588 | |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 589 | class ChromeServiceWorkerNavigationHintTest : public ChromeServiceWorkerTest { |
| 590 | protected: |
| 591 | void RunNavigationHintTest( |
| 592 | const char* scope, |
Tsuyoshi Horo | 6ddf281f | 2017-07-14 04:02:48 | [diff] [blame] | 593 | content::StartServiceWorkerForNavigationHintResult expected_result, |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 594 | bool expected_started) { |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 595 | base::RunLoop run_loop; |
| 596 | GetServiceWorkerContext()->StartServiceWorkerForNavigationHint( |
| 597 | embedded_test_server()->GetURL(scope), |
Matt Falkenhagen | da8af67 | 2017-09-12 02:39:23 | [diff] [blame] | 598 | base::BindOnce(&ExpectResultAndRun< |
| 599 | content::StartServiceWorkerForNavigationHintResult>, |
| 600 | expected_result, run_loop.QuitClosure())); |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 601 | run_loop.Run(); |
| 602 | if (expected_started) { |
Tsuyoshi Horo | 8290f13 | 2017-06-22 06:26:05 | [diff] [blame] | 603 | histogram_tester_.ExpectBucketCount( |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 604 | "ServiceWorker.StartWorker.Purpose", |
| 605 | 27 /* ServiceWorkerMetrics::EventType::NAVIGATION_HINT */, 1); |
Tsuyoshi Horo | 8290f13 | 2017-06-22 06:26:05 | [diff] [blame] | 606 | histogram_tester_.ExpectBucketCount( |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 607 | "ServiceWorker.StartWorker.StatusByPurpose_NAVIGATION_HINT", |
| 608 | 0 /* SERVICE_WORKER_OK */, 1); |
| 609 | } else { |
Tsuyoshi Horo | 8290f13 | 2017-06-22 06:26:05 | [diff] [blame] | 610 | histogram_tester_.ExpectTotalCount("ServiceWorker.StartWorker.Purpose", |
| 611 | 0); |
| 612 | histogram_tester_.ExpectTotalCount( |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 613 | "ServiceWorker.StartWorker.StatusByPurpose_NAVIGATION_HINT", 0); |
| 614 | } |
Tsuyoshi Horo | 6ddf281f | 2017-07-14 04:02:48 | [diff] [blame] | 615 | histogram_tester_.ExpectBucketCount( |
| 616 | "ServiceWorker.StartForNavigationHint.Result", |
| 617 | static_cast<int>(expected_result), 1); |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 618 | } |
Tsuyoshi Horo | 8290f13 | 2017-06-22 06:26:05 | [diff] [blame] | 619 | |
| 620 | base::HistogramTester histogram_tester_; |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 621 | }; |
| 622 | |
| 623 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerNavigationHintTest, Started) { |
| 624 | WriteFile(FILE_PATH_LITERAL("sw.js"), "self.onfetch = function(e) {};"); |
| 625 | WriteFile(FILE_PATH_LITERAL("test.html"), kInstallAndWaitForActivatedPage); |
| 626 | InitializeServer(); |
| 627 | NavigateToPageAndWaitForReadyTitle("/test.html"); |
| 628 | GetServiceWorkerContext()->StopAllServiceWorkersForOrigin( |
| 629 | embedded_test_server()->base_url()); |
| 630 | RunNavigationHintTest( |
| 631 | "/scope/", content::StartServiceWorkerForNavigationHintResult::STARTED, |
| 632 | true); |
| 633 | } |
| 634 | |
| 635 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerNavigationHintTest, AlreadyRunning) { |
| 636 | WriteFile(FILE_PATH_LITERAL("sw.js"), "self.onfetch = function(e) {};"); |
| 637 | WriteFile(FILE_PATH_LITERAL("test.html"), kInstallAndWaitForActivatedPage); |
| 638 | InitializeServer(); |
| 639 | NavigateToPageAndWaitForReadyTitle("/test.html"); |
| 640 | RunNavigationHintTest( |
| 641 | "/scope/", |
| 642 | content::StartServiceWorkerForNavigationHintResult::ALREADY_RUNNING, |
| 643 | false); |
| 644 | } |
| 645 | |
| 646 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerNavigationHintTest, |
| 647 | NoServiceWorkerRegistration) { |
| 648 | InitializeServer(); |
| 649 | RunNavigationHintTest("/scope/", |
| 650 | content::StartServiceWorkerForNavigationHintResult:: |
| 651 | NO_SERVICE_WORKER_REGISTRATION, |
| 652 | false); |
| 653 | } |
| 654 | |
| 655 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerNavigationHintTest, |
| 656 | NoActiveServiceWorkerVersion) { |
| 657 | WriteFile(FILE_PATH_LITERAL("sw.js"), |
| 658 | "self.oninstall = function(e) {\n" |
| 659 | " e.waitUntil(new Promise(r => { /* never resolve */ }));\n" |
| 660 | " };\n" |
| 661 | "self.onfetch = function(e) {};"); |
| 662 | InitializeServer(); |
| 663 | base::RunLoop run_loop; |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 664 | blink::mojom::ServiceWorkerRegistrationOptions options( |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 665 | embedded_test_server()->GetURL("/scope/"), |
Asami Doi | 5de8dea | 2018-09-13 10:01:07 | [diff] [blame] | 666 | blink::mojom::ScriptType::kClassic, |
Emma Haruka Iwao | bc30210 | 2017-12-05 02:33:08 | [diff] [blame] | 667 | blink::mojom::ServiceWorkerUpdateViaCache::kImports); |
| 668 | GetServiceWorkerContext()->RegisterServiceWorker( |
| 669 | embedded_test_server()->GetURL("/sw.js"), options, |
Tsuyoshi Horo | a1c6f54 | 2017-06-13 15:22:41 | [diff] [blame] | 670 | base::Bind(&ExpectResultAndRun<bool>, true, run_loop.QuitClosure())); |
| 671 | run_loop.Run(); |
| 672 | RunNavigationHintTest("/scope/", |
| 673 | content::StartServiceWorkerForNavigationHintResult:: |
| 674 | NO_ACTIVE_SERVICE_WORKER_VERSION, |
| 675 | false); |
| 676 | } |
| 677 | |
| 678 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerNavigationHintTest, NoFetchHandler) { |
| 679 | WriteFile(FILE_PATH_LITERAL("sw.js"), "/* empty */"); |
| 680 | WriteFile(FILE_PATH_LITERAL("test.html"), kInstallAndWaitForActivatedPage); |
| 681 | InitializeServer(); |
| 682 | NavigateToPageAndWaitForReadyTitle("/test.html"); |
| 683 | GetServiceWorkerContext()->StopAllServiceWorkersForOrigin( |
| 684 | embedded_test_server()->base_url()); |
| 685 | RunNavigationHintTest( |
| 686 | "/scope/", |
| 687 | content::StartServiceWorkerForNavigationHintResult::NO_FETCH_HANDLER, |
| 688 | false); |
| 689 | } |
| 690 | |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 691 | // Copied from devtools_sanity_browsertest.cc. |
| 692 | class StaticURLDataSource : public content::URLDataSource { |
| 693 | public: |
| 694 | StaticURLDataSource(const std::string& source, const std::string& content) |
| 695 | : source_(source), content_(content) {} |
| 696 | ~StaticURLDataSource() override = default; |
| 697 | |
| 698 | // content::URLDataSource: |
Lucas Furukawa Gadani | 4b4eed0 | 2019-06-04 23:12:04 | [diff] [blame] | 699 | std::string GetSource() override { return source_; } |
Wei-Yin Chen (陳威尹) | 39f4ff3 | 2019-10-22 17:59:09 | [diff] [blame] | 700 | void StartDataRequest(const GURL& url, |
John Abd-El-Malek | 92bf360 | 2019-07-31 02:25:48 | [diff] [blame] | 701 | const content::WebContents::Getter& wc_getter, |
danakj | f4b9e94 | 2019-11-29 15:43:04 | [diff] [blame] | 702 | GotDataCallback callback) override { |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 703 | std::string data(content_); |
danakj | f4b9e94 | 2019-11-29 15:43:04 | [diff] [blame] | 704 | std::move(callback).Run(base::RefCountedString::TakeString(&data)); |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 705 | } |
Lucas Furukawa Gadani | 4b4eed0 | 2019-06-04 23:12:04 | [diff] [blame] | 706 | std::string GetMimeType(const std::string& path) override { |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 707 | return "application/javascript"; |
| 708 | } |
Lucas Furukawa Gadani | 4b4eed0 | 2019-06-04 23:12:04 | [diff] [blame] | 709 | bool ShouldAddContentSecurityPolicy() override { return false; } |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 710 | |
| 711 | private: |
| 712 | const std::string source_; |
| 713 | const std::string content_; |
| 714 | |
| 715 | DISALLOW_COPY_AND_ASSIGN(StaticURLDataSource); |
| 716 | }; |
| 717 | |
| 718 | // Copied from devtools_sanity_browsertest.cc. |
| 719 | class MockWebUIProvider |
| 720 | : public TestChromeWebUIControllerFactory::WebUIProvider { |
| 721 | public: |
| 722 | MockWebUIProvider(const std::string& source, const std::string& content) |
| 723 | : source_(source), content_(content) {} |
| 724 | ~MockWebUIProvider() override = default; |
| 725 | |
| 726 | std::unique_ptr<content::WebUIController> NewWebUI(content::WebUI* web_ui, |
| 727 | const GURL& url) override { |
| 728 | content::URLDataSource::Add( |
| 729 | Profile::FromWebUI(web_ui), |
| 730 | std::make_unique<StaticURLDataSource>(source_, content_)); |
| 731 | return std::make_unique<content::WebUIController>(web_ui); |
| 732 | } |
| 733 | |
| 734 | private: |
| 735 | const std::string source_; |
| 736 | const std::string content_; |
| 737 | DISALLOW_COPY_AND_ASSIGN(MockWebUIProvider); |
| 738 | }; |
| 739 | |
| 740 | // Tests that registering a service worker with a chrome:// URL fails. |
| 741 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerTest, DisallowChromeScheme) { |
| 742 | const GURL kScript("chrome://dummyurl/sw.js"); |
| 743 | const GURL kScope("chrome://dummyurl"); |
| 744 | |
| 745 | // Make chrome://dummyurl/sw.js serve a service worker script. |
| 746 | TestChromeWebUIControllerFactory test_factory; |
| 747 | MockWebUIProvider mock_provider("serviceworker", "// empty service worker"); |
| 748 | test_factory.AddFactoryOverride(kScript.host(), &mock_provider); |
| 749 | content::WebUIControllerFactory::RegisterFactory(&test_factory); |
| 750 | |
| 751 | // Try to register the service worker. |
| 752 | base::RunLoop run_loop; |
| 753 | bool result = true; |
| 754 | blink::mojom::ServiceWorkerRegistrationOptions options( |
| 755 | kScope, blink::mojom::ScriptType::kClassic, |
| 756 | blink::mojom::ServiceWorkerUpdateViaCache::kImports); |
| 757 | GetServiceWorkerContext()->RegisterServiceWorker( |
| 758 | kScript, options, |
| 759 | base::BindOnce( |
| 760 | [](base::OnceClosure quit_closure, bool* out_result, bool result) { |
| 761 | *out_result = result; |
| 762 | std::move(quit_closure).Run(); |
| 763 | }, |
| 764 | run_loop.QuitClosure(), &result)); |
| 765 | run_loop.Run(); |
| 766 | |
| 767 | // Registration should fail. This is the desired behavior. At the time of this |
| 768 | // writing, there are a few reasons the registration fails: |
| 769 | // * OriginCanAccessServiceWorkers() returns false for the "chrome" scheme. |
| 770 | // * Even if that returned true, the URL loader factory bundle used to make |
| 771 | // the resource request in ServiceWorkerNewScriptLoader doesn't support |
| 772 | // the "chrome" scheme. This is because: |
| 773 | // * The call to RegisterNonNetworkSubresourceURLLoaderFactories() from |
| 774 | // CreateFactoryBundle() in embedded_worker_instance.cc doesn't register |
| 775 | // the "chrome" scheme, because there is no frame/web_contents. |
| 776 | // * Even if that registered a factory, CreateFactoryBundle() would |
| 777 | // skip it because GetServiceWorkerSchemes() doesn't include "chrome". |
| 778 | // |
| 779 | // It's difficult to change all these, so the test author hasn't actually |
| 780 | // changed Chrome in a way that makes this test fail, to prove that the test |
| 781 | // would be effective at catching a regression. |
| 782 | EXPECT_FALSE(result); |
| 783 | } |
| 784 | |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 785 | enum class ServicifiedFeatures { kNone, kServiceWorker, kNetwork }; |
| 786 | |
| 787 | // A simple fixture used for navigation preload tests so far. The fixture |
| 788 | // stashes the HttpRequest to a certain URL, useful for inspecting the headers |
| 789 | // to see if it was a navigation preload request and if it contained cookies. |
| 790 | // |
| 791 | // This is in //chrome instead of //content since the tests exercise the |
| 792 | // kBlockThirdPartyCookies preference which is not a //content concept. |
Matt Falkenhagen | 4332b16 | 2019-03-04 08:58:52 | [diff] [blame] | 793 | class ChromeServiceWorkerNavigationPreloadTest : public InProcessBrowserTest { |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 794 | public: |
| 795 | ChromeServiceWorkerNavigationPreloadTest() = default; |
| 796 | |
| 797 | void SetUp() override { |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 798 | embedded_test_server()->RegisterRequestHandler(base::BindRepeating( |
| 799 | &ChromeServiceWorkerNavigationPreloadTest::HandleRequest, |
| 800 | base::Unretained(this))); |
| 801 | ASSERT_TRUE(embedded_test_server()->InitializeAndListen()); |
| 802 | |
| 803 | InProcessBrowserTest::SetUp(); |
| 804 | } |
| 805 | |
| 806 | void SetUpOnMainThread() override { |
| 807 | // Make all hosts resolve to 127.0.0.1 so the same embedded test server can |
| 808 | // be used for cross-origin URLs. |
| 809 | host_resolver()->AddRule("*", "127.0.0.1"); |
| 810 | |
| 811 | embedded_test_server()->StartAcceptingConnections(); |
| 812 | } |
| 813 | |
| 814 | std::unique_ptr<net::test_server::HttpResponse> HandleRequest( |
| 815 | const net::test_server::HttpRequest& request) { |
| 816 | // Intercept requests to the "test" endpoint. |
| 817 | GURL url = request.base_url; |
| 818 | url = url.Resolve(request.relative_url); |
| 819 | if (url.path() != "/service_worker/test") |
| 820 | return nullptr; |
| 821 | |
| 822 | // Stash the request for testing. We'd typically prefer to echo back the |
| 823 | // request and test the resulting page contents, but that becomes |
| 824 | // cumbersome if the test involves cross-origin frames. |
| 825 | EXPECT_FALSE(received_request_); |
| 826 | received_request_ = request; |
| 827 | |
| 828 | // Respond with OK. |
| 829 | std::unique_ptr<net::test_server::BasicHttpResponse> http_response( |
| 830 | new net::test_server::BasicHttpResponse()); |
| 831 | http_response->set_code(net::HTTP_OK); |
| 832 | http_response->set_content("OK"); |
| 833 | http_response->set_content_type("text/plain"); |
| 834 | return http_response; |
| 835 | } |
| 836 | |
| 837 | bool HasHeader(const net::test_server::HttpRequest& request, |
| 838 | const std::string& name) const { |
| 839 | return request.headers.find(name) != request.headers.end(); |
| 840 | } |
| 841 | |
| 842 | std::string GetHeader(const net::test_server::HttpRequest& request, |
| 843 | const std::string& name) const { |
| 844 | const auto& iter = request.headers.find(name); |
| 845 | EXPECT_TRUE(iter != request.headers.end()); |
| 846 | if (iter == request.headers.end()) |
| 847 | return std::string(); |
| 848 | return iter->second; |
| 849 | } |
| 850 | |
| 851 | bool has_received_request() const { return received_request_.has_value(); } |
| 852 | |
| 853 | const net::test_server::HttpRequest& received_request() const { |
| 854 | return *received_request_; |
| 855 | } |
| 856 | |
| 857 | private: |
| 858 | base::test::ScopedFeatureList scoped_feature_list_; |
| 859 | |
| 860 | // The request that hit the "test" endpoint. |
| 861 | base::Optional<net::test_server::HttpRequest> received_request_; |
| 862 | |
| 863 | DISALLOW_COPY_AND_ASSIGN(ChromeServiceWorkerNavigationPreloadTest); |
| 864 | }; |
| 865 | |
| 866 | // Tests navigation preload during a navigation in the top-level frame |
| 867 | // when third-party cookies are blocked. The navigation preload request |
| 868 | // should be sent with cookies as normal. Regression test for |
| 869 | // https://crbug.com/913220. |
Matt Falkenhagen | 4332b16 | 2019-03-04 08:58:52 | [diff] [blame] | 870 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerNavigationPreloadTest, |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 871 | TopFrameWithThirdPartyBlocking) { |
| 872 | // Enable third-party cookie blocking. |
| 873 | browser()->profile()->GetPrefs()->SetBoolean(prefs::kBlockThirdPartyCookies, |
| 874 | true); |
| 875 | |
| 876 | // Load a page that registers a service worker. |
| 877 | ui_test_utils::NavigateToURL( |
| 878 | browser(), embedded_test_server()->GetURL( |
| 879 | "/service_worker/create_service_worker.html")); |
| 880 | EXPECT_EQ("DONE", EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), |
| 881 | "register('navigation_preload_worker.js');")); |
| 882 | |
| 883 | // Also set cookies. |
| 884 | EXPECT_EQ("foo=bar", |
| 885 | EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), |
| 886 | "document.cookie = 'foo=bar'; document.cookie;")); |
| 887 | |
| 888 | // Load the test page. |
| 889 | ui_test_utils::NavigateToURL( |
| 890 | browser(), embedded_test_server()->GetURL("/service_worker/test")); |
| 891 | |
| 892 | // The navigation preload request should have occurred and included cookies. |
| 893 | ASSERT_TRUE(has_received_request()); |
| 894 | EXPECT_EQ("true", |
| 895 | GetHeader(received_request(), "Service-Worker-Navigation-Preload")); |
| 896 | EXPECT_EQ("foo=bar", GetHeader(received_request(), "Cookie")); |
| 897 | } |
| 898 | |
| 899 | // Tests navigation preload during a navigation in a third-party iframe |
| 900 | // when third-party cookies are blocked. This blocks service worker as well, |
| 901 | // so the navigation preload request should not be sent. And the navigation |
| 902 | // request should not include cookies. |
Matt Falkenhagen | 4332b16 | 2019-03-04 08:58:52 | [diff] [blame] | 903 | IN_PROC_BROWSER_TEST_F(ChromeServiceWorkerNavigationPreloadTest, |
Matt Falkenhagen | c0d0bac | 2018-12-18 08:31:08 | [diff] [blame] | 904 | SubFrameWithThirdPartyBlocking) { |
| 905 | // Enable third-party cookie blocking. |
| 906 | browser()->profile()->GetPrefs()->SetBoolean(prefs::kBlockThirdPartyCookies, |
| 907 | true); |
| 908 | |
| 909 | // Load a page that registers a service worker. |
| 910 | ui_test_utils::NavigateToURL( |
| 911 | browser(), embedded_test_server()->GetURL( |
| 912 | "/service_worker/create_service_worker.html")); |
| 913 | EXPECT_EQ("DONE", EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), |
| 914 | "register('navigation_preload_worker.js');")); |
| 915 | |
| 916 | // Also set cookies. |
| 917 | EXPECT_EQ("foo=bar", |
| 918 | EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), |
| 919 | "document.cookie = 'foo=bar'; document.cookie;")); |
| 920 | |
| 921 | // Generate a cross-origin URL. |
| 922 | GURL top_frame_url = embedded_test_server()->GetURL( |
| 923 | "/service_worker/page_with_third_party_iframe.html"); |
| 924 | GURL::Replacements replacements; |
| 925 | replacements.SetHostStr("cross-origin.example.com"); |
| 926 | top_frame_url = top_frame_url.ReplaceComponents(replacements); |
| 927 | |
| 928 | // Navigate to the page and embed a third-party iframe to the test |
| 929 | // page. |
| 930 | ui_test_utils::NavigateToURL(browser(), top_frame_url); |
| 931 | GURL iframe_url = embedded_test_server()->GetURL("/service_worker/test"); |
| 932 | EXPECT_EQ(true, EvalJs(browser()->tab_strip_model()->GetActiveWebContents(), |
| 933 | "addIframe('" + iframe_url.spec() + "');")); |
| 934 | |
| 935 | // The request should have been received. Because the navigation was for a |
| 936 | // third-party iframe with cookies blocked, the service worker should not have |
| 937 | // handled the request so navigation preload should not have occurred. |
| 938 | // Likewise, the cookies should not have been sent. |
| 939 | ASSERT_TRUE(has_received_request()); |
| 940 | EXPECT_FALSE( |
| 941 | HasHeader(received_request(), "Service-Worker-Navigation-Preload")); |
| 942 | EXPECT_FALSE(HasHeader(received_request(), "Cookie")); |
| 943 | } |
| 944 | |
Matt Falkenhagen | ea30604 | 2018-11-29 00:45:25 | [diff] [blame] | 945 | } // namespace chrome_service_worker_browser_test |