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(
45 BrowserThread::IO
, FROM_HERE
,
47 &net::URLRequestMockHTTPJob::AddUrlHandlers
, path
,
48 make_scoped_refptr(content::BrowserThread::GetBlockingPool())));
49 BrowserThread::PostTask(
50 BrowserThread::IO
, FROM_HERE
,
51 base::Bind(&net::URLRequestFailedJob::AddUrlHandler
));
54 void OnDownloadCreated(DownloadManager
* manager
,
55 DownloadItem
* item
) override
{
57 got_downloads_
= !!manager
->InProgressCount();
60 GURL
GetMockURL(const std::string
& file
) {
61 return net::URLRequestMockHTTPJob::GetMockUrl(
62 base::FilePath().AppendASCII(file
));
65 void CheckTitleTest(const GURL
& url
,
66 const std::string
& expected_title
) {
67 base::string16
expected_title16(ASCIIToUTF16(expected_title
));
68 TitleWatcher
title_watcher(shell()->web_contents(), expected_title16
);
69 NavigateToURL(shell(), url
);
70 EXPECT_EQ(expected_title16
, title_watcher
.WaitAndGetTitle());
73 bool GetPopupTitle(const GURL
& url
, base::string16
* title
) {
74 NavigateToURL(shell(), url
);
76 ShellAddedObserver new_shell_observer
;
78 // Create dynamic popup.
79 if (!ExecuteScript(shell()->web_contents(), "OpenPopup();"))
82 Shell
* new_shell
= new_shell_observer
.GetShell();
83 *title
= new_shell
->web_contents()->GetTitle();
87 std::string
GetCookies(const GURL
& url
) {
88 return content::GetCookies(
89 shell()->web_contents()->GetBrowserContext(), url
);
92 bool got_downloads() const { return got_downloads_
; }
98 // Test title for content created by javascript window.open().
99 // See http://crbug.com/5988
100 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, DynamicTitle1
) {
101 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
103 GURL
url(embedded_test_server()->GetURL("/dynamic1.html"));
104 base::string16 title
;
105 ASSERT_TRUE(GetPopupTitle(url
, &title
));
106 EXPECT_TRUE(base::StartsWith(title
, ASCIIToUTF16("My Popup Title"),
107 base::CompareCase::SENSITIVE
))
108 << "Actual title: " << title
;
111 // Test title for content created by javascript window.open().
112 // See http://crbug.com/5988
113 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, DynamicTitle2
) {
114 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
116 GURL
url(embedded_test_server()->GetURL("/dynamic2.html"));
117 base::string16 title
;
118 ASSERT_TRUE(GetPopupTitle(url
, &title
));
119 EXPECT_TRUE(base::StartsWith(title
, ASCIIToUTF16("My Dynamic Title"),
120 base::CompareCase::SENSITIVE
))
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 (!base::StartsWith(path
, request
.relative_url
,
272 base::CompareCase::SENSITIVE
))
273 return scoped_ptr
<net::test_server::HttpResponse
>();
275 scoped_ptr
<net::test_server::BasicHttpResponse
> http_response(
276 new net::test_server::BasicHttpResponse
);
277 http_response
->set_code(net::HTTP_NO_CONTENT
);
278 return http_response
.Pass();
283 // Tests that the unload handler is not run for 204 responses.
284 // If this flakes use http://crbug.com/80596.
285 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
286 CrossSiteNoUnloadOn204
) {
287 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
289 // Start with a URL that sets a cookie in its unload handler.
290 GURL url
= embedded_test_server()->GetURL("/onunload_cookie.html");
291 CheckTitleTest(url
, "set cookie on unload");
293 // Navigate to a cross-site URL that returns a 204 No Content response.
294 const char kNoContentPath
[] = "/nocontent";
295 embedded_test_server()->RegisterRequestHandler(
296 base::Bind(&NoContentResponseHandler
, kNoContentPath
));
297 NavigateToURL(shell(), embedded_test_server()->GetURL(kNoContentPath
));
299 // Check that the unload cookie was not set.
300 EXPECT_EQ("", GetCookies(url
));
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 #if defined(OS_MACOSX)
312 #define MAYBE_CrossSiteAfterCrash DISABLED_CrossSiteAfterCrash
314 #define MAYBE_CrossSiteAfterCrash CrossSiteAfterCrash
316 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
317 MAYBE_CrossSiteAfterCrash
) {
318 // Make sure we have a live process before trying to kill it.
319 NavigateToURL(shell(), GURL("about:blank"));
321 // Cause the renderer to crash.
322 RenderProcessHostWatcher
crash_observer(
323 shell()->web_contents(),
324 RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT
);
325 NavigateToURL(shell(), GURL(kChromeUICrashURL
));
326 // Wait for browser to notice the renderer crash.
327 crash_observer
.Wait();
329 // Navigate to a new cross-site page. The browser should not wait around for
330 // the old renderer's on{before}unload handlers to run.
331 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
332 "Content Sniffer Test 0");
335 // Tests that cross-site navigations work when the new page does not go through
336 // the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
337 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
338 CrossSiteNavigationNonBuffered
) {
339 // Start with an HTTP page.
340 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
341 "Content Sniffer Test 0");
343 // Now load a file:// page, which does not use the BufferedEventHandler.
344 // Make sure that the page loads and displays a title, and doesn't get stuck.
345 GURL url
= GetTestUrl("", "title2.html");
346 CheckTitleTest(url
, "Title Of Awesomeness");
349 // Flaky everywhere. http://crbug.com/130404
350 // Tests that a cross-site navigation to an error page (resulting in the link
351 // doctor page) still runs the onunload handler and can support navigations
352 // away from the link doctor page. (Bug 1235537)
353 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
354 DISABLED_CrossSiteNavigationErrorPage
) {
355 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
357 GURL
url(embedded_test_server()->GetURL("/onunload_cookie.html"));
358 CheckTitleTest(url
, "set cookie on unload");
360 // Navigate to a new cross-site URL that results in an error.
361 // TODO(creis): If this causes crashes or hangs, it might be for the same
362 // reason as ErrorPageTest::DNSError. See bug 1199491 and
363 // http://crbug.com/22877.
364 GURL failed_url
= net::URLRequestFailedJob::GetMockHttpUrl(
365 net::ERR_NAME_NOT_RESOLVED
);
366 NavigateToURL(shell(), failed_url
);
368 EXPECT_NE(ASCIIToUTF16("set cookie on unload"),
369 shell()->web_contents()->GetTitle());
371 // Check that the cookie was set, meaning that the onunload handler ran.
372 EXPECT_EQ("onunloadCookie=foo", GetCookies(url
));
374 // Check that renderer-initiated navigations still work. In a previous bug,
375 // the ResourceDispatcherHost would think that such navigations were
376 // cross-site, because we didn't clean up from the previous request. Since
377 // WebContentsImpl was in the NORMAL state, it would ignore the attempt to run
378 // the onunload handler, and the navigation would fail. We can't test by
379 // redirecting to javascript:window.location='someURL', since javascript:
380 // URLs are prohibited by policy from interacting with sensitive chrome
381 // pages of which the error page is one. Instead, use automation to kick
382 // off the navigation, and wait to see that the tab loads.
383 base::string16
expected_title16(ASCIIToUTF16("Title Of Awesomeness"));
384 TitleWatcher
title_watcher(shell()->web_contents(), expected_title16
);
387 GURL
test_url(embedded_test_server()->GetURL("/title2.html"));
388 std::string redirect_script
= "window.location='" +
389 test_url
.possibly_invalid_spec() + "';" +
390 "window.domAutomationController.send(true);";
391 EXPECT_TRUE(ExecuteScriptAndExtractBool(
392 shell()->web_contents(),
395 EXPECT_EQ(expected_title16
, title_watcher
.WaitAndGetTitle());
398 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
399 CrossSiteNavigationErrorPage2
) {
400 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
402 GURL
url(embedded_test_server()->GetURL("/title2.html"));
403 CheckTitleTest(url
, "Title Of Awesomeness");
405 // Navigate to a new cross-site URL that results in an error.
406 // TODO(creis): If this causes crashes or hangs, it might be for the same
407 // reason as ErrorPageTest::DNSError. See bug 1199491 and
408 // http://crbug.com/22877.
409 GURL failed_url
= net::URLRequestFailedJob::GetMockHttpUrl(
410 net::ERR_NAME_NOT_RESOLVED
);
412 NavigateToURL(shell(), failed_url
);
413 EXPECT_NE(ASCIIToUTF16("Title Of Awesomeness"),
414 shell()->web_contents()->GetTitle());
416 // Repeat navigation. We are testing that this completes.
417 NavigateToURL(shell(), failed_url
);
418 EXPECT_NE(ASCIIToUTF16("Title Of Awesomeness"),
419 shell()->web_contents()->GetTitle());
422 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
423 CrossOriginRedirectBlocked
) {
424 // We expect the following URL requests from this test:
425 // 1- http://mock.http/cross-origin-redirect-blocked.html
426 // 2- http://mock.http/redirect-to-title2.html
427 // 3- http://mock.http/title2.html
429 // If the redirect in #2 were not blocked, we'd also see a request
430 // for http://mock.http:4000/title2.html, and the title would be different.
431 CheckTitleTest(GetMockURL("cross-origin-redirect-blocked.html"),
432 "Title Of More Awesomeness");
435 // Tests that ResourceRequestInfoImpl is updated correctly on failed
436 // requests, to prevent calling Read on a request that has already failed.
438 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
439 CrossSiteFailedRequest
) {
440 // Visit another URL first to trigger a cross-site navigation.
441 NavigateToURL(shell(), GetTestUrl("", "simple_page.html"));
443 // Visit a URL that fails without calling ResourceDispatcherHost::Read.
444 GURL
broken_url("chrome://theme");
445 NavigateToURL(shell(), broken_url
);
450 scoped_ptr
<net::test_server::HttpResponse
> HandleRedirectRequest(
451 const std::string
& request_path
,
452 const net::test_server::HttpRequest
& request
) {
453 if (!base::StartsWith(request
.relative_url
, request_path
,
454 base::CompareCase::SENSITIVE
))
455 return scoped_ptr
<net::test_server::HttpResponse
>();
457 scoped_ptr
<net::test_server::BasicHttpResponse
> http_response(
458 new net::test_server::BasicHttpResponse
);
459 http_response
->set_code(net::HTTP_FOUND
);
460 http_response
->AddCustomHeader(
461 "Location", request
.relative_url
.substr(request_path
.length()));
462 return http_response
.Pass();
467 // Test that we update the cookie policy URLs correctly when transferring
469 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, CookiePolicy
) {
470 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
471 embedded_test_server()->RegisterRequestHandler(
472 base::Bind(&HandleRedirectRequest
, "/redirect?"));
474 std::string
set_cookie_url(base::StringPrintf(
475 "http://localhost:%u/set_cookie.html", embedded_test_server()->port()));
476 GURL
url(embedded_test_server()->GetURL("/redirect?" + set_cookie_url
));
478 ShellContentBrowserClient::SetSwapProcessesForRedirect(true);
479 ShellNetworkDelegate::SetAcceptAllCookies(false);
481 CheckTitleTest(url
, "cookie set");
484 class PageTransitionResourceDispatcherHostDelegate
485 : public ResourceDispatcherHostDelegate
{
487 PageTransitionResourceDispatcherHostDelegate(GURL watch_url
)
488 : watch_url_(watch_url
) {}
490 // ResourceDispatcherHostDelegate implementation:
491 void RequestBeginning(net::URLRequest
* request
,
492 ResourceContext
* resource_context
,
493 AppCacheService
* appcache_service
,
494 ResourceType resource_type
,
495 ScopedVector
<ResourceThrottle
>* throttles
) override
{
496 if (request
->url() == watch_url_
) {
497 const ResourceRequestInfo
* info
=
498 ResourceRequestInfo::ForRequest(request
);
499 page_transition_
= info
->GetPageTransition();
503 ui::PageTransition
page_transition() { return page_transition_
; }
507 ui::PageTransition page_transition_
;
510 // Test that ui::PAGE_TRANSITION_CLIENT_REDIRECT is correctly set
511 // when encountering a meta refresh tag.
512 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
513 PageTransitionClientRedirect
) {
514 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
516 PageTransitionResourceDispatcherHostDelegate
delegate(
517 embedded_test_server()->GetURL("/title1.html"));
518 ResourceDispatcherHost::Get()->SetDelegate(&delegate
);
520 NavigateToURLBlockUntilNavigationsComplete(
522 embedded_test_server()->GetURL("/client_redirect.html"),
526 delegate
.page_transition() & ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
529 } // namespace content