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(StartsWith(title
, ASCIIToUTF16("My Popup Title"), true))
107 << "Actual title: " << title
;
110 // Test title for content created by javascript window.open().
111 // See http://crbug.com/5988
112 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, DynamicTitle2
) {
113 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
115 GURL
url(embedded_test_server()->GetURL("/dynamic2.html"));
116 base::string16 title
;
117 ASSERT_TRUE(GetPopupTitle(url
, &title
));
118 EXPECT_TRUE(StartsWith(title
, ASCIIToUTF16("My Dynamic Title"), true))
119 << "Actual title: " << title
;
122 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
123 SniffHTMLWithNoContentType
) {
124 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
125 "Content Sniffer Test 0");
128 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
129 RespectNoSniffDirective
) {
130 CheckTitleTest(GetMockURL("nosniff-test.html"),
131 "mock.http/nosniff-test.html");
134 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
135 DoNotSniffHTMLFromTextPlain
) {
136 CheckTitleTest(GetMockURL("content-sniffer-test1.html"),
137 "mock.http/content-sniffer-test1.html");
140 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
141 DoNotSniffHTMLFromImageGIF
) {
142 CheckTitleTest(GetMockURL("content-sniffer-test2.html"),
143 "mock.http/content-sniffer-test2.html");
146 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
147 SniffNoContentTypeNoData
) {
148 // Make sure no downloads start.
149 BrowserContext::GetDownloadManager(
150 shell()->web_contents()->GetBrowserContext())->AddObserver(this);
151 CheckTitleTest(GetMockURL("content-sniffer-test3.html"),
152 "Content Sniffer Test 3");
153 EXPECT_EQ(1u, Shell::windows().size());
154 ASSERT_FALSE(got_downloads());
157 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
158 ContentDispositionEmpty
) {
159 CheckTitleTest(GetMockURL("content-disposition-empty.html"), "success");
162 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
163 ContentDispositionInline
) {
164 CheckTitleTest(GetMockURL("content-disposition-inline.html"), "success");
167 // Test for bug #1091358.
168 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, SyncXMLHttpRequest
) {
169 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
171 shell(), embedded_test_server()->GetURL("/sync_xmlhttprequest.html"));
173 // Let's check the XMLHttpRequest ran successfully.
174 bool success
= false;
175 EXPECT_TRUE(ExecuteScriptAndExtractBool(
176 shell()->web_contents(),
177 "window.domAutomationController.send(DidSyncRequestSucceed());",
179 EXPECT_TRUE(success
);
182 // If this flakes, use http://crbug.com/62776.
183 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
184 SyncXMLHttpRequest_Disallowed
) {
185 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
188 embedded_test_server()->GetURL("/sync_xmlhttprequest_disallowed.html"));
190 // Let's check the XMLHttpRequest ran successfully.
191 bool success
= false;
192 EXPECT_TRUE(ExecuteScriptAndExtractBool(
193 shell()->web_contents(),
194 "window.domAutomationController.send(DidSucceed());",
196 EXPECT_TRUE(success
);
199 // Test for bug #1159553 -- A synchronous xhr (whose content-type is
200 // downloadable) would trigger download and hang the renderer process,
201 // if executed while navigating to a new page.
202 // Disabled on Mac: see http://crbug.com/56264
203 #if defined(OS_MACOSX)
204 #define MAYBE_SyncXMLHttpRequest_DuringUnload \
205 DISABLED_SyncXMLHttpRequest_DuringUnload
207 #define MAYBE_SyncXMLHttpRequest_DuringUnload SyncXMLHttpRequest_DuringUnload
209 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
210 MAYBE_SyncXMLHttpRequest_DuringUnload
) {
211 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
212 BrowserContext::GetDownloadManager(
213 shell()->web_contents()->GetBrowserContext())->AddObserver(this);
216 embedded_test_server()->GetURL("/sync_xmlhttprequest_during_unload.html"),
217 "sync xhr on unload");
219 // Navigate to a new page, to dispatch unload event and trigger xhr.
220 // (the bug would make this step hang the renderer).
222 embedded_test_server()->GetURL("/title2.html"), "Title Of Awesomeness");
224 ASSERT_FALSE(got_downloads());
227 // Flaky everywhere. http://crbug.com/130404
228 // Tests that onunload is run for cross-site requests. (Bug 1114994)
229 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
230 DISABLED_CrossSiteOnunloadCookie
) {
231 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
233 GURL url
= embedded_test_server()->GetURL("/onunload_cookie.html");
234 CheckTitleTest(url
, "set cookie on unload");
236 // Navigate to a new cross-site page, to dispatch unload event and set the
238 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
239 "Content Sniffer Test 0");
241 // Check that the cookie was set.
242 EXPECT_EQ("onunloadCookie=foo", GetCookies(url
));
245 // If this flakes, use http://crbug.com/130404
246 // Tests that onunload is run for cross-site requests to URLs that complete
247 // without network loads (e.g., about:blank, data URLs).
248 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
249 DISABLED_CrossSiteImmediateLoadOnunloadCookie
) {
250 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
252 GURL url
= embedded_test_server()->GetURL("/onunload_cookie.html");
253 CheckTitleTest(url
, "set cookie on unload");
255 // Navigate to a cross-site page that loads immediately without making a
256 // network request. The unload event should still be run.
257 NavigateToURL(shell(), GURL(url::kAboutBlankURL
));
259 // Check that the cookie was set.
260 EXPECT_EQ("onunloadCookie=foo", GetCookies(url
));
265 // Handles |request| by serving a redirect response.
266 scoped_ptr
<net::test_server::HttpResponse
> NoContentResponseHandler(
267 const std::string
& path
,
268 const net::test_server::HttpRequest
& request
) {
269 if (!StartsWithASCII(path
, request
.relative_url
, true))
270 return scoped_ptr
<net::test_server::HttpResponse
>();
272 scoped_ptr
<net::test_server::BasicHttpResponse
> http_response(
273 new net::test_server::BasicHttpResponse
);
274 http_response
->set_code(net::HTTP_NO_CONTENT
);
275 return http_response
.Pass();
280 // Tests that the unload handler is not run for 204 responses.
281 // If this flakes use http://crbug.com/80596.
282 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
283 CrossSiteNoUnloadOn204
) {
284 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
286 // Start with a URL that sets a cookie in its unload handler.
287 GURL url
= embedded_test_server()->GetURL("/onunload_cookie.html");
288 CheckTitleTest(url
, "set cookie on unload");
290 // Navigate to a cross-site URL that returns a 204 No Content response.
291 const char kNoContentPath
[] = "/nocontent";
292 embedded_test_server()->RegisterRequestHandler(
293 base::Bind(&NoContentResponseHandler
, kNoContentPath
));
294 NavigateToURL(shell(), embedded_test_server()->GetURL(kNoContentPath
));
296 // Check that the unload cookie was not set.
297 EXPECT_EQ("", GetCookies(url
));
300 #if !defined(OS_MACOSX)
301 // Tests that the onbeforeunload and onunload logic is short-circuited if the
302 // old renderer is gone. In that case, we don't want to wait for the old
303 // renderer to run the handlers.
304 // We need to disable this on Mac because the crash causes the OS CrashReporter
305 // process to kick in to analyze the poor dead renderer. Unfortunately, if the
306 // app isn't stripped of debug symbols, this takes about five minutes to
307 // complete and isn't conducive to quick turnarounds. As we don't currently
308 // strip the app on the build bots, this is bad times.
309 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, CrossSiteAfterCrash
) {
310 // Make sure we have a live process before trying to kill it.
311 NavigateToURL(shell(), GURL("about:blank"));
313 // Cause the renderer to crash.
314 RenderProcessHostWatcher
crash_observer(
315 shell()->web_contents(),
316 RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT
);
317 NavigateToURL(shell(), GURL(kChromeUICrashURL
));
318 // Wait for browser to notice the renderer crash.
319 crash_observer
.Wait();
321 // Navigate to a new cross-site page. The browser should not wait around for
322 // the old renderer's on{before}unload handlers to run.
323 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
324 "Content Sniffer Test 0");
326 #endif // !defined(OS_MACOSX)
328 // Tests that cross-site navigations work when the new page does not go through
329 // the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
330 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
331 CrossSiteNavigationNonBuffered
) {
332 // Start with an HTTP page.
333 CheckTitleTest(GetMockURL("content-sniffer-test0.html"),
334 "Content Sniffer Test 0");
336 // Now load a file:// page, which does not use the BufferedEventHandler.
337 // Make sure that the page loads and displays a title, and doesn't get stuck.
338 GURL url
= GetTestUrl("", "title2.html");
339 CheckTitleTest(url
, "Title Of Awesomeness");
342 // Flaky everywhere. http://crbug.com/130404
343 // Tests that a cross-site navigation to an error page (resulting in the link
344 // doctor page) still runs the onunload handler and can support navigations
345 // away from the link doctor page. (Bug 1235537)
346 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
347 DISABLED_CrossSiteNavigationErrorPage
) {
348 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
350 GURL
url(embedded_test_server()->GetURL("/onunload_cookie.html"));
351 CheckTitleTest(url
, "set cookie on unload");
353 // Navigate to a new cross-site URL that results in an error.
354 // TODO(creis): If this causes crashes or hangs, it might be for the same
355 // reason as ErrorPageTest::DNSError. See bug 1199491 and
356 // http://crbug.com/22877.
357 GURL failed_url
= net::URLRequestFailedJob::GetMockHttpUrl(
358 net::ERR_NAME_NOT_RESOLVED
);
359 NavigateToURL(shell(), failed_url
);
361 EXPECT_NE(ASCIIToUTF16("set cookie on unload"),
362 shell()->web_contents()->GetTitle());
364 // Check that the cookie was set, meaning that the onunload handler ran.
365 EXPECT_EQ("onunloadCookie=foo", GetCookies(url
));
367 // Check that renderer-initiated navigations still work. In a previous bug,
368 // the ResourceDispatcherHost would think that such navigations were
369 // cross-site, because we didn't clean up from the previous request. Since
370 // WebContentsImpl was in the NORMAL state, it would ignore the attempt to run
371 // the onunload handler, and the navigation would fail. We can't test by
372 // redirecting to javascript:window.location='someURL', since javascript:
373 // URLs are prohibited by policy from interacting with sensitive chrome
374 // pages of which the error page is one. Instead, use automation to kick
375 // off the navigation, and wait to see that the tab loads.
376 base::string16
expected_title16(ASCIIToUTF16("Title Of Awesomeness"));
377 TitleWatcher
title_watcher(shell()->web_contents(), expected_title16
);
380 GURL
test_url(embedded_test_server()->GetURL("/title2.html"));
381 std::string redirect_script
= "window.location='" +
382 test_url
.possibly_invalid_spec() + "';" +
383 "window.domAutomationController.send(true);";
384 EXPECT_TRUE(ExecuteScriptAndExtractBool(
385 shell()->web_contents(),
388 EXPECT_EQ(expected_title16
, title_watcher
.WaitAndGetTitle());
391 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
392 CrossSiteNavigationErrorPage2
) {
393 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
395 GURL
url(embedded_test_server()->GetURL("/title2.html"));
396 CheckTitleTest(url
, "Title Of Awesomeness");
398 // Navigate to a new cross-site URL that results in an error.
399 // TODO(creis): If this causes crashes or hangs, it might be for the same
400 // reason as ErrorPageTest::DNSError. See bug 1199491 and
401 // http://crbug.com/22877.
402 GURL failed_url
= net::URLRequestFailedJob::GetMockHttpUrl(
403 net::ERR_NAME_NOT_RESOLVED
);
405 NavigateToURL(shell(), failed_url
);
406 EXPECT_NE(ASCIIToUTF16("Title Of Awesomeness"),
407 shell()->web_contents()->GetTitle());
409 // Repeat navigation. We are testing that this completes.
410 NavigateToURL(shell(), failed_url
);
411 EXPECT_NE(ASCIIToUTF16("Title Of Awesomeness"),
412 shell()->web_contents()->GetTitle());
415 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
416 CrossOriginRedirectBlocked
) {
417 // We expect the following URL requests from this test:
418 // 1- http://mock.http/cross-origin-redirect-blocked.html
419 // 2- http://mock.http/redirect-to-title2.html
420 // 3- http://mock.http/title2.html
422 // If the redirect in #2 were not blocked, we'd also see a request
423 // for http://mock.http:4000/title2.html, and the title would be different.
424 CheckTitleTest(GetMockURL("cross-origin-redirect-blocked.html"),
425 "Title Of More Awesomeness");
428 // Tests that ResourceRequestInfoImpl is updated correctly on failed
429 // requests, to prevent calling Read on a request that has already failed.
431 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
432 CrossSiteFailedRequest
) {
433 // Visit another URL first to trigger a cross-site navigation.
434 NavigateToURL(shell(), GetTestUrl("", "simple_page.html"));
436 // Visit a URL that fails without calling ResourceDispatcherHost::Read.
437 GURL
broken_url("chrome://theme");
438 NavigateToURL(shell(), broken_url
);
443 scoped_ptr
<net::test_server::HttpResponse
> HandleRedirectRequest(
444 const std::string
& request_path
,
445 const net::test_server::HttpRequest
& request
) {
446 if (!StartsWithASCII(request
.relative_url
, request_path
, true))
447 return scoped_ptr
<net::test_server::HttpResponse
>();
449 scoped_ptr
<net::test_server::BasicHttpResponse
> http_response(
450 new net::test_server::BasicHttpResponse
);
451 http_response
->set_code(net::HTTP_FOUND
);
452 http_response
->AddCustomHeader(
453 "Location", request
.relative_url
.substr(request_path
.length()));
454 return http_response
.Pass();
459 // Test that we update the cookie policy URLs correctly when transferring
461 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
, CookiePolicy
) {
462 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
463 embedded_test_server()->RegisterRequestHandler(
464 base::Bind(&HandleRedirectRequest
, "/redirect?"));
466 std::string
set_cookie_url(base::StringPrintf(
467 "http://localhost:%u/set_cookie.html", embedded_test_server()->port()));
468 GURL
url(embedded_test_server()->GetURL("/redirect?" + set_cookie_url
));
470 ShellContentBrowserClient::SetSwapProcessesForRedirect(true);
471 ShellNetworkDelegate::SetAcceptAllCookies(false);
473 CheckTitleTest(url
, "cookie set");
476 class PageTransitionResourceDispatcherHostDelegate
477 : public ResourceDispatcherHostDelegate
{
479 PageTransitionResourceDispatcherHostDelegate(GURL watch_url
)
480 : watch_url_(watch_url
) {}
482 // ResourceDispatcherHostDelegate implementation:
483 void RequestBeginning(net::URLRequest
* request
,
484 ResourceContext
* resource_context
,
485 AppCacheService
* appcache_service
,
486 ResourceType resource_type
,
487 ScopedVector
<ResourceThrottle
>* throttles
) override
{
488 if (request
->url() == watch_url_
) {
489 const ResourceRequestInfo
* info
=
490 ResourceRequestInfo::ForRequest(request
);
491 page_transition_
= info
->GetPageTransition();
495 ui::PageTransition
page_transition() { return page_transition_
; }
499 ui::PageTransition page_transition_
;
502 // Test that ui::PAGE_TRANSITION_CLIENT_REDIRECT is correctly set
503 // when encountering a meta refresh tag.
504 IN_PROC_BROWSER_TEST_F(ResourceDispatcherHostBrowserTest
,
505 PageTransitionClientRedirect
) {
506 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
508 PageTransitionResourceDispatcherHostDelegate
delegate(
509 embedded_test_server()->GetURL("/title1.html"));
510 ResourceDispatcherHost::Get()->SetDelegate(&delegate
);
512 NavigateToURLBlockUntilNavigationsComplete(
514 embedded_test_server()->GetURL("/client_redirect.html"),
518 delegate
.page_transition() & ui::PAGE_TRANSITION_CLIENT_REDIRECT
);
521 } // namespace content