1 // Copyright (c) 2012 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.
5 #include "base/memory/ref_counted.h"
6 #include "base/strings/string_util.h"
7 #include "base/strings/stringprintf.h"
8 #include "base/strings/utf_string_conversions.h"
9 #include "content/browser/download/download_manager_impl.h"
10 #include "content/browser/web_contents/web_contents_impl.h"
11 #include "content/public/browser/browser_context.h"
12 #include "content/public/browser/browser_thread.h"
13 #include "content/public/browser/resource_dispatcher_host.h"
14 #include "content/public/browser/resource_dispatcher_host_delegate.h"
15 #include "content/public/browser/resource_request_info.h"
16 #include "content/public/browser/web_contents.h"
17 #include "content/public/common/url_constants.h"
18 #include "content/public/test/browser_test_utils.h"
19 #include "content/public/test/content_browser_test.h"
20 #include "content/public/test/content_browser_test_utils.h"
21 #include "content/public/test/test_utils.h"
22 #include "content/shell/browser/shell.h"
23 #include "content/shell/browser/shell_content_browser_client.h"
24 #include "content/shell/browser/shell_network_delegate.h"
25 #include "net/base/net_errors.h"
26 #include "net/test/embedded_test_server/embedded_test_server.h"
27 #include "net/test/embedded_test_server/http_request.h"
28 #include "net/test/embedded_test_server/http_response.h"
29 #include "net/test/url_request/url_request_failed_job.h"
30 #include "net/test/url_request/url_request_mock_http_job.h"
32 using base::ASCIIToUTF16
;
36 class ResourceDispatcherHostBrowserTest
: public ContentBrowserTest
,
37 public DownloadManager::Observer
{
39 ResourceDispatcherHostBrowserTest() : got_downloads_(false) {}
42 void SetUpOnMainThread() override
{
43 base::FilePath path
= GetTestFilePath("", "");
44 BrowserThread::PostTask(
48 &net::URLRequestMockHTTPJob::AddUrlHandler
,
50 make_scoped_refptr(content::BrowserThread::GetBlockingPool())));
51 BrowserThread::PostTask(
52 BrowserThread::IO
, FROM_HERE
,
53 base::Bind(&net::URLRequestFailedJob::AddUrlHandler
));
56 void OnDownloadCreated(DownloadManager
* manager
,
57 DownloadItem
* item
) override
{
59 got_downloads_
= !!manager
->InProgressCount();
62 GURL
GetMockURL(const std::string
& file
) {
63 return net::URLRequestMockHTTPJob::GetMockUrl(
64 base::FilePath().AppendASCII(file
));
67 void CheckTitleTest(const GURL
& url
,
68 const std::string
& expected_title
) {
69 base::string16
expected_title16(ASCIIToUTF16(expected_title
));
70 TitleWatcher
title_watcher(shell()->web_contents(), expected_title16
);
71 NavigateToURL(shell(), url
);
72 EXPECT_EQ(expected_title16
, title_watcher
.WaitAndGetTitle());
75 bool GetPopupTitle(const GURL
& url
, base::string16
* title
) {
76 NavigateToURL(shell(), url
);
78 ShellAddedObserver new_shell_observer
;
80 // Create dynamic popup.
81 if (!ExecuteScript(shell()->web_contents(), "OpenPopup();"))
84 Shell
* new_shell
= new_shell_observer
.GetShell();
85 *title
= new_shell
->web_contents()->GetTitle();
89 std::string
GetCookies(const GURL
& url
) {
90 return content::GetCookies(
91 shell()->web_contents()->GetBrowserContext(), url
);
94 bool got_downloads() const { return got_downloads_
; }
100 // Test title for content created by javascript window.open().
101 // See http://crbug.com/5988
102 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, DynamicTitle1
) {
103 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
105 GURL
url(embedded_test_server()->GetURL("/dynamic1.html"));
106 base::string16 title
;
107 ASSERT_TRUE(GetPopupTitle(url
, &title
));
108 EXPECT_TRUE(StartsWith(title
, ASCIIToUTF16("My Popup Title"), true))
109 << "Actual title: " << title
;
112 // Test title for content created by javascript window.open().
113 // See http://crbug.com/5988
114 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, DynamicTitle2
) {
115 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
117 GURL
url(embedded_test_server()->GetURL("/dynamic2.html"));
118 base::string16 title
;
119 ASSERT_TRUE(GetPopupTitle(url
, &title
));
120 EXPECT_TRUE(StartsWith(title
, ASCIIToUTF16("My Dynamic Title"), true))
121 << "Actual title: " << title
;
124 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
125 SniffHTMLWithNoContentType
) {
126 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
127 "Content Sniffer Test 0");
130 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
131 RespectNoSniffDirective
) {
132 CheckTitleTest(GetMockURL("nosniff-test.html"),
133 "mock.http/nosniff-test.html");
136 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
137 DoNotSniffHTMLFromTextPlain
) {
138 CheckTitleTest(GetMockURL("content-sniffer-test1.html"),
139 "mock.http/content-sniffer-test1.html");
142 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
143 DoNotSniffHTMLFromImageGIF
) {
144 CheckTitleTest(GetMockURL("content-sniffer-test2.html"),
145 "mock.http/content-sniffer-test2.html");
148 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
149 SniffNoContentTypeNoData
) {
150 // Make sure no downloads start.
151 BrowserContext::GetDownloadManager(
152 shell()->web_contents()->GetBrowserContext())->AddObserver(this);
153 CheckTitleTest(GetMockURL("content-sniffer-test3.html"),
154 "Content Sniffer Test 3");
155 EXPECT_EQ(1u, Shell::windows().size());
156 ASSERT_FALSE(got_downloads());
159 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
160 ContentDispositionEmpty
) {
161 CheckTitleTest(GetMockURL("content-disposition-empty.html"), "success");
164 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
165 ContentDispositionInline
) {
166 CheckTitleTest(GetMockURL("content-disposition-inline.html"), "success");
169 // Test for bug #1091358.
170 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, SyncXMLHttpRequest
) {
171 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
173 shell(), embedded_test_server()->GetURL("/sync_xmlhttprequest.html"));
175 // Let's check the XMLHttpRequest ran successfully.
176 bool success
= false;
177 EXPECT_TRUE(ExecuteScriptAndExtractBool(
178 shell()->web_contents(),
179 "window.domAutomationController.send(DidSyncRequestSucceed());",
181 EXPECT_TRUE(success
);
184 // If this flakes, use http://crbug.com/62776.
185 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
186 SyncXMLHttpRequest_Disallowed
) {
187 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
190 embedded_test_server()->GetURL("/sync_xmlhttprequest_disallowed.html"));
192 // Let's check the XMLHttpRequest ran successfully.
193 bool success
= false;
194 EXPECT_TRUE(ExecuteScriptAndExtractBool(
195 shell()->web_contents(),
196 "window.domAutomationController.send(DidSucceed());",
198 EXPECT_TRUE(success
);
201 // Test for bug #1159553 -- A synchronous xhr (whose content-type is
202 // downloadable) would trigger download and hang the renderer process,
203 // if executed while navigating to a new page.
204 // Disabled on Mac: see http://crbug.com/56264
205 #if defined(OS_MACOSX)
206 #define MAYBE_SyncXMLHttpRequest_DuringUnload \
207 DISABLED_SyncXMLHttpRequest_DuringUnload
209 #define MAYBE_SyncXMLHttpRequest_DuringUnload SyncXMLHttpRequest_DuringUnload
211 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
212 MAYBE_SyncXMLHttpRequest_DuringUnload
) {
213 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
214 BrowserContext::GetDownloadManager(
215 shell()->web_contents()->GetBrowserContext())->AddObserver(this);
218 embedded_test_server()->GetURL("/sync_xmlhttprequest_during_unload.html"),
219 "sync xhr on unload");
221 // Navigate to a new page, to dispatch unload event and trigger xhr.
222 // (the bug would make this step hang the renderer).
224 embedded_test_server()->GetURL("/title2.html"), "Title Of Awesomeness");
226 ASSERT_FALSE(got_downloads());
229 // Flaky everywhere. http://crbug.com/130404
230 // Tests that onunload is run for cross-site requests. (Bug 1114994)
231 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
232 DISABLED_CrossSiteOnunloadCookie
) {
233 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
235 GURL url
= embedded_test_server()->GetURL("/onunload_cookie.html");
236 CheckTitleTest(url
, "set cookie on unload");
238 // Navigate to a new cross-site page, to dispatch unload event and set the
240 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
241 "Content Sniffer Test 0");
243 // Check that the cookie was set.
244 EXPECT_EQ("onunloadCookie=foo", GetCookies(url
));
247 // If this flakes, use http://crbug.com/130404
248 // Tests that onunload is run for cross-site requests to URLs that complete
249 // without network loads (e.g., about:blank, data URLs).
250 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
251 DISABLED_CrossSiteImmediateLoadOnunloadCookie
) {
252 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
254 GURL url
= embedded_test_server()->GetURL("/onunload_cookie.html");
255 CheckTitleTest(url
, "set cookie on unload");
257 // Navigate to a cross-site page that loads immediately without making a
258 // network request. The unload event should still be run.
259 NavigateToURL(shell(), GURL(url::kAboutBlankURL
));
261 // Check that the cookie was set.
262 EXPECT_EQ("onunloadCookie=foo", GetCookies(url
));
267 // Handles |request| by serving a redirect response.
268 scoped_ptr
<net::test_server::HttpResponse
> NoContentResponseHandler(
269 const std::string
& path
,
270 const net::test_server::HttpRequest
& request
) {
271 if (!StartsWithASCII(path
, request
.relative_url
, true))
272 return scoped_ptr
<net::test_server::HttpResponse
>();
274 scoped_ptr
<net::test_server::BasicHttpResponse
> http_response(
275 new net::test_server::BasicHttpResponse
);
276 http_response
->set_code(net::HTTP_NO_CONTENT
);
277 return http_response
.Pass();
282 // Tests that the unload handler is not run for 204 responses.
283 // If this flakes use http://crbug.com/80596.
284 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
285 CrossSiteNoUnloadOn204
) {
286 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
288 // Start with a URL that sets a cookie in its unload handler.
289 GURL url
= embedded_test_server()->GetURL("/onunload_cookie.html");
290 CheckTitleTest(url
, "set cookie on unload");
292 // Navigate to a cross-site URL that returns a 204 No Content response.
293 const char kNoContentPath
[] = "/nocontent";
294 embedded_test_server()->RegisterRequestHandler(
295 base::Bind(&NoContentResponseHandler
, kNoContentPath
));
296 NavigateToURL(shell(), embedded_test_server()->GetURL(kNoContentPath
));
298 // Check that the unload cookie was not set.
299 EXPECT_EQ("", GetCookies(url
));
302 #if !defined(OS_MACOSX)
303 // Tests that the onbeforeunload and onunload logic is short-circuited if the
304 // old renderer is gone. In that case, we don't want to wait for the old
305 // renderer to run the handlers.
306 // We need to disable this on Mac because the crash causes the OS CrashReporter
307 // process to kick in to analyze the poor dead renderer. Unfortunately, if the
308 // app isn't stripped of debug symbols, this takes about five minutes to
309 // complete and isn't conducive to quick turnarounds. As we don't currently
310 // strip the app on the build bots, this is bad times.
311 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, CrossSiteAfterCrash
) {
312 // Make sure we have a live process before trying to kill it.
313 NavigateToURL(shell(), GURL("about:blank"));
315 // Cause the renderer to crash.
316 RenderProcessHostWatcher
crash_observer(
317 shell()->web_contents(),
318 RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT
);
319 NavigateToURL(shell(), GURL(kChromeUICrashURL
));
320 // Wait for browser to notice the renderer crash.
321 crash_observer
.Wait();
323 // Navigate to a new cross-site page. The browser should not wait around for
324 // the old renderer's on{before}unload handlers to run.
325 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
326 "Content Sniffer Test 0");
328 #endif // !defined(OS_MACOSX)
330 // Tests that cross-site navigations work when the new page does not go through
331 // the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
332 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
333 CrossSiteNavigationNonBuffered
) {
334 // Start with an HTTP page.
335 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
336 "Content Sniffer Test 0");
338 // Now load a file:// page, which does not use the BufferedEventHandler.
339 // Make sure that the page loads and displays a title, and doesn't get stuck.
340 GURL url
= GetTestUrl("", "title2.html");
341 CheckTitleTest(url
, "Title Of Awesomeness");
344 // Flaky everywhere. http://crbug.com/130404
345 // Tests that a cross-site navigation to an error page (resulting in the link
346 // doctor page) still runs the onunload handler and can support navigations
347 // away from the link doctor page. (Bug 1235537)
348 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
349 DISABLED_CrossSiteNavigationErrorPage
) {
350 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
352 GURL
url(embedded_test_server()->GetURL("/onunload_cookie.html"));
353 CheckTitleTest(url
, "set cookie on unload");
355 // Navigate to a new cross-site URL that results in an error.
356 // TODO(creis): If this causes crashes or hangs, it might be for the same
357 // reason as ErrorPageTest::DNSError. See bug 1199491 and
358 // http://crbug.com/22877.
359 GURL failed_url
= net::URLRequestFailedJob::GetMockHttpUrl(
360 net::ERR_NAME_NOT_RESOLVED
);
361 NavigateToURL(shell(), failed_url
);
363 EXPECT_NE(ASCIIToUTF16("set cookie on unload"),
364 shell()->web_contents()->GetTitle());
366 // Check that the cookie was set, meaning that the onunload handler ran.
367 EXPECT_EQ("onunloadCookie=foo", GetCookies(url
));
369 // Check that renderer-initiated navigations still work. In a previous bug,
370 // the ResourceDispatcherHost would think that such navigations were
371 // cross-site, because we didn't clean up from the previous request. Since
372 // WebContentsImpl was in the NORMAL state, it would ignore the attempt to run
373 // the onunload handler, and the navigation would fail. We can't test by
374 // redirecting to javascript:window.location='someURL', since javascript:
375 // URLs are prohibited by policy from interacting with sensitive chrome
376 // pages of which the error page is one. Instead, use automation to kick
377 // off the navigation, and wait to see that the tab loads.
378 base::string16
expected_title16(ASCIIToUTF16("Title Of Awesomeness"));
379 TitleWatcher
title_watcher(shell()->web_contents(), expected_title16
);
382 GURL
test_url(embedded_test_server()->GetURL("/title2.html"));
383 std::string redirect_script
= "window.location='" +
384 test_url
.possibly_invalid_spec() + "';" +
385 "window.domAutomationController.send(true);";
386 EXPECT_TRUE(ExecuteScriptAndExtractBool(
387 shell()->web_contents(),
390 EXPECT_EQ(expected_title16
, title_watcher
.WaitAndGetTitle());
393 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
394 CrossSiteNavigationErrorPage2
) {
395 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
397 GURL
url(embedded_test_server()->GetURL("/title2.html"));
398 CheckTitleTest(url
, "Title Of Awesomeness");
400 // Navigate to a new cross-site URL that results in an error.
401 // TODO(creis): If this causes crashes or hangs, it might be for the same
402 // reason as ErrorPageTest::DNSError. See bug 1199491 and
403 // http://crbug.com/22877.
404 GURL failed_url
= net::URLRequestFailedJob::GetMockHttpUrl(
405 net::ERR_NAME_NOT_RESOLVED
);
407 NavigateToURL(shell(), failed_url
);
408 EXPECT_NE(ASCIIToUTF16("Title Of Awesomeness"),
409 shell()->web_contents()->GetTitle());
411 // Repeat navigation. We are testing that this completes.
412 NavigateToURL(shell(), failed_url
);
413 EXPECT_NE(ASCIIToUTF16("Title Of Awesomeness"),
414 shell()->web_contents()->GetTitle());
417 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
418 CrossOriginRedirectBlocked
) {
419 // We expect the following URL requests from this test:
420 // 1- http://mock.http/cross-origin-redirect-blocked.html
421 // 2- http://mock.http/redirect-to-title2.html
422 // 3- http://mock.http/title2.html
424 // If the redirect in #2 were not blocked, we'd also see a request
425 // for http://mock.http:4000/title2.html, and the title would be different.
426 CheckTitleTest(GetMockURL("cross-origin-redirect-blocked.html"),
427 "Title Of More Awesomeness");
430 // Tests that ResourceRequestInfoImpl is updated correctly on failed
431 // requests, to prevent calling Read on a request that has already failed.
433 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
434 CrossSiteFailedRequest
) {
435 // Visit another URL first to trigger a cross-site navigation.
436 NavigateToURL(shell(), GetTestUrl("", "simple_page.html"));
438 // Visit a URL that fails without calling ResourceDispatcherHost::Read.
439 GURL
broken_url("chrome://theme");
440 NavigateToURL(shell(), broken_url
);
445 scoped_ptr
<net::test_server::HttpResponse
> HandleRedirectRequest(
446 const std::string
& request_path
,
447 const net::test_server::HttpRequest
& request
) {
448 if (!StartsWithASCII(request
.relative_url
, request_path
, true))
449 return scoped_ptr
<net::test_server::HttpResponse
>();
451 scoped_ptr
<net::test_server::BasicHttpResponse
> http_response(
452 new net::test_server::BasicHttpResponse
);
453 http_response
->set_code(net::HTTP_FOUND
);
454 http_response
->AddCustomHeader(
455 "Location", request
.relative_url
.substr(request_path
.length()));
456 return http_response
.Pass();
461 // Test that we update the cookie policy URLs correctly when transferring
463 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, CookiePolicy
) {
464 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
465 embedded_test_server()->RegisterRequestHandler(
466 base::Bind(&HandleRedirectRequest
, "/redirect?"));
468 std::string
set_cookie_url(base::StringPrintf(
469 "http://localhost:%u/set_cookie.html", embedded_test_server()->port()));
470 GURL
url(embedded_test_server()->GetURL("/redirect?" + set_cookie_url
));
472 ShellContentBrowserClient::SetSwapProcessesForRedirect(true);
473 ShellNetworkDelegate::SetAcceptAllCookies(false);
475 CheckTitleTest(url
, "cookie set");
478 class PageTransitionResourceDispatcherHostDelegate
479 : public ResourceDispatcherHostDelegate
{
481 PageTransitionResourceDispatcherHostDelegate(GURL watch_url
)
482 : watch_url_(watch_url
) {}
484 // ResourceDispatcherHostDelegate implementation:
485 void RequestBeginning(net::URLRequest
* request
,
486 ResourceContext
* resource_context
,
487 AppCacheService
* appcache_service
,
488 ResourceType resource_type
,
489 ScopedVector
<ResourceThrottle
>* throttles
) override
{
490 if (request
->url() == watch_url_
) {
491 const ResourceRequestInfo
* info
=
492 ResourceRequestInfo::ForRequest(request
);
493 page_transition_
= info
->GetPageTransition();
497 ui::PageTransition
page_transition() { return page_transition_
; }
501 ui::PageTransition page_transition_
;
504 // Test that ui::PAGE_TRANSITION_CLIENT_REDIRECT is correctly set
505 // when encountering a meta refresh tag.
506 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
507 PageTransitionClientRedirect
) {
508 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
510 PageTransitionResourceDispatcherHostDelegate
delegate(
511 embedded_test_server()->GetURL("/title1.html"));
512 ResourceDispatcherHost::Get()->SetDelegate(&delegate
);
514 NavigateToURLBlockUntilNavigationsComplete(
516 embedded_test_server()->GetURL("/client_redirect.html"),
520 delegate
.page_transition() & ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
523 } // namespace content