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 "build/build_config.h"
16 #include "base/basictypes.h"
17 #include "base/bind.h"
18 #include "base/compiler_specific.h"
19 #include "base/files/file_util.h"
20 #include "base/files/scoped_temp_dir.h"
21 #include "base/format_macros.h"
22 #include "base/memory/scoped_ptr.h"
23 #include "base/memory/weak_ptr.h"
24 #include "base/message_loop/message_loop.h"
25 #include "base/message_loop/message_loop_proxy.h"
26 #include "base/path_service.h"
27 #include "base/run_loop.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_piece.h"
30 #include "base/strings/string_split.h"
31 #include "base/strings/string_util.h"
32 #include "base/strings/stringprintf.h"
33 #include "base/strings/utf_string_conversions.h"
34 #include "base/test/histogram_tester.h"
35 #include "net/base/chunked_upload_data_stream.h"
36 #include "net/base/elements_upload_data_stream.h"
37 #include "net/base/load_flags.h"
38 #include "net/base/load_timing_info.h"
39 #include "net/base/load_timing_info_test_util.h"
40 #include "net/base/net_errors.h"
41 #include "net/base/net_module.h"
42 #include "net/base/net_util.h"
43 #include "net/base/network_quality.h"
44 #include "net/base/network_quality_estimator.h"
45 #include "net/base/request_priority.h"
46 #include "net/base/test_data_directory.h"
47 #include "net/base/upload_bytes_element_reader.h"
48 #include "net/base/upload_data_stream.h"
49 #include "net/base/upload_file_element_reader.h"
50 #include "net/cert/ev_root_ca_metadata.h"
51 #include "net/cert/mock_cert_verifier.h"
52 #include "net/cert/test_root_certs.h"
53 #include "net/cert_net/nss_ocsp.h"
54 #include "net/cookies/cookie_monster.h"
55 #include "net/cookies/cookie_store_test_helpers.h"
56 #include "net/disk_cache/disk_cache.h"
57 #include "net/dns/mock_host_resolver.h"
58 #include "net/ftp/ftp_network_layer.h"
59 #include "net/http/http_byte_range.h"
60 #include "net/http/http_cache.h"
61 #include "net/http/http_network_layer.h"
62 #include "net/http/http_network_session.h"
63 #include "net/http/http_request_headers.h"
64 #include "net/http/http_response_headers.h"
65 #include "net/http/http_util.h"
66 #include "net/log/net_log.h"
67 #include "net/log/test_net_log.h"
68 #include "net/log/test_net_log_entry.h"
69 #include "net/log/test_net_log_util.h"
70 #include "net/proxy/proxy_service.h"
71 #include "net/socket/ssl_client_socket.h"
72 #include "net/ssl/ssl_cipher_suite_names.h"
73 #include "net/ssl/ssl_connection_status_flags.h"
74 #include "net/test/cert_test_util.h"
75 #include "net/test/spawned_test_server/spawned_test_server.h"
76 #include "net/url_request/data_protocol_handler.h"
77 #include "net/url_request/static_http_user_agent_settings.h"
78 #include "net/url_request/url_request.h"
79 #include "net/url_request/url_request_http_job.h"
80 #include "net/url_request/url_request_intercepting_job_factory.h"
81 #include "net/url_request/url_request_interceptor.h"
82 #include "net/url_request/url_request_job_factory_impl.h"
83 #include "net/url_request/url_request_redirect_job.h"
84 #include "net/url_request/url_request_test_job.h"
85 #include "net/url_request/url_request_test_util.h"
86 #include "testing/gtest/include/gtest/gtest.h"
87 #include "testing/platform_test.h"
89 #if !defined(DISABLE_FILE_SUPPORT)
90 #include "net/base/filename_util.h"
91 #include "net/url_request/file_protocol_handler.h"
92 #include "net/url_request/url_request_file_dir_job.h"
95 #if !defined(DISABLE_FTP_SUPPORT)
96 #include "net/url_request/ftp_protocol_handler.h"
100 #include "base/win/scoped_com_initializer.h"
101 #include "base/win/scoped_comptr.h"
102 #include "base/win/windows_version.h"
105 using base::ASCIIToUTF16
;
113 const base::string16
kChrome(ASCIIToUTF16("chrome"));
114 const base::string16
kSecret(ASCIIToUTF16("secret"));
115 const base::string16
kUser(ASCIIToUTF16("user"));
117 // Tests load timing information in the case a fresh connection was used, with
119 void TestLoadTimingNotReused(const LoadTimingInfo
& load_timing_info
,
120 int connect_timing_flags
) {
121 EXPECT_FALSE(load_timing_info
.socket_reused
);
122 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
124 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
125 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
127 EXPECT_LE(load_timing_info
.request_start
,
128 load_timing_info
.connect_timing
.connect_start
);
129 ExpectConnectTimingHasTimes(load_timing_info
.connect_timing
,
130 connect_timing_flags
);
131 EXPECT_LE(load_timing_info
.connect_timing
.connect_end
,
132 load_timing_info
.send_start
);
133 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
134 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
136 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
137 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
140 // Same as above, but with proxy times.
141 void TestLoadTimingNotReusedWithProxy(
142 const LoadTimingInfo
& load_timing_info
,
143 int connect_timing_flags
) {
144 EXPECT_FALSE(load_timing_info
.socket_reused
);
145 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
147 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
148 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
150 EXPECT_LE(load_timing_info
.request_start
,
151 load_timing_info
.proxy_resolve_start
);
152 EXPECT_LE(load_timing_info
.proxy_resolve_start
,
153 load_timing_info
.proxy_resolve_end
);
154 EXPECT_LE(load_timing_info
.proxy_resolve_end
,
155 load_timing_info
.connect_timing
.connect_start
);
156 ExpectConnectTimingHasTimes(load_timing_info
.connect_timing
,
157 connect_timing_flags
);
158 EXPECT_LE(load_timing_info
.connect_timing
.connect_end
,
159 load_timing_info
.send_start
);
160 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
161 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
164 // Same as above, but with a reused socket and proxy times.
165 void TestLoadTimingReusedWithProxy(
166 const LoadTimingInfo
& load_timing_info
) {
167 EXPECT_TRUE(load_timing_info
.socket_reused
);
168 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
170 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
171 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
173 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
175 EXPECT_LE(load_timing_info
.request_start
,
176 load_timing_info
.proxy_resolve_start
);
177 EXPECT_LE(load_timing_info
.proxy_resolve_start
,
178 load_timing_info
.proxy_resolve_end
);
179 EXPECT_LE(load_timing_info
.proxy_resolve_end
,
180 load_timing_info
.send_start
);
181 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
182 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
185 #if !defined(DISABLE_FILE_SUPPORT)
186 // Tests load timing information in the case of a cache hit, when no cache
187 // validation request was sent over the wire.
188 base::StringPiece
TestNetResourceProvider(int key
) {
192 void FillBuffer(char* buffer
, size_t len
) {
193 static bool called
= false;
196 int seed
= static_cast<int>(Time::Now().ToInternalValue());
200 for (size_t i
= 0; i
< len
; i
++) {
201 buffer
[i
] = static_cast<char>(rand());
209 void TestLoadTimingCacheHitNoNetwork(
210 const LoadTimingInfo
& load_timing_info
) {
211 EXPECT_FALSE(load_timing_info
.socket_reused
);
212 EXPECT_EQ(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
214 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
215 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
217 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
218 EXPECT_LE(load_timing_info
.request_start
, load_timing_info
.send_start
);
219 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
220 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
222 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
223 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
226 #if !defined(DISABLE_FTP_SUPPORT)
227 // Tests load timing in the case that there is no HTTP response. This can be
228 // used to test in the case of errors or non-HTTP requests.
229 void TestLoadTimingNoHttpResponse(
230 const LoadTimingInfo
& load_timing_info
) {
231 EXPECT_FALSE(load_timing_info
.socket_reused
);
232 EXPECT_EQ(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
234 // Only the request times should be non-null.
235 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
236 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
238 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
240 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
241 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
242 EXPECT_TRUE(load_timing_info
.send_start
.is_null());
243 EXPECT_TRUE(load_timing_info
.send_end
.is_null());
244 EXPECT_TRUE(load_timing_info
.receive_headers_end
.is_null());
248 // Do a case-insensitive search through |haystack| for |needle|.
249 bool ContainsString(const std::string
& haystack
, const char* needle
) {
250 std::string::const_iterator it
=
251 std::search(haystack
.begin(),
254 needle
+ strlen(needle
),
255 base::CaseInsensitiveCompare
<char>());
256 return it
!= haystack
.end();
259 scoped_ptr
<UploadDataStream
> CreateSimpleUploadData(const char* data
) {
260 scoped_ptr
<UploadElementReader
> reader(
261 new UploadBytesElementReader(data
, strlen(data
)));
262 return ElementsUploadDataStream::CreateWithReader(reader
.Pass(), 0);
265 // Verify that the SSLInfo of a successful SSL connection has valid values.
266 void CheckSSLInfo(const SSLInfo
& ssl_info
) {
267 // -1 means unknown. 0 means no encryption.
268 EXPECT_GT(ssl_info
.security_bits
, 0);
270 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
271 uint16 cipher_suite
= SSLConnectionStatusToCipherSuite(
272 ssl_info
.connection_status
);
273 EXPECT_NE(0U, cipher_suite
);
276 void CheckFullRequestHeaders(const HttpRequestHeaders
& headers
,
277 const GURL
& host_url
) {
278 std::string sent_value
;
280 EXPECT_TRUE(headers
.GetHeader("Host", &sent_value
));
281 EXPECT_EQ(GetHostAndOptionalPort(host_url
), sent_value
);
283 EXPECT_TRUE(headers
.GetHeader("Connection", &sent_value
));
284 EXPECT_EQ("keep-alive", sent_value
);
287 bool FingerprintsEqual(const HashValueVector
& a
, const HashValueVector
& b
) {
288 size_t size
= a
.size();
290 if (size
!= b
.size())
293 for (size_t i
= 0; i
< size
; ++i
) {
294 if (!a
[i
].Equals(b
[i
]))
300 #endif // !defined(OS_IOS)
302 // A network delegate that allows the user to choose a subset of request stages
303 // to block in. When blocking, the delegate can do one of the following:
304 // * synchronously return a pre-specified error code, or
305 // * asynchronously return that value via an automatically called callback,
307 // * block and wait for the user to do a callback.
308 // Additionally, the user may also specify a redirect URL -- then each request
309 // with the current URL different from the redirect target will be redirected
310 // to that target, in the on-before-URL-request stage, independent of whether
311 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
312 class BlockingNetworkDelegate
: public TestNetworkDelegate
{
314 // Stages in which the delegate can block.
317 ON_BEFORE_URL_REQUEST
= 1 << 0,
318 ON_BEFORE_SEND_HEADERS
= 1 << 1,
319 ON_HEADERS_RECEIVED
= 1 << 2,
320 ON_AUTH_REQUIRED
= 1 << 3
323 // Behavior during blocked stages. During other stages, just
324 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
326 SYNCHRONOUS
, // No callback, returns specified return values.
327 AUTO_CALLBACK
, // |this| posts a task to run the callback using the
328 // specified return codes.
329 USER_CALLBACK
, // User takes care of doing a callback. |retval_| and
330 // |auth_retval_| are ignored. In every blocking stage the
331 // message loop is quit.
334 // Creates a delegate which does not block at all.
335 explicit BlockingNetworkDelegate(BlockMode block_mode
);
337 // For users to trigger a callback returning |response|.
338 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
339 // Only call if |block_mode_| == USER_CALLBACK.
340 void DoCallback(int response
);
341 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response
);
344 void set_retval(int retval
) {
345 ASSERT_NE(USER_CALLBACK
, block_mode_
);
346 ASSERT_NE(ERR_IO_PENDING
, retval
);
347 ASSERT_NE(OK
, retval
);
351 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
352 // |auth_credentials_| will be passed with the response.
353 void set_auth_retval(AuthRequiredResponse auth_retval
) {
354 ASSERT_NE(USER_CALLBACK
, block_mode_
);
355 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING
, auth_retval
);
356 auth_retval_
= auth_retval
;
358 void set_auth_credentials(const AuthCredentials
& auth_credentials
) {
359 auth_credentials_
= auth_credentials
;
362 void set_redirect_url(const GURL
& url
) {
366 void set_block_on(int block_on
) {
367 block_on_
= block_on
;
370 // Allows the user to check in which state did we block.
371 Stage
stage_blocked_for_callback() const {
372 EXPECT_EQ(USER_CALLBACK
, block_mode_
);
373 return stage_blocked_for_callback_
;
377 void RunCallback(int response
, const CompletionCallback
& callback
);
378 void RunAuthCallback(AuthRequiredResponse response
,
379 const AuthCallback
& callback
);
381 // TestNetworkDelegate implementation.
382 int OnBeforeURLRequest(URLRequest
* request
,
383 const CompletionCallback
& callback
,
384 GURL
* new_url
) override
;
386 int OnBeforeSendHeaders(URLRequest
* request
,
387 const CompletionCallback
& callback
,
388 HttpRequestHeaders
* headers
) override
;
390 int OnHeadersReceived(
392 const CompletionCallback
& callback
,
393 const HttpResponseHeaders
* original_response_headers
,
394 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
395 GURL
* allowed_unsafe_redirect_url
) override
;
397 NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
399 const AuthChallengeInfo
& auth_info
,
400 const AuthCallback
& callback
,
401 AuthCredentials
* credentials
) override
;
403 // Resets the callbacks and |stage_blocked_for_callback_|.
406 // Checks whether we should block in |stage|. If yes, returns an error code
407 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
408 int MaybeBlockStage(Stage stage
, const CompletionCallback
& callback
);
410 // Configuration parameters, can be adjusted by public methods:
411 const BlockMode block_mode_
;
413 // Values returned on blocking stages when mode is SYNCHRONOUS or
414 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
415 int retval_
; // To be returned in non-auth stages.
416 AuthRequiredResponse auth_retval_
;
418 GURL redirect_url_
; // Used if non-empty during OnBeforeURLRequest.
419 int block_on_
; // Bit mask: in which stages to block.
421 // |auth_credentials_| will be copied to |*target_auth_credential_| on
423 AuthCredentials auth_credentials_
;
424 AuthCredentials
* target_auth_credentials_
;
426 // Internal variables, not set by not the user:
427 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
429 Stage stage_blocked_for_callback_
;
431 // Callback objects stored during blocking stages.
432 CompletionCallback callback_
;
433 AuthCallback auth_callback_
;
435 base::WeakPtrFactory
<BlockingNetworkDelegate
> weak_factory_
;
437 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate
);
440 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode
)
441 : block_mode_(block_mode
),
443 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION
),
445 target_auth_credentials_(NULL
),
446 stage_blocked_for_callback_(NOT_BLOCKED
),
447 weak_factory_(this) {
450 void BlockingNetworkDelegate::DoCallback(int response
) {
451 ASSERT_EQ(USER_CALLBACK
, block_mode_
);
452 ASSERT_NE(NOT_BLOCKED
, stage_blocked_for_callback_
);
453 ASSERT_NE(ON_AUTH_REQUIRED
, stage_blocked_for_callback_
);
454 CompletionCallback callback
= callback_
;
456 RunCallback(response
, callback
);
459 void BlockingNetworkDelegate::DoAuthCallback(
460 NetworkDelegate::AuthRequiredResponse response
) {
461 ASSERT_EQ(USER_CALLBACK
, block_mode_
);
462 ASSERT_EQ(ON_AUTH_REQUIRED
, stage_blocked_for_callback_
);
463 AuthCallback auth_callback
= auth_callback_
;
465 RunAuthCallback(response
, auth_callback
);
468 void BlockingNetworkDelegate::RunCallback(int response
,
469 const CompletionCallback
& callback
) {
470 callback
.Run(response
);
473 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response
,
474 const AuthCallback
& callback
) {
475 if (auth_retval_
== AUTH_REQUIRED_RESPONSE_SET_AUTH
) {
476 ASSERT_TRUE(target_auth_credentials_
!= NULL
);
477 *target_auth_credentials_
= auth_credentials_
;
479 callback
.Run(response
);
482 int BlockingNetworkDelegate::OnBeforeURLRequest(
484 const CompletionCallback
& callback
,
486 if (redirect_url_
== request
->url())
487 return OK
; // We've already seen this request and redirected elsewhere.
489 TestNetworkDelegate::OnBeforeURLRequest(request
, callback
, new_url
);
491 if (!redirect_url_
.is_empty())
492 *new_url
= redirect_url_
;
494 return MaybeBlockStage(ON_BEFORE_URL_REQUEST
, callback
);
497 int BlockingNetworkDelegate::OnBeforeSendHeaders(
499 const CompletionCallback
& callback
,
500 HttpRequestHeaders
* headers
) {
501 TestNetworkDelegate::OnBeforeSendHeaders(request
, callback
, headers
);
503 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS
, callback
);
506 int BlockingNetworkDelegate::OnHeadersReceived(
508 const CompletionCallback
& callback
,
509 const HttpResponseHeaders
* original_response_headers
,
510 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
511 GURL
* allowed_unsafe_redirect_url
) {
512 TestNetworkDelegate::OnHeadersReceived(request
,
514 original_response_headers
,
515 override_response_headers
,
516 allowed_unsafe_redirect_url
);
518 return MaybeBlockStage(ON_HEADERS_RECEIVED
, callback
);
521 NetworkDelegate::AuthRequiredResponse
BlockingNetworkDelegate::OnAuthRequired(
523 const AuthChallengeInfo
& auth_info
,
524 const AuthCallback
& callback
,
525 AuthCredentials
* credentials
) {
526 TestNetworkDelegate::OnAuthRequired(request
, auth_info
, callback
,
528 // Check that the user has provided callback for the previous blocked stage.
529 EXPECT_EQ(NOT_BLOCKED
, stage_blocked_for_callback_
);
531 if ((block_on_
& ON_AUTH_REQUIRED
) == 0) {
532 return AUTH_REQUIRED_RESPONSE_NO_ACTION
;
535 target_auth_credentials_
= credentials
;
537 switch (block_mode_
) {
539 if (auth_retval_
== AUTH_REQUIRED_RESPONSE_SET_AUTH
)
540 *target_auth_credentials_
= auth_credentials_
;
544 base::MessageLoop::current()->PostTask(
546 base::Bind(&BlockingNetworkDelegate::RunAuthCallback
,
547 weak_factory_
.GetWeakPtr(), auth_retval_
, callback
));
548 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
551 auth_callback_
= callback
;
552 stage_blocked_for_callback_
= ON_AUTH_REQUIRED
;
553 base::MessageLoop::current()->PostTask(FROM_HERE
,
554 base::MessageLoop::QuitClosure());
555 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
558 return AUTH_REQUIRED_RESPONSE_NO_ACTION
; // Dummy value.
561 void BlockingNetworkDelegate::Reset() {
562 EXPECT_NE(NOT_BLOCKED
, stage_blocked_for_callback_
);
563 stage_blocked_for_callback_
= NOT_BLOCKED
;
565 auth_callback_
.Reset();
568 int BlockingNetworkDelegate::MaybeBlockStage(
569 BlockingNetworkDelegate::Stage stage
,
570 const CompletionCallback
& callback
) {
571 // Check that the user has provided callback for the previous blocked stage.
572 EXPECT_EQ(NOT_BLOCKED
, stage_blocked_for_callback_
);
574 if ((block_on_
& stage
) == 0) {
578 switch (block_mode_
) {
580 EXPECT_NE(OK
, retval_
);
584 base::MessageLoop::current()->PostTask(
586 base::Bind(&BlockingNetworkDelegate::RunCallback
,
587 weak_factory_
.GetWeakPtr(), retval_
, callback
));
588 return ERR_IO_PENDING
;
591 callback_
= callback
;
592 stage_blocked_for_callback_
= stage
;
593 base::MessageLoop::current()->PostTask(FROM_HERE
,
594 base::MessageLoop::QuitClosure());
595 return ERR_IO_PENDING
;
601 class TestURLRequestContextWithProxy
: public TestURLRequestContext
{
603 // Does not own |delegate|.
604 TestURLRequestContextWithProxy(const std::string
& proxy
,
605 NetworkDelegate
* delegate
)
606 : TestURLRequestContext(true) {
607 context_storage_
.set_proxy_service(ProxyService::CreateFixed(proxy
));
608 set_network_delegate(delegate
);
611 ~TestURLRequestContextWithProxy() override
{}
616 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
617 class URLRequestTest
: public PlatformTest
{
619 URLRequestTest() : default_context_(true) {
620 default_context_
.set_network_delegate(&default_network_delegate_
);
621 default_context_
.set_net_log(&net_log_
);
622 job_factory_impl_
= new URLRequestJobFactoryImpl();
623 job_factory_
.reset(job_factory_impl_
);
626 ~URLRequestTest() override
{
627 // URLRequestJobs may post clean-up tasks on destruction.
628 base::RunLoop().RunUntilIdle();
631 void SetUp() override
{
633 default_context_
.set_job_factory(job_factory_
.get());
634 default_context_
.Init();
635 PlatformTest::SetUp();
638 virtual void SetUpFactory() {
639 job_factory_impl_
->SetProtocolHandler("data", new DataProtocolHandler
);
640 #if !defined(DISABLE_FILE_SUPPORT)
641 job_factory_impl_
->SetProtocolHandler(
642 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
646 TestNetworkDelegate
* default_network_delegate() {
647 return &default_network_delegate_
;
650 const TestURLRequestContext
& default_context() const {
651 return default_context_
;
655 // Adds the TestJobInterceptor to the default context.
656 TestJobInterceptor
* AddTestInterceptor() {
657 TestJobInterceptor
* protocol_handler_
= new TestJobInterceptor();
658 job_factory_impl_
->SetProtocolHandler("http", NULL
);
659 job_factory_impl_
->SetProtocolHandler("http", protocol_handler_
);
660 return protocol_handler_
;
665 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
666 URLRequestJobFactoryImpl
* job_factory_impl_
;
667 scoped_ptr
<URLRequestJobFactory
> job_factory_
;
668 TestURLRequestContext default_context_
;
671 TEST_F(URLRequestTest
, AboutBlankTest
) {
674 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
675 GURL("about:blank"), DEFAULT_PRIORITY
, &d
));
678 EXPECT_TRUE(r
->is_pending());
680 base::RunLoop().Run();
682 EXPECT_TRUE(!r
->is_pending());
683 EXPECT_FALSE(d
.received_data_before_response());
684 EXPECT_EQ(d
.bytes_received(), 0);
685 EXPECT_EQ("", r
->GetSocketAddress().host());
686 EXPECT_EQ(0, r
->GetSocketAddress().port());
688 HttpRequestHeaders headers
;
689 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
693 TEST_F(URLRequestTest
, DataURLImageTest
) {
696 // Use our nice little Chrome logo.
697 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
699 "data:image/png;base64,"
700 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
701 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
702 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
703 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
704 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
705 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
706 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
707 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
708 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
709 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
710 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
711 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
712 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
713 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
714 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
715 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
716 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
717 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
718 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
719 DEFAULT_PRIORITY
, &d
));
722 EXPECT_TRUE(r
->is_pending());
724 base::RunLoop().Run();
726 EXPECT_TRUE(!r
->is_pending());
727 EXPECT_FALSE(d
.received_data_before_response());
728 EXPECT_EQ(d
.bytes_received(), 911);
729 EXPECT_EQ("", r
->GetSocketAddress().host());
730 EXPECT_EQ(0, r
->GetSocketAddress().port());
732 HttpRequestHeaders headers
;
733 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
737 #if !defined(DISABLE_FILE_SUPPORT)
738 TEST_F(URLRequestTest
, FileTest
) {
739 base::FilePath app_path
;
740 PathService::Get(base::FILE_EXE
, &app_path
);
741 GURL app_url
= FilePathToFileURL(app_path
);
745 scoped_ptr
<URLRequest
> r(
746 default_context_
.CreateRequest(app_url
, DEFAULT_PRIORITY
, &d
));
749 EXPECT_TRUE(r
->is_pending());
751 base::RunLoop().Run();
753 int64 file_size
= -1;
754 EXPECT_TRUE(base::GetFileSize(app_path
, &file_size
));
756 EXPECT_TRUE(!r
->is_pending());
757 EXPECT_EQ(1, d
.response_started_count());
758 EXPECT_FALSE(d
.received_data_before_response());
759 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
760 EXPECT_EQ("", r
->GetSocketAddress().host());
761 EXPECT_EQ(0, r
->GetSocketAddress().port());
763 HttpRequestHeaders headers
;
764 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
768 TEST_F(URLRequestTest
, FileTestCancel
) {
769 base::FilePath app_path
;
770 PathService::Get(base::FILE_EXE
, &app_path
);
771 GURL app_url
= FilePathToFileURL(app_path
);
775 scoped_ptr
<URLRequest
> r(
776 default_context_
.CreateRequest(app_url
, DEFAULT_PRIORITY
, &d
));
779 EXPECT_TRUE(r
->is_pending());
782 // Async cancellation should be safe even when URLRequest has been already
784 base::RunLoop().RunUntilIdle();
787 TEST_F(URLRequestTest
, FileTestFullSpecifiedRange
) {
788 const size_t buffer_size
= 4000;
789 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
790 FillBuffer(buffer
.get(), buffer_size
);
792 base::FilePath temp_path
;
793 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
794 GURL temp_url
= FilePathToFileURL(temp_path
);
795 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
798 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
800 const size_t first_byte_position
= 500;
801 const size_t last_byte_position
= buffer_size
- first_byte_position
;
802 const size_t content_length
= last_byte_position
- first_byte_position
+ 1;
803 std::string
partial_buffer_string(buffer
.get() + first_byte_position
,
804 buffer
.get() + last_byte_position
+ 1);
808 scoped_ptr
<URLRequest
> r(
809 default_context_
.CreateRequest(temp_url
, DEFAULT_PRIORITY
, &d
));
811 HttpRequestHeaders headers
;
813 HttpRequestHeaders::kRange
,
814 HttpByteRange::Bounded(
815 first_byte_position
, last_byte_position
).GetHeaderValue());
816 r
->SetExtraRequestHeaders(headers
);
818 EXPECT_TRUE(r
->is_pending());
820 base::RunLoop().Run();
821 EXPECT_TRUE(!r
->is_pending());
822 EXPECT_EQ(1, d
.response_started_count());
823 EXPECT_FALSE(d
.received_data_before_response());
824 EXPECT_EQ(static_cast<int>(content_length
), d
.bytes_received());
825 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
826 EXPECT_TRUE(partial_buffer_string
== d
.data_received());
829 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
832 TEST_F(URLRequestTest
, FileTestHalfSpecifiedRange
) {
833 const size_t buffer_size
= 4000;
834 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
835 FillBuffer(buffer
.get(), buffer_size
);
837 base::FilePath temp_path
;
838 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
839 GURL temp_url
= FilePathToFileURL(temp_path
);
840 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
843 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
845 const size_t first_byte_position
= 500;
846 const size_t last_byte_position
= buffer_size
- 1;
847 const size_t content_length
= last_byte_position
- first_byte_position
+ 1;
848 std::string
partial_buffer_string(buffer
.get() + first_byte_position
,
849 buffer
.get() + last_byte_position
+ 1);
853 scoped_ptr
<URLRequest
> r(
854 default_context_
.CreateRequest(temp_url
, DEFAULT_PRIORITY
, &d
));
856 HttpRequestHeaders headers
;
857 headers
.SetHeader(HttpRequestHeaders::kRange
,
858 HttpByteRange::RightUnbounded(
859 first_byte_position
).GetHeaderValue());
860 r
->SetExtraRequestHeaders(headers
);
862 EXPECT_TRUE(r
->is_pending());
864 base::RunLoop().Run();
865 EXPECT_TRUE(!r
->is_pending());
866 EXPECT_EQ(1, d
.response_started_count());
867 EXPECT_FALSE(d
.received_data_before_response());
868 EXPECT_EQ(static_cast<int>(content_length
), d
.bytes_received());
869 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
870 EXPECT_TRUE(partial_buffer_string
== d
.data_received());
873 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
876 TEST_F(URLRequestTest
, FileTestMultipleRanges
) {
877 const size_t buffer_size
= 400000;
878 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
879 FillBuffer(buffer
.get(), buffer_size
);
881 base::FilePath temp_path
;
882 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
883 GURL temp_url
= FilePathToFileURL(temp_path
);
884 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
887 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
891 scoped_ptr
<URLRequest
> r(
892 default_context_
.CreateRequest(temp_url
, DEFAULT_PRIORITY
, &d
));
894 HttpRequestHeaders headers
;
895 headers
.SetHeader(HttpRequestHeaders::kRange
, "bytes=0-0,10-200,200-300");
896 r
->SetExtraRequestHeaders(headers
);
898 EXPECT_TRUE(r
->is_pending());
900 base::RunLoop().Run();
901 EXPECT_TRUE(d
.request_failed());
904 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
907 TEST_F(URLRequestTest
, AllowFileURLs
) {
908 base::ScopedTempDir temp_dir
;
909 ASSERT_TRUE(temp_dir
.CreateUniqueTempDir());
910 base::FilePath test_file
;
911 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir
.path(), &test_file
));
912 std::string
test_data("monkey");
913 base::WriteFile(test_file
, test_data
.data(), test_data
.size());
914 GURL test_file_url
= FilePathToFileURL(test_file
);
918 TestNetworkDelegate network_delegate
;
919 network_delegate
.set_can_access_files(true);
920 default_context_
.set_network_delegate(&network_delegate
);
921 scoped_ptr
<URLRequest
> r(
922 default_context_
.CreateRequest(test_file_url
, DEFAULT_PRIORITY
, &d
));
924 base::RunLoop().Run();
925 EXPECT_FALSE(d
.request_failed());
926 EXPECT_EQ(test_data
, d
.data_received());
931 TestNetworkDelegate network_delegate
;
932 network_delegate
.set_can_access_files(false);
933 default_context_
.set_network_delegate(&network_delegate
);
934 scoped_ptr
<URLRequest
> r(
935 default_context_
.CreateRequest(test_file_url
, DEFAULT_PRIORITY
, &d
));
937 base::RunLoop().Run();
938 EXPECT_TRUE(d
.request_failed());
939 EXPECT_EQ("", d
.data_received());
944 TEST_F(URLRequestTest
, FileDirCancelTest
) {
945 // Put in mock resource provider.
946 NetModule::SetResourceProvider(TestNetResourceProvider
);
950 base::FilePath file_path
;
951 PathService::Get(base::DIR_SOURCE_ROOT
, &file_path
);
952 file_path
= file_path
.Append(FILE_PATH_LITERAL("net"));
953 file_path
= file_path
.Append(FILE_PATH_LITERAL("data"));
955 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
956 FilePathToFileURL(file_path
), DEFAULT_PRIORITY
, &d
));
958 EXPECT_TRUE(req
->is_pending());
960 d
.set_cancel_in_received_data_pending(true);
962 base::RunLoop().Run();
965 // Take out mock resource provider.
966 NetModule::SetResourceProvider(NULL
);
969 TEST_F(URLRequestTest
, FileDirOutputSanity
) {
970 // Verify the general sanity of the the output of the file:
971 // directory lister by checking for the output of a known existing
973 const char sentinel_name
[] = "filedir-sentinel";
976 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
977 path
= path
.Append(FILE_PATH_LITERAL("net"));
978 path
= path
.Append(FILE_PATH_LITERAL("data"));
979 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
982 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
983 FilePathToFileURL(path
), DEFAULT_PRIORITY
, &d
));
985 base::RunLoop().Run();
987 // Generate entry for the sentinel file.
988 base::FilePath sentinel_path
= path
.AppendASCII(sentinel_name
);
989 base::File::Info info
;
990 EXPECT_TRUE(base::GetFileInfo(sentinel_path
, &info
));
991 EXPECT_GT(info
.size
, 0);
992 std::string sentinel_output
= GetDirectoryListingEntry(
993 base::string16(sentinel_name
, sentinel_name
+ strlen(sentinel_name
)),
994 std::string(sentinel_name
),
999 ASSERT_LT(0, d
.bytes_received());
1000 ASSERT_FALSE(d
.request_failed());
1001 ASSERT_TRUE(req
->status().is_success());
1002 // Check for the entry generated for the "sentinel" file.
1003 const std::string
& data
= d
.data_received();
1004 ASSERT_NE(data
.find(sentinel_output
), std::string::npos
);
1007 TEST_F(URLRequestTest
, FileDirRedirectNoCrash
) {
1008 // There is an implicit redirect when loading a file path that matches a
1009 // directory and does not end with a slash. Ensure that following such
1010 // redirects does not crash. See http://crbug.com/18686.
1012 base::FilePath path
;
1013 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
1014 path
= path
.Append(FILE_PATH_LITERAL("net"));
1015 path
= path
.Append(FILE_PATH_LITERAL("data"));
1016 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
1019 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1020 FilePathToFileURL(path
), DEFAULT_PRIORITY
, &d
));
1022 base::RunLoop().Run();
1024 ASSERT_EQ(1, d
.received_redirect_count());
1025 ASSERT_LT(0, d
.bytes_received());
1026 ASSERT_FALSE(d
.request_failed());
1027 ASSERT_TRUE(req
->status().is_success());
1031 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1032 TEST_F(URLRequestTest
, FileDirRedirectSingleSlash
) {
1034 scoped_ptr
<URLRequest
> req(
1035 default_context_
.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY
, &d
));
1037 base::RunLoop().Run();
1039 ASSERT_EQ(1, d
.received_redirect_count());
1040 ASSERT_FALSE(req
->status().is_success());
1042 #endif // defined(OS_WIN)
1044 #endif // !defined(DISABLE_FILE_SUPPORT)
1046 TEST_F(URLRequestTest
, InvalidUrlTest
) {
1049 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
1050 GURL("invalid url"), DEFAULT_PRIORITY
, &d
));
1053 EXPECT_TRUE(r
->is_pending());
1055 base::RunLoop().Run();
1056 EXPECT_TRUE(d
.request_failed());
1060 TEST_F(URLRequestTest
, InvalidReferrerTest
) {
1061 TestURLRequestContext context
;
1062 TestNetworkDelegate network_delegate
;
1063 network_delegate
.set_cancel_request_with_policy_violating_referrer(true);
1064 context
.set_network_delegate(&network_delegate
);
1066 scoped_ptr
<URLRequest
> req(
1067 context
.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY
, &d
));
1068 req
->SetReferrer("https://somewhere.com/");
1071 base::RunLoop().Run();
1072 EXPECT_TRUE(d
.request_failed());
1076 TEST_F(URLRequestTest
, ResolveShortcutTest
) {
1077 base::FilePath app_path
;
1078 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
1079 app_path
= app_path
.AppendASCII("net");
1080 app_path
= app_path
.AppendASCII("data");
1081 app_path
= app_path
.AppendASCII("url_request_unittest");
1082 app_path
= app_path
.AppendASCII("with-headers.html");
1084 std::wstring lnk_path
= app_path
.value() + L
".lnk";
1086 base::win::ScopedCOMInitializer com_initializer
;
1088 // Temporarily create a shortcut for test
1090 base::win::ScopedComPtr
<IShellLink
> shell
;
1091 ASSERT_TRUE(SUCCEEDED(shell
.CreateInstance(CLSID_ShellLink
, NULL
,
1092 CLSCTX_INPROC_SERVER
)));
1093 base::win::ScopedComPtr
<IPersistFile
> persist
;
1094 ASSERT_TRUE(SUCCEEDED(shell
.QueryInterface(persist
.Receive())));
1095 EXPECT_TRUE(SUCCEEDED(shell
->SetPath(app_path
.value().c_str())));
1096 EXPECT_TRUE(SUCCEEDED(shell
->SetDescription(L
"ResolveShortcutTest")));
1097 EXPECT_TRUE(SUCCEEDED(persist
->Save(lnk_path
.c_str(), TRUE
)));
1102 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
1103 FilePathToFileURL(base::FilePath(lnk_path
)), DEFAULT_PRIORITY
, &d
));
1106 EXPECT_TRUE(r
->is_pending());
1108 base::RunLoop().Run();
1110 WIN32_FILE_ATTRIBUTE_DATA data
;
1111 GetFileAttributesEx(app_path
.value().c_str(),
1112 GetFileExInfoStandard
, &data
);
1113 HANDLE file
= CreateFile(app_path
.value().c_str(), GENERIC_READ
,
1114 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
1115 FILE_ATTRIBUTE_NORMAL
, NULL
);
1116 EXPECT_NE(INVALID_HANDLE_VALUE
, file
);
1117 scoped_ptr
<char[]> buffer(new char[data
.nFileSizeLow
]);
1120 result
= ReadFile(file
, buffer
.get(), data
.nFileSizeLow
,
1122 std::string
content(buffer
.get(), read_size
);
1125 EXPECT_TRUE(!r
->is_pending());
1126 EXPECT_EQ(1, d
.received_redirect_count());
1127 EXPECT_EQ(content
, d
.data_received());
1130 // Clean the shortcut
1131 DeleteFile(lnk_path
.c_str());
1133 #endif // defined(OS_WIN)
1135 // Custom URLRequestJobs for use with interceptor tests
1136 class RestartTestJob
: public URLRequestTestJob
{
1138 RestartTestJob(URLRequest
* request
, NetworkDelegate
* network_delegate
)
1139 : URLRequestTestJob(request
, network_delegate
, true) {}
1141 void StartAsync() override
{ this->NotifyRestartRequired(); }
1143 ~RestartTestJob() override
{}
1146 class CancelTestJob
: public URLRequestTestJob
{
1148 explicit CancelTestJob(URLRequest
* request
, NetworkDelegate
* network_delegate
)
1149 : URLRequestTestJob(request
, network_delegate
, true) {}
1151 void StartAsync() override
{ request_
->Cancel(); }
1153 ~CancelTestJob() override
{}
1156 class CancelThenRestartTestJob
: public URLRequestTestJob
{
1158 explicit CancelThenRestartTestJob(URLRequest
* request
,
1159 NetworkDelegate
* network_delegate
)
1160 : URLRequestTestJob(request
, network_delegate
, true) {
1163 void StartAsync() override
{
1165 this->NotifyRestartRequired();
1168 ~CancelThenRestartTestJob() override
{}
1171 // An Interceptor for use with interceptor tests.
1172 class MockURLRequestInterceptor
: public URLRequestInterceptor
{
1174 // Static getters for canned response header and data strings.
1175 static std::string
ok_data() {
1176 return URLRequestTestJob::test_data_1();
1179 static std::string
ok_headers() {
1180 return URLRequestTestJob::test_headers();
1183 static std::string
redirect_data() {
1184 return std::string();
1187 static std::string
redirect_headers() {
1188 return URLRequestTestJob::test_redirect_headers();
1191 static std::string
error_data() {
1192 return std::string("ohhh nooooo mr. bill!");
1195 static std::string
error_headers() {
1196 return URLRequestTestJob::test_error_headers();
1199 MockURLRequestInterceptor()
1200 : intercept_main_request_(false), restart_main_request_(false),
1201 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1202 simulate_main_network_error_(false),
1203 intercept_redirect_(false), cancel_redirect_request_(false),
1204 intercept_final_response_(false), cancel_final_request_(false),
1205 use_url_request_http_job_(false),
1206 did_intercept_main_(false), did_restart_main_(false),
1207 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1208 did_simulate_error_main_(false),
1209 did_intercept_redirect_(false), did_cancel_redirect_(false),
1210 did_intercept_final_(false), did_cancel_final_(false) {
1213 ~MockURLRequestInterceptor() override
{
1216 // URLRequestInterceptor implementation:
1217 URLRequestJob
* MaybeInterceptRequest(
1218 URLRequest
* request
,
1219 NetworkDelegate
* network_delegate
) const override
{
1220 if (restart_main_request_
) {
1221 restart_main_request_
= false;
1222 did_restart_main_
= true;
1223 return new RestartTestJob(request
, network_delegate
);
1225 if (cancel_main_request_
) {
1226 cancel_main_request_
= false;
1227 did_cancel_main_
= true;
1228 return new CancelTestJob(request
, network_delegate
);
1230 if (cancel_then_restart_main_request_
) {
1231 cancel_then_restart_main_request_
= false;
1232 did_cancel_then_restart_main_
= true;
1233 return new CancelThenRestartTestJob(request
, network_delegate
);
1235 if (simulate_main_network_error_
) {
1236 simulate_main_network_error_
= false;
1237 did_simulate_error_main_
= true;
1238 if (use_url_request_http_job_
) {
1239 return URLRequestHttpJob::Factory(request
, network_delegate
, "http");
1241 // This job will result in error since the requested URL is not one of the
1242 // URLs supported by these tests.
1243 return new URLRequestTestJob(request
, network_delegate
, true);
1245 if (!intercept_main_request_
)
1247 intercept_main_request_
= false;
1248 did_intercept_main_
= true;
1249 URLRequestTestJob
* job
= new URLRequestTestJob(request
,
1254 job
->set_load_timing_info(main_request_load_timing_info_
);
1258 URLRequestJob
* MaybeInterceptRedirect(URLRequest
* request
,
1259 NetworkDelegate
* network_delegate
,
1260 const GURL
& location
) const override
{
1261 if (cancel_redirect_request_
) {
1262 cancel_redirect_request_
= false;
1263 did_cancel_redirect_
= true;
1264 return new CancelTestJob(request
, network_delegate
);
1266 if (!intercept_redirect_
)
1268 intercept_redirect_
= false;
1269 did_intercept_redirect_
= true;
1270 if (use_url_request_http_job_
) {
1271 return URLRequestHttpJob::Factory(request
, network_delegate
, "http");
1273 return new URLRequestTestJob(request
,
1280 URLRequestJob
* MaybeInterceptResponse(
1281 URLRequest
* request
,
1282 NetworkDelegate
* network_delegate
) const override
{
1283 if (cancel_final_request_
) {
1284 cancel_final_request_
= false;
1285 did_cancel_final_
= true;
1286 return new CancelTestJob(request
, network_delegate
);
1288 if (!intercept_final_response_
)
1290 intercept_final_response_
= false;
1291 did_intercept_final_
= true;
1292 if (use_url_request_http_job_
) {
1293 return URLRequestHttpJob::Factory(request
, network_delegate
, "http");
1295 return new URLRequestTestJob(request
,
1302 void set_intercept_main_request(bool intercept_main_request
) {
1303 intercept_main_request_
= intercept_main_request
;
1306 void set_main_headers(const std::string
& main_headers
) {
1307 main_headers_
= main_headers
;
1310 void set_main_data(const std::string
& main_data
) {
1311 main_data_
= main_data
;
1314 void set_main_request_load_timing_info(
1315 const LoadTimingInfo
& main_request_load_timing_info
) {
1316 main_request_load_timing_info_
= main_request_load_timing_info
;
1319 void set_restart_main_request(bool restart_main_request
) {
1320 restart_main_request_
= restart_main_request
;
1323 void set_cancel_main_request(bool cancel_main_request
) {
1324 cancel_main_request_
= cancel_main_request
;
1327 void set_cancel_then_restart_main_request(
1328 bool cancel_then_restart_main_request
) {
1329 cancel_then_restart_main_request_
= cancel_then_restart_main_request
;
1332 void set_simulate_main_network_error(bool simulate_main_network_error
) {
1333 simulate_main_network_error_
= simulate_main_network_error
;
1336 void set_intercept_redirect(bool intercept_redirect
) {
1337 intercept_redirect_
= intercept_redirect
;
1340 void set_redirect_headers(const std::string
& redirect_headers
) {
1341 redirect_headers_
= redirect_headers
;
1344 void set_redirect_data(const std::string
& redirect_data
) {
1345 redirect_data_
= redirect_data
;
1348 void set_cancel_redirect_request(bool cancel_redirect_request
) {
1349 cancel_redirect_request_
= cancel_redirect_request
;
1352 void set_intercept_final_response(bool intercept_final_response
) {
1353 intercept_final_response_
= intercept_final_response
;
1356 void set_final_headers(const std::string
& final_headers
) {
1357 final_headers_
= final_headers
;
1360 void set_final_data(const std::string
& final_data
) {
1361 final_data_
= final_data
;
1364 void set_cancel_final_request(bool cancel_final_request
) {
1365 cancel_final_request_
= cancel_final_request
;
1368 void set_use_url_request_http_job(bool use_url_request_http_job
) {
1369 use_url_request_http_job_
= use_url_request_http_job
;
1372 bool did_intercept_main() const {
1373 return did_intercept_main_
;
1376 bool did_restart_main() const {
1377 return did_restart_main_
;
1380 bool did_cancel_main() const {
1381 return did_cancel_main_
;
1384 bool did_cancel_then_restart_main() const {
1385 return did_cancel_then_restart_main_
;
1388 bool did_simulate_error_main() const {
1389 return did_simulate_error_main_
;
1392 bool did_intercept_redirect() const {
1393 return did_intercept_redirect_
;
1396 bool did_cancel_redirect() const {
1397 return did_cancel_redirect_
;
1400 bool did_intercept_final() const {
1401 return did_intercept_final_
;
1404 bool did_cancel_final() const {
1405 return did_cancel_final_
;
1409 // Indicate whether to intercept the main request, and if so specify the
1410 // response to return and the LoadTimingInfo to use.
1411 mutable bool intercept_main_request_
;
1412 mutable std::string main_headers_
;
1413 mutable std::string main_data_
;
1414 mutable LoadTimingInfo main_request_load_timing_info_
;
1416 // These indicate actions that can be taken within MaybeInterceptRequest.
1417 mutable bool restart_main_request_
;
1418 mutable bool cancel_main_request_
;
1419 mutable bool cancel_then_restart_main_request_
;
1420 mutable bool simulate_main_network_error_
;
1422 // Indicate whether to intercept redirects, and if so specify the response to
1424 mutable bool intercept_redirect_
;
1425 mutable std::string redirect_headers_
;
1426 mutable std::string redirect_data_
;
1428 // Cancel the request within MaybeInterceptRedirect.
1429 mutable bool cancel_redirect_request_
;
1431 // Indicate whether to intercept the final response, and if so specify the
1432 // response to return.
1433 mutable bool intercept_final_response_
;
1434 mutable std::string final_headers_
;
1435 mutable std::string final_data_
;
1437 // Cancel the final request within MaybeInterceptResponse.
1438 mutable bool cancel_final_request_
;
1440 // Instruct the interceptor to use a real URLRequestHTTPJob.
1441 mutable bool use_url_request_http_job_
;
1443 // These indicate if the interceptor did something or not.
1444 mutable bool did_intercept_main_
;
1445 mutable bool did_restart_main_
;
1446 mutable bool did_cancel_main_
;
1447 mutable bool did_cancel_then_restart_main_
;
1448 mutable bool did_simulate_error_main_
;
1449 mutable bool did_intercept_redirect_
;
1450 mutable bool did_cancel_redirect_
;
1451 mutable bool did_intercept_final_
;
1452 mutable bool did_cancel_final_
;
1455 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1456 class URLRequestInterceptorTest
: public URLRequestTest
{
1458 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL
) {
1461 ~URLRequestInterceptorTest() override
{
1462 // URLRequestJobs may post clean-up tasks on destruction.
1463 base::RunLoop().RunUntilIdle();
1466 void SetUpFactory() override
{
1467 interceptor_
= new MockURLRequestInterceptor();
1468 job_factory_
.reset(new URLRequestInterceptingJobFactory(
1469 job_factory_
.Pass(), make_scoped_ptr(interceptor_
)));
1472 MockURLRequestInterceptor
* interceptor() const {
1473 return interceptor_
;
1477 MockURLRequestInterceptor
* interceptor_
;
1480 TEST_F(URLRequestInterceptorTest
, Intercept
) {
1481 // Intercept the main request and respond with a simple response.
1482 interceptor()->set_intercept_main_request(true);
1483 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1484 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1486 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1487 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1488 base::SupportsUserData::Data
* user_data0
= new base::SupportsUserData::Data();
1489 base::SupportsUserData::Data
* user_data1
= new base::SupportsUserData::Data();
1490 base::SupportsUserData::Data
* user_data2
= new base::SupportsUserData::Data();
1491 req
->SetUserData(nullptr, user_data0
);
1492 req
->SetUserData(&user_data1
, user_data1
);
1493 req
->SetUserData(&user_data2
, user_data2
);
1494 req
->set_method("GET");
1496 base::RunLoop().Run();
1498 // Make sure we can retrieve our specific user data.
1499 EXPECT_EQ(user_data0
, req
->GetUserData(nullptr));
1500 EXPECT_EQ(user_data1
, req
->GetUserData(&user_data1
));
1501 EXPECT_EQ(user_data2
, req
->GetUserData(&user_data2
));
1503 // Check that we got one good response.
1504 EXPECT_TRUE(req
->status().is_success());
1505 EXPECT_EQ(200, req
->response_headers()->response_code());
1506 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d
.data_received());
1507 EXPECT_EQ(1, d
.response_started_count());
1508 EXPECT_EQ(0, d
.received_redirect_count());
1511 TEST_F(URLRequestInterceptorTest
, InterceptRedirect
) {
1512 // Intercept the main request and respond with a redirect.
1513 interceptor()->set_intercept_main_request(true);
1514 interceptor()->set_main_headers(
1515 MockURLRequestInterceptor::redirect_headers());
1516 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1518 // Intercept that redirect and respond with a final OK response.
1519 interceptor()->set_intercept_redirect(true);
1520 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1521 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1524 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1525 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1526 req
->set_method("GET");
1528 base::RunLoop().Run();
1530 // Check that the interceptor got called as expected.
1531 EXPECT_TRUE(interceptor()->did_intercept_main());
1532 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1534 // Check that we got one good response.
1535 EXPECT_TRUE(req
->status().is_success());
1536 if (req
->status().is_success())
1537 EXPECT_EQ(200, req
->response_headers()->response_code());
1539 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d
.data_received());
1540 EXPECT_EQ(1, d
.response_started_count());
1541 EXPECT_EQ(0, d
.received_redirect_count());
1544 TEST_F(URLRequestInterceptorTest
, InterceptServerError
) {
1545 // Intercept the main request to generate a server error response.
1546 interceptor()->set_intercept_main_request(true);
1547 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1548 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1550 // Intercept that error and respond with an OK response.
1551 interceptor()->set_intercept_final_response(true);
1552 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1553 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1556 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1557 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1558 req
->set_method("GET");
1560 base::RunLoop().Run();
1562 // Check that the interceptor got called as expected.
1563 EXPECT_TRUE(interceptor()->did_intercept_main());
1564 EXPECT_TRUE(interceptor()->did_intercept_final());
1566 // Check that we got one good response.
1567 EXPECT_TRUE(req
->status().is_success());
1568 EXPECT_EQ(200, req
->response_headers()->response_code());
1569 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d
.data_received());
1570 EXPECT_EQ(1, d
.response_started_count());
1571 EXPECT_EQ(0, d
.received_redirect_count());
1574 TEST_F(URLRequestInterceptorTest
, InterceptNetworkError
) {
1575 // Intercept the main request to simulate a network error.
1576 interceptor()->set_simulate_main_network_error(true);
1578 // Intercept that error and respond with an OK response.
1579 interceptor()->set_intercept_final_response(true);
1580 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1581 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1584 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1585 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1586 req
->set_method("GET");
1588 base::RunLoop().Run();
1590 // Check that the interceptor got called as expected.
1591 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1592 EXPECT_TRUE(interceptor()->did_intercept_final());
1594 // Check that we received one good response.
1595 EXPECT_TRUE(req
->status().is_success());
1596 EXPECT_EQ(200, req
->response_headers()->response_code());
1597 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d
.data_received());
1598 EXPECT_EQ(1, d
.response_started_count());
1599 EXPECT_EQ(0, d
.received_redirect_count());
1602 TEST_F(URLRequestInterceptorTest
, InterceptRestartRequired
) {
1603 // Restart the main request.
1604 interceptor()->set_restart_main_request(true);
1606 // then intercept the new main request and respond with an OK response
1607 interceptor()->set_intercept_main_request(true);
1608 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1609 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1612 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1613 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1614 req
->set_method("GET");
1616 base::RunLoop().Run();
1618 // Check that the interceptor got called as expected.
1619 EXPECT_TRUE(interceptor()->did_restart_main());
1620 EXPECT_TRUE(interceptor()->did_intercept_main());
1622 // Check that we received one good response.
1623 EXPECT_TRUE(req
->status().is_success());
1624 if (req
->status().is_success())
1625 EXPECT_EQ(200, req
->response_headers()->response_code());
1627 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d
.data_received());
1628 EXPECT_EQ(1, d
.response_started_count());
1629 EXPECT_EQ(0, d
.received_redirect_count());
1632 TEST_F(URLRequestInterceptorTest
, InterceptRespectsCancelMain
) {
1633 // Intercept the main request and cancel from within the restarted job.
1634 interceptor()->set_cancel_main_request(true);
1636 // Set up to intercept the final response and override it with an OK response.
1637 interceptor()->set_intercept_final_response(true);
1638 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1639 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1642 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1643 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1644 req
->set_method("GET");
1646 base::RunLoop().Run();
1648 // Check that the interceptor got called as expected.
1649 EXPECT_TRUE(interceptor()->did_cancel_main());
1650 EXPECT_FALSE(interceptor()->did_intercept_final());
1652 // Check that we see a canceled request.
1653 EXPECT_FALSE(req
->status().is_success());
1654 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1657 TEST_F(URLRequestInterceptorTest
, InterceptRespectsCancelRedirect
) {
1658 // Intercept the main request and respond with a redirect.
1659 interceptor()->set_intercept_main_request(true);
1660 interceptor()->set_main_headers(
1661 MockURLRequestInterceptor::redirect_headers());
1662 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1664 // Intercept the redirect and cancel from within that job.
1665 interceptor()->set_cancel_redirect_request(true);
1667 // Set up to intercept the final response and override it with an OK response.
1668 interceptor()->set_intercept_final_response(true);
1669 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1670 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1673 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1674 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1675 req
->set_method("GET");
1677 base::RunLoop().Run();
1679 // Check that the interceptor got called as expected.
1680 EXPECT_TRUE(interceptor()->did_intercept_main());
1681 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1682 EXPECT_FALSE(interceptor()->did_intercept_final());
1684 // Check that we see a canceled request.
1685 EXPECT_FALSE(req
->status().is_success());
1686 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1689 TEST_F(URLRequestInterceptorTest
, InterceptRespectsCancelFinal
) {
1690 // Intercept the main request to simulate a network error.
1691 interceptor()->set_simulate_main_network_error(true);
1693 // Set up to intercept final the response and cancel from within that job.
1694 interceptor()->set_cancel_final_request(true);
1697 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1698 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1699 req
->set_method("GET");
1701 base::RunLoop().Run();
1703 // Check that the interceptor got called as expected.
1704 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1705 EXPECT_TRUE(interceptor()->did_cancel_final());
1707 // Check that we see a canceled request.
1708 EXPECT_FALSE(req
->status().is_success());
1709 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1712 TEST_F(URLRequestInterceptorTest
, InterceptRespectsCancelInRestart
) {
1713 // Intercept the main request and cancel then restart from within that job.
1714 interceptor()->set_cancel_then_restart_main_request(true);
1716 // Set up to intercept the final response and override it with an OK response.
1717 interceptor()->set_intercept_final_response(true);
1718 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1719 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1722 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
1723 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1724 req
->set_method("GET");
1726 base::RunLoop().Run();
1728 // Check that the interceptor got called as expected.
1729 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1730 EXPECT_FALSE(interceptor()->did_intercept_final());
1732 // Check that we see a canceled request.
1733 EXPECT_FALSE(req
->status().is_success());
1734 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1737 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1738 // reused. |connect_time_flags| is used to indicate if there should be dns
1739 // or SSL times, and |used_proxy| is used for proxy times.
1740 LoadTimingInfo
NormalLoadTimingInfo(base::TimeTicks now
,
1741 int connect_time_flags
,
1743 LoadTimingInfo load_timing
;
1744 load_timing
.socket_log_id
= 1;
1747 load_timing
.proxy_resolve_start
= now
+ base::TimeDelta::FromDays(1);
1748 load_timing
.proxy_resolve_end
= now
+ base::TimeDelta::FromDays(2);
1751 LoadTimingInfo::ConnectTiming
& connect_timing
= load_timing
.connect_timing
;
1752 if (connect_time_flags
& CONNECT_TIMING_HAS_DNS_TIMES
) {
1753 connect_timing
.dns_start
= now
+ base::TimeDelta::FromDays(3);
1754 connect_timing
.dns_end
= now
+ base::TimeDelta::FromDays(4);
1756 connect_timing
.connect_start
= now
+ base::TimeDelta::FromDays(5);
1757 if (connect_time_flags
& CONNECT_TIMING_HAS_SSL_TIMES
) {
1758 connect_timing
.ssl_start
= now
+ base::TimeDelta::FromDays(6);
1759 connect_timing
.ssl_end
= now
+ base::TimeDelta::FromDays(7);
1761 connect_timing
.connect_end
= now
+ base::TimeDelta::FromDays(8);
1763 load_timing
.send_start
= now
+ base::TimeDelta::FromDays(9);
1764 load_timing
.send_end
= now
+ base::TimeDelta::FromDays(10);
1765 load_timing
.receive_headers_end
= now
+ base::TimeDelta::FromDays(11);
1769 // Same as above, but in the case of a reused socket.
1770 LoadTimingInfo
NormalLoadTimingInfoReused(base::TimeTicks now
,
1772 LoadTimingInfo load_timing
;
1773 load_timing
.socket_log_id
= 1;
1774 load_timing
.socket_reused
= true;
1777 load_timing
.proxy_resolve_start
= now
+ base::TimeDelta::FromDays(1);
1778 load_timing
.proxy_resolve_end
= now
+ base::TimeDelta::FromDays(2);
1781 load_timing
.send_start
= now
+ base::TimeDelta::FromDays(9);
1782 load_timing
.send_end
= now
+ base::TimeDelta::FromDays(10);
1783 load_timing
.receive_headers_end
= now
+ base::TimeDelta::FromDays(11);
1787 LoadTimingInfo
RunURLRequestInterceptorLoadTimingTest(
1788 const LoadTimingInfo
& job_load_timing
,
1789 const URLRequestContext
& context
,
1790 MockURLRequestInterceptor
* interceptor
) {
1791 interceptor
->set_intercept_main_request(true);
1792 interceptor
->set_main_request_load_timing_info(job_load_timing
);
1794 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
1795 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
1797 base::RunLoop().Run();
1799 LoadTimingInfo resulting_load_timing
;
1800 req
->GetLoadTimingInfo(&resulting_load_timing
);
1802 // None of these should be modified by the URLRequest.
1803 EXPECT_EQ(job_load_timing
.socket_reused
, resulting_load_timing
.socket_reused
);
1804 EXPECT_EQ(job_load_timing
.socket_log_id
, resulting_load_timing
.socket_log_id
);
1805 EXPECT_EQ(job_load_timing
.send_start
, resulting_load_timing
.send_start
);
1806 EXPECT_EQ(job_load_timing
.send_end
, resulting_load_timing
.send_end
);
1807 EXPECT_EQ(job_load_timing
.receive_headers_end
,
1808 resulting_load_timing
.receive_headers_end
);
1810 return resulting_load_timing
;
1813 // Basic test that the intercept + load timing tests work.
1814 TEST_F(URLRequestInterceptorTest
, InterceptLoadTiming
) {
1815 base::TimeTicks now
= base::TimeTicks::Now();
1816 LoadTimingInfo job_load_timing
=
1817 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_DNS_TIMES
, false);
1819 LoadTimingInfo load_timing_result
=
1820 RunURLRequestInterceptorLoadTimingTest(
1821 job_load_timing
, default_context(), interceptor());
1823 // Nothing should have been changed by the URLRequest.
1824 EXPECT_EQ(job_load_timing
.proxy_resolve_start
,
1825 load_timing_result
.proxy_resolve_start
);
1826 EXPECT_EQ(job_load_timing
.proxy_resolve_end
,
1827 load_timing_result
.proxy_resolve_end
);
1828 EXPECT_EQ(job_load_timing
.connect_timing
.dns_start
,
1829 load_timing_result
.connect_timing
.dns_start
);
1830 EXPECT_EQ(job_load_timing
.connect_timing
.dns_end
,
1831 load_timing_result
.connect_timing
.dns_end
);
1832 EXPECT_EQ(job_load_timing
.connect_timing
.connect_start
,
1833 load_timing_result
.connect_timing
.connect_start
);
1834 EXPECT_EQ(job_load_timing
.connect_timing
.connect_end
,
1835 load_timing_result
.connect_timing
.connect_end
);
1836 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_start
,
1837 load_timing_result
.connect_timing
.ssl_start
);
1838 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_end
,
1839 load_timing_result
.connect_timing
.ssl_end
);
1841 // Redundant sanity check.
1842 TestLoadTimingNotReused(load_timing_result
, CONNECT_TIMING_HAS_DNS_TIMES
);
1845 // Another basic test, with proxy and SSL times, but no DNS times.
1846 TEST_F(URLRequestInterceptorTest
, InterceptLoadTimingProxy
) {
1847 base::TimeTicks now
= base::TimeTicks::Now();
1848 LoadTimingInfo job_load_timing
=
1849 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_SSL_TIMES
, true);
1851 LoadTimingInfo load_timing_result
=
1852 RunURLRequestInterceptorLoadTimingTest(
1853 job_load_timing
, default_context(), interceptor());
1855 // Nothing should have been changed by the URLRequest.
1856 EXPECT_EQ(job_load_timing
.proxy_resolve_start
,
1857 load_timing_result
.proxy_resolve_start
);
1858 EXPECT_EQ(job_load_timing
.proxy_resolve_end
,
1859 load_timing_result
.proxy_resolve_end
);
1860 EXPECT_EQ(job_load_timing
.connect_timing
.dns_start
,
1861 load_timing_result
.connect_timing
.dns_start
);
1862 EXPECT_EQ(job_load_timing
.connect_timing
.dns_end
,
1863 load_timing_result
.connect_timing
.dns_end
);
1864 EXPECT_EQ(job_load_timing
.connect_timing
.connect_start
,
1865 load_timing_result
.connect_timing
.connect_start
);
1866 EXPECT_EQ(job_load_timing
.connect_timing
.connect_end
,
1867 load_timing_result
.connect_timing
.connect_end
);
1868 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_start
,
1869 load_timing_result
.connect_timing
.ssl_start
);
1870 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_end
,
1871 load_timing_result
.connect_timing
.ssl_end
);
1873 // Redundant sanity check.
1874 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1875 CONNECT_TIMING_HAS_SSL_TIMES
);
1878 // Make sure that URLRequest correctly adjusts proxy times when they're before
1879 // |request_start|, due to already having a connected socket. This happens in
1880 // the case of reusing a SPDY session. The connected socket is not considered
1881 // reused in this test (May be a preconnect).
1883 // To mix things up from the test above, assumes DNS times but no SSL times.
1884 TEST_F(URLRequestInterceptorTest
, InterceptLoadTimingEarlyProxyResolution
) {
1885 base::TimeTicks now
= base::TimeTicks::Now();
1886 LoadTimingInfo job_load_timing
=
1887 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_DNS_TIMES
, true);
1888 job_load_timing
.proxy_resolve_start
= now
- base::TimeDelta::FromDays(6);
1889 job_load_timing
.proxy_resolve_end
= now
- base::TimeDelta::FromDays(5);
1890 job_load_timing
.connect_timing
.dns_start
= now
- base::TimeDelta::FromDays(4);
1891 job_load_timing
.connect_timing
.dns_end
= now
- base::TimeDelta::FromDays(3);
1892 job_load_timing
.connect_timing
.connect_start
=
1893 now
- base::TimeDelta::FromDays(2);
1894 job_load_timing
.connect_timing
.connect_end
=
1895 now
- base::TimeDelta::FromDays(1);
1897 LoadTimingInfo load_timing_result
=
1898 RunURLRequestInterceptorLoadTimingTest(
1899 job_load_timing
, default_context(), interceptor());
1901 // Proxy times, connect times, and DNS times should all be replaced with
1903 EXPECT_EQ(load_timing_result
.request_start
,
1904 load_timing_result
.proxy_resolve_start
);
1905 EXPECT_EQ(load_timing_result
.request_start
,
1906 load_timing_result
.proxy_resolve_end
);
1907 EXPECT_EQ(load_timing_result
.request_start
,
1908 load_timing_result
.connect_timing
.dns_start
);
1909 EXPECT_EQ(load_timing_result
.request_start
,
1910 load_timing_result
.connect_timing
.dns_end
);
1911 EXPECT_EQ(load_timing_result
.request_start
,
1912 load_timing_result
.connect_timing
.connect_start
);
1913 EXPECT_EQ(load_timing_result
.request_start
,
1914 load_timing_result
.connect_timing
.connect_end
);
1916 // Other times should have been left null.
1917 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1918 CONNECT_TIMING_HAS_DNS_TIMES
);
1921 // Same as above, but in the reused case.
1922 TEST_F(URLRequestInterceptorTest
,
1923 InterceptLoadTimingEarlyProxyResolutionReused
) {
1924 base::TimeTicks now
= base::TimeTicks::Now();
1925 LoadTimingInfo job_load_timing
= NormalLoadTimingInfoReused(now
, true);
1926 job_load_timing
.proxy_resolve_start
= now
- base::TimeDelta::FromDays(4);
1927 job_load_timing
.proxy_resolve_end
= now
- base::TimeDelta::FromDays(3);
1929 LoadTimingInfo load_timing_result
=
1930 RunURLRequestInterceptorLoadTimingTest(
1931 job_load_timing
, default_context(), interceptor());
1933 // Proxy times and connect times should all be replaced with request_start.
1934 EXPECT_EQ(load_timing_result
.request_start
,
1935 load_timing_result
.proxy_resolve_start
);
1936 EXPECT_EQ(load_timing_result
.request_start
,
1937 load_timing_result
.proxy_resolve_end
);
1939 // Other times should have been left null.
1940 TestLoadTimingReusedWithProxy(load_timing_result
);
1943 // Make sure that URLRequest correctly adjusts connect times when they're before
1944 // |request_start|, due to reusing a connected socket. The connected socket is
1945 // not considered reused in this test (May be a preconnect).
1947 // To mix things up, the request has SSL times, but no DNS times.
1948 TEST_F(URLRequestInterceptorTest
, InterceptLoadTimingEarlyConnect
) {
1949 base::TimeTicks now
= base::TimeTicks::Now();
1950 LoadTimingInfo job_load_timing
=
1951 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_SSL_TIMES
, false);
1952 job_load_timing
.connect_timing
.connect_start
=
1953 now
- base::TimeDelta::FromDays(1);
1954 job_load_timing
.connect_timing
.ssl_start
= now
- base::TimeDelta::FromDays(2);
1955 job_load_timing
.connect_timing
.ssl_end
= now
- base::TimeDelta::FromDays(3);
1956 job_load_timing
.connect_timing
.connect_end
=
1957 now
- base::TimeDelta::FromDays(4);
1959 LoadTimingInfo load_timing_result
=
1960 RunURLRequestInterceptorLoadTimingTest(
1961 job_load_timing
, default_context(), interceptor());
1963 // Connect times, and SSL times should be replaced with request_start.
1964 EXPECT_EQ(load_timing_result
.request_start
,
1965 load_timing_result
.connect_timing
.connect_start
);
1966 EXPECT_EQ(load_timing_result
.request_start
,
1967 load_timing_result
.connect_timing
.ssl_start
);
1968 EXPECT_EQ(load_timing_result
.request_start
,
1969 load_timing_result
.connect_timing
.ssl_end
);
1970 EXPECT_EQ(load_timing_result
.request_start
,
1971 load_timing_result
.connect_timing
.connect_end
);
1973 // Other times should have been left null.
1974 TestLoadTimingNotReused(load_timing_result
, CONNECT_TIMING_HAS_SSL_TIMES
);
1977 // Make sure that URLRequest correctly adjusts connect times when they're before
1978 // |request_start|, due to reusing a connected socket in the case that there
1979 // are also proxy times. The connected socket is not considered reused in this
1980 // test (May be a preconnect).
1982 // In this test, there are no SSL or DNS times.
1983 TEST_F(URLRequestInterceptorTest
, InterceptLoadTimingEarlyConnectWithProxy
) {
1984 base::TimeTicks now
= base::TimeTicks::Now();
1985 LoadTimingInfo job_load_timing
=
1986 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY
, true);
1987 job_load_timing
.connect_timing
.connect_start
=
1988 now
- base::TimeDelta::FromDays(1);
1989 job_load_timing
.connect_timing
.connect_end
=
1990 now
- base::TimeDelta::FromDays(2);
1992 LoadTimingInfo load_timing_result
=
1993 RunURLRequestInterceptorLoadTimingTest(
1994 job_load_timing
, default_context(), interceptor());
1996 // Connect times should be replaced with proxy_resolve_end.
1997 EXPECT_EQ(load_timing_result
.proxy_resolve_end
,
1998 load_timing_result
.connect_timing
.connect_start
);
1999 EXPECT_EQ(load_timing_result
.proxy_resolve_end
,
2000 load_timing_result
.connect_timing
.connect_end
);
2002 // Other times should have been left null.
2003 TestLoadTimingNotReusedWithProxy(load_timing_result
,
2004 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY
);
2007 // Check that two different URL requests have different identifiers.
2008 TEST_F(URLRequestTest
, Identifiers
) {
2010 TestURLRequestContext context
;
2011 scoped_ptr
<URLRequest
> req(
2012 context
.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY
, &d
));
2013 scoped_ptr
<URLRequest
> other_req(
2014 context
.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY
, &d
));
2016 ASSERT_NE(req
->identifier(), other_req
->identifier());
2019 // Check that a failure to connect to the proxy is reported to the network
2021 TEST_F(URLRequestTest
, NetworkDelegateProxyError
) {
2022 MockHostResolver host_resolver
;
2023 host_resolver
.rules()->AddSimulatedFailure("*");
2025 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
2026 TestURLRequestContextWithProxy
context("myproxy:70", &network_delegate
);
2029 scoped_ptr
<URLRequest
> req(
2030 context
.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY
, &d
));
2031 req
->set_method("GET");
2034 base::RunLoop().Run();
2036 // Check we see a failed request.
2037 EXPECT_FALSE(req
->status().is_success());
2038 // The proxy server is not set before failure.
2039 EXPECT_TRUE(req
->proxy_server().IsEmpty());
2040 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
2041 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED
, req
->status().error());
2043 EXPECT_EQ(1, network_delegate
.error_count());
2044 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED
, network_delegate
.last_error());
2045 EXPECT_EQ(1, network_delegate
.completed_requests());
2048 // Make sure that NetworkDelegate::NotifyCompleted is called if
2049 // content is empty.
2050 TEST_F(URLRequestTest
, RequestCompletionForEmptyResponse
) {
2052 scoped_ptr
<URLRequest
> req(
2053 default_context_
.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY
, &d
));
2055 base::RunLoop().Run();
2056 EXPECT_EQ("", d
.data_received());
2057 EXPECT_EQ(1, default_network_delegate_
.completed_requests());
2060 // Make sure that SetPriority actually sets the URLRequest's priority
2061 // correctly, both before and after start.
2062 TEST_F(URLRequestTest
, SetPriorityBasic
) {
2064 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2065 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
2066 EXPECT_EQ(DEFAULT_PRIORITY
, req
->priority());
2068 req
->SetPriority(LOW
);
2069 EXPECT_EQ(LOW
, req
->priority());
2072 EXPECT_EQ(LOW
, req
->priority());
2074 req
->SetPriority(MEDIUM
);
2075 EXPECT_EQ(MEDIUM
, req
->priority());
2078 // Make sure that URLRequest calls SetPriority on a job before calling
2080 TEST_F(URLRequestTest
, SetJobPriorityBeforeJobStart
) {
2082 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2083 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
2084 EXPECT_EQ(DEFAULT_PRIORITY
, req
->priority());
2086 scoped_refptr
<URLRequestTestJob
> job
=
2087 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
2088 AddTestInterceptor()->set_main_intercept_job(job
.get());
2089 EXPECT_EQ(DEFAULT_PRIORITY
, job
->priority());
2091 req
->SetPriority(LOW
);
2094 EXPECT_EQ(LOW
, job
->priority());
2097 // Make sure that URLRequest passes on its priority updates to its
2099 TEST_F(URLRequestTest
, SetJobPriority
) {
2101 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2102 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
2104 scoped_refptr
<URLRequestTestJob
> job
=
2105 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
2106 AddTestInterceptor()->set_main_intercept_job(job
.get());
2108 req
->SetPriority(LOW
);
2110 EXPECT_EQ(LOW
, job
->priority());
2112 req
->SetPriority(MEDIUM
);
2113 EXPECT_EQ(MEDIUM
, req
->priority());
2114 EXPECT_EQ(MEDIUM
, job
->priority());
2117 // Setting the IGNORE_LIMITS load flag should be okay if the priority
2118 // is MAXIMUM_PRIORITY.
2119 TEST_F(URLRequestTest
, PriorityIgnoreLimits
) {
2121 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2122 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY
, &d
));
2123 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
2125 scoped_refptr
<URLRequestTestJob
> job
=
2126 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
2127 AddTestInterceptor()->set_main_intercept_job(job
.get());
2129 req
->SetLoadFlags(LOAD_IGNORE_LIMITS
);
2130 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
2132 req
->SetPriority(MAXIMUM_PRIORITY
);
2133 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
2136 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
2137 EXPECT_EQ(MAXIMUM_PRIORITY
, job
->priority());
2140 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
2141 #if !defined(OS_IOS)
2144 // Less verbose way of running a simple testserver for the tests below.
2145 class LocalHttpTestServer
: public SpawnedTestServer
{
2147 explicit LocalHttpTestServer(const base::FilePath
& document_root
)
2148 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP
,
2149 SpawnedTestServer::kLocalhost
,
2151 LocalHttpTestServer()
2152 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP
,
2153 SpawnedTestServer::kLocalhost
,
2154 base::FilePath()) {}
2159 TEST_F(URLRequestTest
, DelayedCookieCallback
) {
2160 LocalHttpTestServer test_server
;
2161 ASSERT_TRUE(test_server
.Start());
2163 TestURLRequestContext context
;
2164 scoped_refptr
<DelayedCookieMonster
> delayed_cm
=
2165 new DelayedCookieMonster();
2166 scoped_refptr
<CookieStore
> cookie_store
= delayed_cm
;
2167 context
.set_cookie_store(delayed_cm
.get());
2171 TestNetworkDelegate network_delegate
;
2172 context
.set_network_delegate(&network_delegate
);
2174 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
2175 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2178 base::RunLoop().Run();
2179 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2180 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2181 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2184 // Verify that the cookie is set.
2186 TestNetworkDelegate network_delegate
;
2187 context
.set_network_delegate(&network_delegate
);
2189 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
2190 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2192 base::RunLoop().Run();
2194 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2195 != std::string::npos
);
2196 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2197 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2201 TEST_F(URLRequestTest
, DoNotSendCookies
) {
2202 LocalHttpTestServer test_server
;
2203 ASSERT_TRUE(test_server
.Start());
2207 TestNetworkDelegate network_delegate
;
2208 default_context_
.set_network_delegate(&network_delegate
);
2210 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2211 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2214 base::RunLoop().Run();
2215 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2216 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2219 // Verify that the cookie is set.
2221 TestNetworkDelegate network_delegate
;
2222 default_context_
.set_network_delegate(&network_delegate
);
2224 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2225 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2227 base::RunLoop().Run();
2229 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2230 != std::string::npos
);
2231 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2232 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2235 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2237 TestNetworkDelegate network_delegate
;
2238 default_context_
.set_network_delegate(&network_delegate
);
2240 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2241 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2242 req
->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES
);
2244 base::RunLoop().Run();
2246 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2247 == std::string::npos
);
2249 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2250 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2251 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2255 TEST_F(URLRequestTest
, DoNotSaveCookies
) {
2256 LocalHttpTestServer test_server
;
2257 ASSERT_TRUE(test_server
.Start());
2261 TestNetworkDelegate network_delegate
;
2262 default_context_
.set_network_delegate(&network_delegate
);
2264 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2265 test_server
.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY
,
2268 base::RunLoop().Run();
2270 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2271 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2272 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2275 // Try to set-up another cookie and update the previous cookie.
2277 TestNetworkDelegate network_delegate
;
2278 default_context_
.set_network_delegate(&network_delegate
);
2280 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2281 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2282 DEFAULT_PRIORITY
, &d
));
2283 req
->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES
);
2286 base::RunLoop().Run();
2288 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2289 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2290 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2291 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2294 // Verify the cookies weren't saved or updated.
2296 TestNetworkDelegate network_delegate
;
2297 default_context_
.set_network_delegate(&network_delegate
);
2299 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2300 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2302 base::RunLoop().Run();
2304 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2305 == std::string::npos
);
2306 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2307 != std::string::npos
);
2309 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2310 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2311 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2315 TEST_F(URLRequestTest
, DoNotSendCookies_ViaPolicy
) {
2316 LocalHttpTestServer test_server
;
2317 ASSERT_TRUE(test_server
.Start());
2321 TestNetworkDelegate network_delegate
;
2322 default_context_
.set_network_delegate(&network_delegate
);
2324 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2325 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2328 base::RunLoop().Run();
2330 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2331 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2334 // Verify that the cookie is set.
2336 TestNetworkDelegate network_delegate
;
2337 default_context_
.set_network_delegate(&network_delegate
);
2339 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2340 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2342 base::RunLoop().Run();
2344 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2345 != std::string::npos
);
2347 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2348 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2351 // Verify that the cookie isn't sent.
2353 TestNetworkDelegate network_delegate
;
2354 default_context_
.set_network_delegate(&network_delegate
);
2356 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES
);
2357 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2358 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2360 base::RunLoop().Run();
2362 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2363 == std::string::npos
);
2365 EXPECT_EQ(1, network_delegate
.blocked_get_cookies_count());
2366 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2370 TEST_F(URLRequestTest
, DoNotSaveCookies_ViaPolicy
) {
2371 LocalHttpTestServer test_server
;
2372 ASSERT_TRUE(test_server
.Start());
2376 TestNetworkDelegate network_delegate
;
2377 default_context_
.set_network_delegate(&network_delegate
);
2379 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2380 test_server
.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY
,
2383 base::RunLoop().Run();
2385 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2386 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2389 // Try to set-up another cookie and update the previous cookie.
2391 TestNetworkDelegate network_delegate
;
2392 default_context_
.set_network_delegate(&network_delegate
);
2394 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE
);
2395 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2396 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2397 DEFAULT_PRIORITY
, &d
));
2400 base::RunLoop().Run();
2402 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2403 EXPECT_EQ(2, network_delegate
.blocked_set_cookie_count());
2406 // Verify the cookies weren't saved or updated.
2408 TestNetworkDelegate network_delegate
;
2409 default_context_
.set_network_delegate(&network_delegate
);
2411 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2412 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2414 base::RunLoop().Run();
2416 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2417 == std::string::npos
);
2418 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2419 != std::string::npos
);
2421 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2422 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2426 TEST_F(URLRequestTest
, DoNotSaveEmptyCookies
) {
2427 LocalHttpTestServer test_server
;
2428 ASSERT_TRUE(test_server
.Start());
2430 // Set up an empty cookie.
2432 TestNetworkDelegate network_delegate
;
2433 default_context_
.set_network_delegate(&network_delegate
);
2435 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2436 test_server
.GetURL("set-cookie"), DEFAULT_PRIORITY
, &d
));
2438 base::RunLoop().Run();
2440 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2441 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2442 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2446 TEST_F(URLRequestTest
, DoNotSendCookies_ViaPolicy_Async
) {
2447 LocalHttpTestServer test_server
;
2448 ASSERT_TRUE(test_server
.Start());
2452 TestNetworkDelegate network_delegate
;
2453 default_context_
.set_network_delegate(&network_delegate
);
2455 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2456 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2459 base::RunLoop().Run();
2461 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2462 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2465 // Verify that the cookie is set.
2467 TestNetworkDelegate network_delegate
;
2468 default_context_
.set_network_delegate(&network_delegate
);
2470 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2471 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2473 base::RunLoop().Run();
2475 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2476 != std::string::npos
);
2478 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2479 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2482 // Verify that the cookie isn't sent.
2484 TestNetworkDelegate network_delegate
;
2485 default_context_
.set_network_delegate(&network_delegate
);
2487 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES
);
2488 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2489 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2491 base::RunLoop().Run();
2493 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2494 == std::string::npos
);
2496 EXPECT_EQ(1, network_delegate
.blocked_get_cookies_count());
2497 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2501 TEST_F(URLRequestTest
, DoNotSaveCookies_ViaPolicy_Async
) {
2502 LocalHttpTestServer test_server
;
2503 ASSERT_TRUE(test_server
.Start());
2507 TestNetworkDelegate network_delegate
;
2508 default_context_
.set_network_delegate(&network_delegate
);
2510 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2511 test_server
.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY
,
2514 base::RunLoop().Run();
2516 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2517 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2520 // Try to set-up another cookie and update the previous cookie.
2522 TestNetworkDelegate network_delegate
;
2523 default_context_
.set_network_delegate(&network_delegate
);
2525 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE
);
2526 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2527 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2528 DEFAULT_PRIORITY
, &d
));
2531 base::RunLoop().Run();
2533 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2534 EXPECT_EQ(2, network_delegate
.blocked_set_cookie_count());
2537 // Verify the cookies weren't saved or updated.
2539 TestNetworkDelegate network_delegate
;
2540 default_context_
.set_network_delegate(&network_delegate
);
2542 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2543 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2545 base::RunLoop().Run();
2547 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2548 == std::string::npos
);
2549 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2550 != std::string::npos
);
2552 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2553 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2557 TEST_F(URLRequestTest
, FirstPartyOnlyCookiesEnabled
) {
2558 LocalHttpTestServer test_server
;
2559 ASSERT_TRUE(test_server
.Start());
2561 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2562 // LocalHttpTestServer points).
2564 TestNetworkDelegate network_delegate
;
2565 network_delegate
.set_first_party_only_cookies_enabled(true);
2566 default_context_
.set_network_delegate(&network_delegate
);
2569 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2571 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2572 DEFAULT_PRIORITY
, &d
));
2574 base::RunLoop().Run();
2575 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2576 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2577 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2580 // Verify that the cookie is sent for first-party requests.
2582 TestNetworkDelegate network_delegate
;
2583 network_delegate
.set_first_party_only_cookies_enabled(true);
2584 default_context_
.set_network_delegate(&network_delegate
);
2586 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2587 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2588 req
->set_first_party_for_cookies(test_server
.GetURL(""));
2590 base::RunLoop().Run();
2592 EXPECT_TRUE(d
.data_received().find("FirstPartyCookieToSet=1") !=
2594 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2595 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2598 // Verify that the cookie is not-sent for non-first-party requests.
2600 TestNetworkDelegate network_delegate
;
2601 network_delegate
.set_first_party_only_cookies_enabled(true);
2602 default_context_
.set_network_delegate(&network_delegate
);
2604 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2605 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2606 req
->set_first_party_for_cookies(GURL("http://third-party.test/"));
2608 base::RunLoop().Run();
2610 EXPECT_TRUE(d
.data_received().find("FirstPartyCookieToSet=1") ==
2612 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2613 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2617 TEST_F(URLRequestTest
, FirstPartyOnlyCookiesDisabled
) {
2618 LocalHttpTestServer test_server
;
2619 ASSERT_TRUE(test_server
.Start());
2621 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2622 // LocalHttpTestServer points).
2624 TestNetworkDelegate network_delegate
;
2625 network_delegate
.set_first_party_only_cookies_enabled(false);
2626 default_context_
.set_network_delegate(&network_delegate
);
2629 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2631 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2632 DEFAULT_PRIORITY
, &d
));
2634 base::RunLoop().Run();
2635 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2636 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2637 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2640 // Verify that the cookie is sent for first-party requests.
2642 TestNetworkDelegate network_delegate
;
2643 network_delegate
.set_first_party_only_cookies_enabled(false);
2644 default_context_
.set_network_delegate(&network_delegate
);
2646 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2647 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2648 req
->set_first_party_for_cookies(test_server
.GetURL(""));
2650 base::RunLoop().Run();
2652 EXPECT_TRUE(d
.data_received().find("FirstPartyCookieToSet=1") !=
2654 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2655 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2658 // Verify that the cookie is also sent for non-first-party requests.
2660 TestNetworkDelegate network_delegate
;
2661 network_delegate
.set_first_party_only_cookies_enabled(false);
2662 default_context_
.set_network_delegate(&network_delegate
);
2664 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2665 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2666 req
->set_first_party_for_cookies(GURL("http://third-party.test/"));
2668 base::RunLoop().Run();
2670 EXPECT_TRUE(d
.data_received().find("FirstPartyCookieToSet=1") !=
2672 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2673 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2677 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2678 // value for the |fixed_date| argument given to the constructor.
2679 class FixedDateNetworkDelegate
: public TestNetworkDelegate
{
2681 explicit FixedDateNetworkDelegate(const std::string
& fixed_date
)
2682 : fixed_date_(fixed_date
) {}
2683 ~FixedDateNetworkDelegate() override
{}
2685 // NetworkDelegate implementation
2686 int OnHeadersReceived(
2687 URLRequest
* request
,
2688 const CompletionCallback
& callback
,
2689 const HttpResponseHeaders
* original_response_headers
,
2690 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
2691 GURL
* allowed_unsafe_redirect_url
) override
;
2694 std::string fixed_date_
;
2696 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate
);
2699 int FixedDateNetworkDelegate::OnHeadersReceived(
2700 URLRequest
* request
,
2701 const CompletionCallback
& callback
,
2702 const HttpResponseHeaders
* original_response_headers
,
2703 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
2704 GURL
* allowed_unsafe_redirect_url
) {
2705 HttpResponseHeaders
* new_response_headers
=
2706 new HttpResponseHeaders(original_response_headers
->raw_headers());
2708 new_response_headers
->RemoveHeader("Date");
2709 new_response_headers
->AddHeader("Date: " + fixed_date_
);
2711 *override_response_headers
= new_response_headers
;
2712 return TestNetworkDelegate::OnHeadersReceived(request
,
2714 original_response_headers
,
2715 override_response_headers
,
2716 allowed_unsafe_redirect_url
);
2719 // Test that cookie expiration times are adjusted for server/client clock
2720 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2721 // headers by defaulting to GMT. (crbug.com/135131)
2722 TEST_F(URLRequestTest
, AcceptClockSkewCookieWithWrongDateTimezone
) {
2723 LocalHttpTestServer test_server
;
2724 ASSERT_TRUE(test_server
.Start());
2726 // Set up an expired cookie.
2728 TestNetworkDelegate network_delegate
;
2729 default_context_
.set_network_delegate(&network_delegate
);
2731 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2733 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2734 DEFAULT_PRIORITY
, &d
));
2736 base::RunLoop().Run();
2738 // Verify that the cookie is not set.
2740 TestNetworkDelegate network_delegate
;
2741 default_context_
.set_network_delegate(&network_delegate
);
2743 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2744 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2746 base::RunLoop().Run();
2748 EXPECT_TRUE(d
.data_received().find("StillGood=1") == std::string::npos
);
2750 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2752 FixedDateNetworkDelegate
network_delegate("18-Apr-1977 22:49:13 UTC");
2753 default_context_
.set_network_delegate(&network_delegate
);
2755 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2757 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2758 DEFAULT_PRIORITY
, &d
));
2760 base::RunLoop().Run();
2762 // Verify that the cookie is set.
2764 TestNetworkDelegate network_delegate
;
2765 default_context_
.set_network_delegate(&network_delegate
);
2767 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2768 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
));
2770 base::RunLoop().Run();
2772 EXPECT_TRUE(d
.data_received().find("StillGood=1") != std::string::npos
);
2777 // Check that it is impossible to change the referrer in the extra headers of
2779 TEST_F(URLRequestTest
, DoNotOverrideReferrer
) {
2780 LocalHttpTestServer test_server
;
2781 ASSERT_TRUE(test_server
.Start());
2783 // If extra headers contain referer and the request contains a referer,
2784 // only the latter shall be respected.
2787 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2788 test_server
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
));
2789 req
->SetReferrer("http://foo.com/");
2791 HttpRequestHeaders headers
;
2792 headers
.SetHeader(HttpRequestHeaders::kReferer
, "http://bar.com/");
2793 req
->SetExtraRequestHeaders(headers
);
2796 base::RunLoop().Run();
2798 EXPECT_EQ("http://foo.com/", d
.data_received());
2801 // If extra headers contain a referer but the request does not, no referer
2802 // shall be sent in the header.
2805 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2806 test_server
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
));
2808 HttpRequestHeaders headers
;
2809 headers
.SetHeader(HttpRequestHeaders::kReferer
, "http://bar.com/");
2810 req
->SetExtraRequestHeaders(headers
);
2811 req
->SetLoadFlags(LOAD_VALIDATE_CACHE
);
2814 base::RunLoop().Run();
2816 EXPECT_EQ("None", d
.data_received());
2820 class URLRequestTestHTTP
: public URLRequestTest
{
2822 URLRequestTestHTTP()
2823 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2824 "net/data/url_request_unittest"))) {
2828 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2829 // |request_method| is the method to use for the initial request.
2830 // |redirect_method| is the method that is expected to be used for the second
2831 // request, after redirection.
2832 // If |include_data| is true, data is uploaded with the request. The
2833 // response body is expected to match it exactly, if and only if
2834 // |request_method| == |redirect_method|.
2835 void HTTPRedirectMethodTest(const GURL
& redirect_url
,
2836 const std::string
& request_method
,
2837 const std::string
& redirect_method
,
2838 bool include_data
) {
2839 static const char kData
[] = "hello world";
2841 scoped_ptr
<URLRequest
> req(
2842 default_context_
.CreateRequest(redirect_url
, DEFAULT_PRIORITY
, &d
));
2843 req
->set_method(request_method
);
2845 req
->set_upload(CreateSimpleUploadData(kData
));
2846 HttpRequestHeaders headers
;
2847 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
2848 base::UintToString(arraysize(kData
) - 1));
2849 req
->SetExtraRequestHeaders(headers
);
2852 base::RunLoop().Run();
2853 EXPECT_EQ(redirect_method
, req
->method());
2854 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
2855 EXPECT_EQ(OK
, req
->status().error());
2857 if (request_method
== redirect_method
) {
2858 EXPECT_EQ(kData
, d
.data_received());
2860 EXPECT_NE(kData
, d
.data_received());
2864 LOG(WARNING
) << "Request method was: " << request_method
;
2867 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2868 // |request_method| is the method to use for the initial request.
2869 // |redirect_method| is the method that is expected to be used for the second
2870 // request, after redirection.
2871 // |origin_value| is the expected value for the Origin header after
2872 // redirection. If empty, expects that there will be no Origin header.
2873 void HTTPRedirectOriginHeaderTest(const GURL
& redirect_url
,
2874 const std::string
& request_method
,
2875 const std::string
& redirect_method
,
2876 const std::string
& origin_value
) {
2878 scoped_ptr
<URLRequest
> req(
2879 default_context_
.CreateRequest(redirect_url
, DEFAULT_PRIORITY
, &d
));
2880 req
->set_method(request_method
);
2881 req
->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin
,
2882 redirect_url
.GetOrigin().spec(), false);
2885 base::RunLoop().Run();
2887 EXPECT_EQ(redirect_method
, req
->method());
2888 // Note that there is no check for request success here because, for
2889 // purposes of testing, the request very well may fail. For example, if the
2890 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
2891 // origin, there is not an HTTPS server in this unit test framework, so the
2892 // request would fail. However, that's fine, as long as the request headers
2893 // are in order and pass the checks below.
2894 if (origin_value
.empty()) {
2896 req
->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin
));
2898 std::string origin_header
;
2899 EXPECT_TRUE(req
->extra_request_headers().GetHeader(
2900 HttpRequestHeaders::kOrigin
, &origin_header
));
2901 EXPECT_EQ(origin_value
, origin_header
);
2905 void HTTPUploadDataOperationTest(const std::string
& method
) {
2906 const int kMsgSize
= 20000; // multiple of 10
2907 const int kIterations
= 50;
2908 char* uploadBytes
= new char[kMsgSize
+1];
2909 char* ptr
= uploadBytes
;
2911 for (int idx
= 0; idx
< kMsgSize
/10; idx
++) {
2912 memcpy(ptr
, "----------", 10);
2914 if (idx
% 100 == 0) {
2921 uploadBytes
[kMsgSize
] = '\0';
2923 for (int i
= 0; i
< kIterations
; ++i
) {
2925 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
2926 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
));
2927 r
->set_method(method
.c_str());
2929 r
->set_upload(CreateSimpleUploadData(uploadBytes
));
2932 EXPECT_TRUE(r
->is_pending());
2934 base::RunLoop().Run();
2936 ASSERT_EQ(1, d
.response_started_count())
2937 << "request failed: " << r
->status().status()
2938 << ", os error: " << r
->status().error();
2940 EXPECT_FALSE(d
.received_data_before_response());
2941 EXPECT_EQ(uploadBytes
, d
.data_received());
2943 delete[] uploadBytes
;
2946 void AddChunksToUpload(URLRequest
* r
) {
2947 r
->AppendChunkToUpload("a", 1, false);
2948 r
->AppendChunkToUpload("bcd", 3, false);
2949 r
->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2950 r
->AppendChunkToUpload("\r\n\r\n", 4, false);
2951 r
->AppendChunkToUpload("0", 1, false);
2952 r
->AppendChunkToUpload("2323", 4, true);
2955 void VerifyReceivedDataMatchesChunks(URLRequest
* r
, TestDelegate
* d
) {
2956 // This should match the chunks sent by AddChunksToUpload().
2957 const std::string expected_data
=
2958 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2960 ASSERT_EQ(1, d
->response_started_count())
2961 << "request failed: " << r
->status().status()
2962 << ", os error: " << r
->status().error();
2964 EXPECT_FALSE(d
->received_data_before_response());
2966 EXPECT_EQ(expected_data
.size(), static_cast<size_t>(d
->bytes_received()));
2967 EXPECT_EQ(expected_data
, d
->data_received());
2970 bool DoManyCookiesRequest(int num_cookies
) {
2972 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
2973 test_server_
.GetURL("set-many-cookies?" +
2974 base::IntToString(num_cookies
)),
2975 DEFAULT_PRIORITY
, &d
));
2978 EXPECT_TRUE(r
->is_pending());
2980 base::RunLoop().Run();
2982 bool is_success
= r
->status().is_success();
2985 EXPECT_TRUE(r
->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG
);
2986 // The test server appears to be unable to handle subsequent requests
2987 // after this error is triggered. Force it to restart.
2988 EXPECT_TRUE(test_server_
.Stop());
2989 EXPECT_TRUE(test_server_
.Start());
2995 LocalHttpTestServer
* test_server() {
2996 return &test_server_
;
3000 LocalHttpTestServer test_server_
;
3003 // In this unit test, we're using the HTTPTestServer as a proxy server and
3004 // issuing a CONNECT request with the magic host name "www.redirect.com".
3005 // The HTTPTestServer will return a 302 response, which we should not
3007 TEST_F(URLRequestTestHTTP
, ProxyTunnelRedirectTest
) {
3008 ASSERT_TRUE(test_server_
.Start());
3010 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
3011 TestURLRequestContextWithProxy
context(
3012 test_server_
.host_port_pair().ToString(), &network_delegate
);
3016 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3017 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY
, &d
));
3019 EXPECT_TRUE(r
->is_pending());
3021 base::RunLoop().Run();
3023 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
3024 // The proxy server is not set before failure.
3025 EXPECT_TRUE(r
->proxy_server().IsEmpty());
3026 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
->status().error());
3027 EXPECT_EQ(1, d
.response_started_count());
3028 // We should not have followed the redirect.
3029 EXPECT_EQ(0, d
.received_redirect_count());
3033 // This is the same as the previous test, but checks that the network delegate
3034 // registers the error.
3035 TEST_F(URLRequestTestHTTP
, NetworkDelegateTunnelConnectionFailed
) {
3036 ASSERT_TRUE(test_server_
.Start());
3038 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
3039 TestURLRequestContextWithProxy
context(
3040 test_server_
.host_port_pair().ToString(), &network_delegate
);
3044 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3045 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY
, &d
));
3047 EXPECT_TRUE(r
->is_pending());
3049 base::RunLoop().Run();
3051 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
3052 // The proxy server is not set before failure.
3053 EXPECT_TRUE(r
->proxy_server().IsEmpty());
3054 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
->status().error());
3055 EXPECT_EQ(1, d
.response_started_count());
3056 // We should not have followed the redirect.
3057 EXPECT_EQ(0, d
.received_redirect_count());
3059 EXPECT_EQ(1, network_delegate
.error_count());
3060 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, network_delegate
.last_error());
3064 // Tests that we can block and asynchronously return OK in various stages.
3065 TEST_F(URLRequestTestHTTP
, NetworkDelegateBlockAsynchronously
) {
3066 static const BlockingNetworkDelegate::Stage blocking_stages
[] = {
3067 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
3068 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
3069 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3071 static const size_t blocking_stages_length
= arraysize(blocking_stages
);
3073 ASSERT_TRUE(test_server_
.Start());
3076 BlockingNetworkDelegate
network_delegate(
3077 BlockingNetworkDelegate::USER_CALLBACK
);
3078 network_delegate
.set_block_on(
3079 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
|
3080 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
|
3081 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
3083 TestURLRequestContext
context(true);
3084 context
.set_network_delegate(&network_delegate
);
3088 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3089 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
));
3092 for (size_t i
= 0; i
< blocking_stages_length
; ++i
) {
3093 base::RunLoop().Run();
3094 EXPECT_EQ(blocking_stages
[i
],
3095 network_delegate
.stage_blocked_for_callback());
3096 network_delegate
.DoCallback(OK
);
3098 base::RunLoop().Run();
3099 EXPECT_EQ(200, r
->GetResponseCode());
3100 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3101 EXPECT_EQ(1, network_delegate
.created_requests());
3102 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3104 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3107 // Tests that the network delegate can block and cancel a request.
3108 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequest
) {
3109 ASSERT_TRUE(test_server_
.Start());
3112 BlockingNetworkDelegate
network_delegate(
3113 BlockingNetworkDelegate::AUTO_CALLBACK
);
3114 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3115 network_delegate
.set_retval(ERR_EMPTY_RESPONSE
);
3117 TestURLRequestContextWithProxy
context(
3118 test_server_
.host_port_pair().ToString(), &network_delegate
);
3121 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3122 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
3125 base::RunLoop().Run();
3127 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
3128 // The proxy server is not set before cancellation.
3129 EXPECT_TRUE(r
->proxy_server().IsEmpty());
3130 EXPECT_EQ(ERR_EMPTY_RESPONSE
, r
->status().error());
3131 EXPECT_EQ(1, network_delegate
.created_requests());
3132 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3134 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3137 // Helper function for NetworkDelegateCancelRequestAsynchronously and
3138 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3139 // delegate operating in |block_mode| and a request for |url|. It blocks the
3140 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3141 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode
,
3142 BlockingNetworkDelegate::Stage stage
,
3145 BlockingNetworkDelegate
network_delegate(block_mode
);
3146 network_delegate
.set_retval(ERR_BLOCKED_BY_CLIENT
);
3147 network_delegate
.set_block_on(stage
);
3149 TestURLRequestContext
context(true);
3150 context
.set_network_delegate(&network_delegate
);
3154 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3157 base::RunLoop().Run();
3159 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
3160 // The proxy server is not set before cancellation.
3161 EXPECT_TRUE(r
->proxy_server().IsEmpty());
3162 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT
, r
->status().error());
3163 EXPECT_EQ(1, network_delegate
.created_requests());
3164 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3166 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3169 // The following 3 tests check that the network delegate can cancel a request
3170 // synchronously in various stages of the request.
3171 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously1
) {
3172 ASSERT_TRUE(test_server_
.Start());
3173 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
3174 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
3175 test_server_
.GetURL(std::string()));
3178 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously2
) {
3179 ASSERT_TRUE(test_server_
.Start());
3180 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
3181 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
3182 test_server_
.GetURL(std::string()));
3185 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously3
) {
3186 ASSERT_TRUE(test_server_
.Start());
3187 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
3188 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
3189 test_server_
.GetURL(std::string()));
3192 // The following 3 tests check that the network delegate can cancel a request
3193 // asynchronously in various stages of the request.
3194 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously1
) {
3195 ASSERT_TRUE(test_server_
.Start());
3196 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
3197 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
3198 test_server_
.GetURL(std::string()));
3201 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously2
) {
3202 ASSERT_TRUE(test_server_
.Start());
3203 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
3204 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
3205 test_server_
.GetURL(std::string()));
3208 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously3
) {
3209 ASSERT_TRUE(test_server_
.Start());
3210 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
3211 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
3212 test_server_
.GetURL(std::string()));
3215 // Tests that the network delegate can block and redirect a request to a new
3217 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequest
) {
3218 ASSERT_TRUE(test_server_
.Start());
3221 BlockingNetworkDelegate
network_delegate(
3222 BlockingNetworkDelegate::AUTO_CALLBACK
);
3223 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3224 GURL
redirect_url(test_server_
.GetURL("simple.html"));
3225 network_delegate
.set_redirect_url(redirect_url
);
3227 TestURLRequestContextWithProxy
context(
3228 test_server_
.host_port_pair().ToString(), &network_delegate
);
3231 GURL
original_url(test_server_
.GetURL("empty.html"));
3232 scoped_ptr
<URLRequest
> r(
3233 context
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
3235 // Quit after hitting the redirect, so can check the headers.
3236 d
.set_quit_on_redirect(true);
3238 base::RunLoop().Run();
3240 // Check headers from URLRequestJob.
3241 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3242 EXPECT_EQ(307, r
->GetResponseCode());
3243 EXPECT_EQ(307, r
->response_headers()->response_code());
3244 std::string location
;
3245 ASSERT_TRUE(r
->response_headers()->EnumerateHeader(NULL
, "Location",
3247 EXPECT_EQ(redirect_url
, GURL(location
));
3249 // Let the request finish.
3250 r
->FollowDeferredRedirect();
3251 base::RunLoop().Run();
3252 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3253 EXPECT_TRUE(r
->proxy_server().Equals(test_server_
.host_port_pair()));
3255 1, network_delegate
.observed_before_proxy_headers_sent_callbacks());
3257 network_delegate
.last_observed_proxy().Equals(
3258 test_server_
.host_port_pair()));
3260 EXPECT_EQ(0, r
->status().error());
3261 EXPECT_EQ(redirect_url
, r
->url());
3262 EXPECT_EQ(original_url
, r
->original_url());
3263 EXPECT_EQ(2U, r
->url_chain().size());
3264 EXPECT_EQ(1, network_delegate
.created_requests());
3265 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3267 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3270 // Tests that the network delegate can block and redirect a request to a new
3271 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3272 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestSynchronously
) {
3273 ASSERT_TRUE(test_server_
.Start());
3276 BlockingNetworkDelegate
network_delegate(
3277 BlockingNetworkDelegate::SYNCHRONOUS
);
3278 GURL
redirect_url(test_server_
.GetURL("simple.html"));
3279 network_delegate
.set_redirect_url(redirect_url
);
3281 TestURLRequestContextWithProxy
context(
3282 test_server_
.host_port_pair().ToString(), &network_delegate
);
3285 GURL
original_url(test_server_
.GetURL("empty.html"));
3286 scoped_ptr
<URLRequest
> r(
3287 context
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
3289 // Quit after hitting the redirect, so can check the headers.
3290 d
.set_quit_on_redirect(true);
3292 base::RunLoop().Run();
3294 // Check headers from URLRequestJob.
3295 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3296 EXPECT_EQ(307, r
->GetResponseCode());
3297 EXPECT_EQ(307, r
->response_headers()->response_code());
3298 std::string location
;
3299 ASSERT_TRUE(r
->response_headers()->EnumerateHeader(NULL
, "Location",
3301 EXPECT_EQ(redirect_url
, GURL(location
));
3303 // Let the request finish.
3304 r
->FollowDeferredRedirect();
3305 base::RunLoop().Run();
3307 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3308 EXPECT_TRUE(r
->proxy_server().Equals(test_server_
.host_port_pair()));
3310 1, network_delegate
.observed_before_proxy_headers_sent_callbacks());
3312 network_delegate
.last_observed_proxy().Equals(
3313 test_server_
.host_port_pair()));
3314 EXPECT_EQ(0, r
->status().error());
3315 EXPECT_EQ(redirect_url
, r
->url());
3316 EXPECT_EQ(original_url
, r
->original_url());
3317 EXPECT_EQ(2U, r
->url_chain().size());
3318 EXPECT_EQ(1, network_delegate
.created_requests());
3319 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3321 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3324 // Tests that redirects caused by the network delegate preserve POST data.
3325 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestPost
) {
3326 ASSERT_TRUE(test_server_
.Start());
3328 const char kData
[] = "hello world";
3331 BlockingNetworkDelegate
network_delegate(
3332 BlockingNetworkDelegate::AUTO_CALLBACK
);
3333 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3334 GURL
redirect_url(test_server_
.GetURL("echo"));
3335 network_delegate
.set_redirect_url(redirect_url
);
3337 TestURLRequestContext
context(true);
3338 context
.set_network_delegate(&network_delegate
);
3342 GURL
original_url(test_server_
.GetURL("empty.html"));
3343 scoped_ptr
<URLRequest
> r(
3344 context
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
3345 r
->set_method("POST");
3346 r
->set_upload(CreateSimpleUploadData(kData
));
3347 HttpRequestHeaders headers
;
3348 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
3349 base::UintToString(arraysize(kData
) - 1));
3350 r
->SetExtraRequestHeaders(headers
);
3352 // Quit after hitting the redirect, so can check the headers.
3353 d
.set_quit_on_redirect(true);
3355 base::RunLoop().Run();
3357 // Check headers from URLRequestJob.
3358 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3359 EXPECT_EQ(307, r
->GetResponseCode());
3360 EXPECT_EQ(307, r
->response_headers()->response_code());
3361 std::string location
;
3362 ASSERT_TRUE(r
->response_headers()->EnumerateHeader(NULL
, "Location",
3364 EXPECT_EQ(redirect_url
, GURL(location
));
3366 // Let the request finish.
3367 r
->FollowDeferredRedirect();
3368 base::RunLoop().Run();
3370 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3371 EXPECT_EQ(0, r
->status().error());
3372 EXPECT_EQ(redirect_url
, r
->url());
3373 EXPECT_EQ(original_url
, r
->original_url());
3374 EXPECT_EQ(2U, r
->url_chain().size());
3375 EXPECT_EQ(1, network_delegate
.created_requests());
3376 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3377 EXPECT_EQ("POST", r
->method());
3378 EXPECT_EQ(kData
, d
.data_received());
3380 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3383 // Tests that the network delegate can block and redirect a request to a new
3384 // URL during OnHeadersReceived.
3385 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestOnHeadersReceived
) {
3386 ASSERT_TRUE(test_server_
.Start());
3389 BlockingNetworkDelegate
network_delegate(
3390 BlockingNetworkDelegate::AUTO_CALLBACK
);
3391 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
3392 GURL
redirect_url(test_server_
.GetURL("simple.html"));
3393 network_delegate
.set_redirect_on_headers_received_url(redirect_url
);
3395 TestURLRequestContextWithProxy
context(
3396 test_server_
.host_port_pair().ToString(), &network_delegate
);
3399 GURL
original_url(test_server_
.GetURL("empty.html"));
3400 scoped_ptr
<URLRequest
> r(
3401 context
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
3404 base::RunLoop().Run();
3406 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3407 EXPECT_TRUE(r
->proxy_server().Equals(test_server_
.host_port_pair()));
3409 2, network_delegate
.observed_before_proxy_headers_sent_callbacks());
3411 network_delegate
.last_observed_proxy().Equals(
3412 test_server_
.host_port_pair()));
3414 EXPECT_EQ(OK
, r
->status().error());
3415 EXPECT_EQ(redirect_url
, r
->url());
3416 EXPECT_EQ(original_url
, r
->original_url());
3417 EXPECT_EQ(2U, r
->url_chain().size());
3418 EXPECT_EQ(2, network_delegate
.created_requests());
3419 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3421 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3424 // Tests that the network delegate can synchronously complete OnAuthRequired
3425 // by taking no action. This indicates that the NetworkDelegate does not want to
3426 // handle the challenge, and is passing the buck along to the
3427 // URLRequest::Delegate.
3428 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncNoAction
) {
3429 ASSERT_TRUE(test_server_
.Start());
3432 BlockingNetworkDelegate
network_delegate(
3433 BlockingNetworkDelegate::SYNCHRONOUS
);
3435 TestURLRequestContext
context(true);
3436 context
.set_network_delegate(&network_delegate
);
3439 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3442 GURL
url(test_server_
.GetURL("auth-basic"));
3443 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3446 base::RunLoop().Run();
3448 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3449 EXPECT_EQ(0, r
->status().error());
3450 EXPECT_EQ(200, r
->GetResponseCode());
3451 EXPECT_TRUE(d
.auth_required_called());
3452 EXPECT_EQ(1, network_delegate
.created_requests());
3453 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3455 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3458 TEST_F(URLRequestTestHTTP
,
3459 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders
) {
3460 ASSERT_TRUE(test_server_
.Start());
3463 BlockingNetworkDelegate
network_delegate(
3464 BlockingNetworkDelegate::SYNCHRONOUS
);
3466 TestURLRequestContext
context(true);
3467 context
.set_network_delegate(&network_delegate
);
3470 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3473 GURL
url(test_server_
.GetURL("auth-basic"));
3474 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3478 HttpRequestHeaders headers
;
3479 EXPECT_TRUE(r
->GetFullRequestHeaders(&headers
));
3480 EXPECT_FALSE(headers
.HasHeader("Authorization"));
3483 base::RunLoop().Run();
3485 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3486 EXPECT_EQ(0, r
->status().error());
3487 EXPECT_EQ(200, r
->GetResponseCode());
3488 EXPECT_TRUE(d
.auth_required_called());
3489 EXPECT_EQ(1, network_delegate
.created_requests());
3490 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3492 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3495 // Tests that the network delegate can synchronously complete OnAuthRequired
3496 // by setting credentials.
3497 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncSetAuth
) {
3498 ASSERT_TRUE(test_server_
.Start());
3501 BlockingNetworkDelegate
network_delegate(
3502 BlockingNetworkDelegate::SYNCHRONOUS
);
3503 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3504 network_delegate
.set_auth_retval(
3505 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3507 network_delegate
.set_auth_credentials(AuthCredentials(kUser
, kSecret
));
3509 TestURLRequestContext
context(true);
3510 context
.set_network_delegate(&network_delegate
);
3514 GURL
url(test_server_
.GetURL("auth-basic"));
3515 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3517 base::RunLoop().Run();
3519 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3520 EXPECT_EQ(0, r
->status().error());
3521 EXPECT_EQ(200, r
->GetResponseCode());
3522 EXPECT_FALSE(d
.auth_required_called());
3523 EXPECT_EQ(1, network_delegate
.created_requests());
3524 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3526 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3529 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3530 // headers (for the first or second request) when called at the proper times.
3531 TEST_F(URLRequestTestHTTP
,
3532 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders
) {
3533 ASSERT_TRUE(test_server_
.Start());
3536 BlockingNetworkDelegate
network_delegate(
3537 BlockingNetworkDelegate::SYNCHRONOUS
);
3538 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3539 network_delegate
.set_auth_retval(
3540 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3542 network_delegate
.set_auth_credentials(AuthCredentials(kUser
, kSecret
));
3544 TestURLRequestContext
context(true);
3545 context
.set_network_delegate(&network_delegate
);
3549 GURL
url(test_server_
.GetURL("auth-basic"));
3550 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3552 base::RunLoop().Run();
3554 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3555 EXPECT_EQ(0, r
->status().error());
3556 EXPECT_EQ(200, r
->GetResponseCode());
3557 EXPECT_FALSE(d
.auth_required_called());
3558 EXPECT_EQ(1, network_delegate
.created_requests());
3559 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3562 HttpRequestHeaders headers
;
3563 EXPECT_TRUE(r
->GetFullRequestHeaders(&headers
));
3564 EXPECT_TRUE(headers
.HasHeader("Authorization"));
3567 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3570 // Tests that the network delegate can synchronously complete OnAuthRequired
3571 // by cancelling authentication.
3572 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncCancel
) {
3573 ASSERT_TRUE(test_server_
.Start());
3576 BlockingNetworkDelegate
network_delegate(
3577 BlockingNetworkDelegate::SYNCHRONOUS
);
3578 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3579 network_delegate
.set_auth_retval(
3580 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH
);
3582 TestURLRequestContext
context(true);
3583 context
.set_network_delegate(&network_delegate
);
3587 GURL
url(test_server_
.GetURL("auth-basic"));
3588 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3590 base::RunLoop().Run();
3592 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3593 EXPECT_EQ(OK
, r
->status().error());
3594 EXPECT_EQ(401, r
->GetResponseCode());
3595 EXPECT_FALSE(d
.auth_required_called());
3596 EXPECT_EQ(1, network_delegate
.created_requests());
3597 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3599 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3602 // Tests that the network delegate can asynchronously complete OnAuthRequired
3603 // by taking no action. This indicates that the NetworkDelegate does not want
3604 // to handle the challenge, and is passing the buck along to the
3605 // URLRequest::Delegate.
3606 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncNoAction
) {
3607 ASSERT_TRUE(test_server_
.Start());
3610 BlockingNetworkDelegate
network_delegate(
3611 BlockingNetworkDelegate::AUTO_CALLBACK
);
3612 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3614 TestURLRequestContext
context(true);
3615 context
.set_network_delegate(&network_delegate
);
3618 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3621 GURL
url(test_server_
.GetURL("auth-basic"));
3622 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3624 base::RunLoop().Run();
3626 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3627 EXPECT_EQ(0, r
->status().error());
3628 EXPECT_EQ(200, r
->GetResponseCode());
3629 EXPECT_TRUE(d
.auth_required_called());
3630 EXPECT_EQ(1, network_delegate
.created_requests());
3631 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3633 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3636 // Tests that the network delegate can asynchronously complete OnAuthRequired
3637 // by setting credentials.
3638 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncSetAuth
) {
3639 ASSERT_TRUE(test_server_
.Start());
3642 BlockingNetworkDelegate
network_delegate(
3643 BlockingNetworkDelegate::AUTO_CALLBACK
);
3644 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3645 network_delegate
.set_auth_retval(
3646 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3648 AuthCredentials
auth_credentials(kUser
, kSecret
);
3649 network_delegate
.set_auth_credentials(auth_credentials
);
3651 TestURLRequestContext
context(true);
3652 context
.set_network_delegate(&network_delegate
);
3656 GURL
url(test_server_
.GetURL("auth-basic"));
3657 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3659 base::RunLoop().Run();
3661 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3662 EXPECT_EQ(0, r
->status().error());
3664 EXPECT_EQ(200, r
->GetResponseCode());
3665 EXPECT_FALSE(d
.auth_required_called());
3666 EXPECT_EQ(1, network_delegate
.created_requests());
3667 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3669 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3672 // Tests that the network delegate can asynchronously complete OnAuthRequired
3673 // by cancelling authentication.
3674 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncCancel
) {
3675 ASSERT_TRUE(test_server_
.Start());
3678 BlockingNetworkDelegate
network_delegate(
3679 BlockingNetworkDelegate::AUTO_CALLBACK
);
3680 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3681 network_delegate
.set_auth_retval(
3682 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH
);
3684 TestURLRequestContext
context(true);
3685 context
.set_network_delegate(&network_delegate
);
3689 GURL
url(test_server_
.GetURL("auth-basic"));
3690 scoped_ptr
<URLRequest
> r(context
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
3692 base::RunLoop().Run();
3694 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3695 EXPECT_EQ(OK
, r
->status().error());
3696 EXPECT_EQ(401, r
->GetResponseCode());
3697 EXPECT_FALSE(d
.auth_required_called());
3698 EXPECT_EQ(1, network_delegate
.created_requests());
3699 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3701 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3704 // Tests that we can handle when a network request was canceled while we were
3705 // waiting for the network delegate.
3706 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3707 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting1
) {
3708 ASSERT_TRUE(test_server_
.Start());
3711 BlockingNetworkDelegate
network_delegate(
3712 BlockingNetworkDelegate::USER_CALLBACK
);
3713 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3715 TestURLRequestContext
context(true);
3716 context
.set_network_delegate(&network_delegate
);
3720 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3721 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
3724 base::RunLoop().Run();
3725 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
3726 network_delegate
.stage_blocked_for_callback());
3727 EXPECT_EQ(0, network_delegate
.completed_requests());
3728 // Cancel before callback.
3730 // Ensure that network delegate is notified.
3731 EXPECT_EQ(1, network_delegate
.completed_requests());
3732 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3733 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3734 EXPECT_EQ(1, network_delegate
.created_requests());
3735 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3737 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3740 // Tests that we can handle when a network request was canceled while we were
3741 // waiting for the network delegate.
3742 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3743 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting2
) {
3744 ASSERT_TRUE(test_server_
.Start());
3747 BlockingNetworkDelegate
network_delegate(
3748 BlockingNetworkDelegate::USER_CALLBACK
);
3749 network_delegate
.set_block_on(
3750 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
);
3752 TestURLRequestContext
context(true);
3753 context
.set_network_delegate(&network_delegate
);
3757 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3758 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
3761 base::RunLoop().Run();
3762 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
3763 network_delegate
.stage_blocked_for_callback());
3764 EXPECT_EQ(0, network_delegate
.completed_requests());
3765 // Cancel before callback.
3767 // Ensure that network delegate is notified.
3768 EXPECT_EQ(1, network_delegate
.completed_requests());
3769 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3770 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3771 EXPECT_EQ(1, network_delegate
.created_requests());
3772 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3774 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3777 // Tests that we can handle when a network request was canceled while we were
3778 // waiting for the network delegate.
3779 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3780 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting3
) {
3781 ASSERT_TRUE(test_server_
.Start());
3784 BlockingNetworkDelegate
network_delegate(
3785 BlockingNetworkDelegate::USER_CALLBACK
);
3786 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
3788 TestURLRequestContext
context(true);
3789 context
.set_network_delegate(&network_delegate
);
3793 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3794 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
3797 base::RunLoop().Run();
3798 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
3799 network_delegate
.stage_blocked_for_callback());
3800 EXPECT_EQ(0, network_delegate
.completed_requests());
3801 // Cancel before callback.
3803 // Ensure that network delegate is notified.
3804 EXPECT_EQ(1, network_delegate
.completed_requests());
3805 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3806 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3807 EXPECT_EQ(1, network_delegate
.created_requests());
3808 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3810 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3813 // Tests that we can handle when a network request was canceled while we were
3814 // waiting for the network delegate.
3815 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3816 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting4
) {
3817 ASSERT_TRUE(test_server_
.Start());
3820 BlockingNetworkDelegate
network_delegate(
3821 BlockingNetworkDelegate::USER_CALLBACK
);
3822 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3824 TestURLRequestContext
context(true);
3825 context
.set_network_delegate(&network_delegate
);
3829 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3830 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
));
3833 base::RunLoop().Run();
3834 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED
,
3835 network_delegate
.stage_blocked_for_callback());
3836 EXPECT_EQ(0, network_delegate
.completed_requests());
3837 // Cancel before callback.
3839 // Ensure that network delegate is notified.
3840 EXPECT_EQ(1, network_delegate
.completed_requests());
3841 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3842 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3843 EXPECT_EQ(1, network_delegate
.created_requests());
3844 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3846 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3849 // In this unit test, we're using the HTTPTestServer as a proxy server and
3850 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3851 // The HTTPTestServer will return a 401 response, which we should balk at.
3852 TEST_F(URLRequestTestHTTP
, UnexpectedServerAuthTest
) {
3853 ASSERT_TRUE(test_server_
.Start());
3855 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
3856 TestURLRequestContextWithProxy
context(
3857 test_server_
.host_port_pair().ToString(), &network_delegate
);
3861 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3862 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY
, &d
));
3865 EXPECT_TRUE(r
->is_pending());
3867 base::RunLoop().Run();
3869 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
3870 // The proxy server is not set before failure.
3871 EXPECT_TRUE(r
->proxy_server().IsEmpty());
3872 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
->status().error());
3876 TEST_F(URLRequestTestHTTP
, GetTest_NoCache
) {
3877 ASSERT_TRUE(test_server_
.Start());
3881 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
3882 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
3885 EXPECT_TRUE(r
->is_pending());
3887 base::RunLoop().Run();
3889 EXPECT_EQ(1, d
.response_started_count());
3890 EXPECT_FALSE(d
.received_data_before_response());
3891 EXPECT_NE(0, d
.bytes_received());
3892 EXPECT_EQ(test_server_
.host_port_pair().host(),
3893 r
->GetSocketAddress().host());
3894 EXPECT_EQ(test_server_
.host_port_pair().port(),
3895 r
->GetSocketAddress().port());
3897 // TODO(eroman): Add back the NetLog tests...
3901 // This test has the server send a large number of cookies to the client.
3902 // To ensure that no number of cookies causes a crash, a galloping binary
3903 // search is used to estimate that maximum number of cookies that are accepted
3904 // by the browser. Beyond the maximum number, the request will fail with
3905 // ERR_RESPONSE_HEADERS_TOO_BIG.
3907 // http://crbug.com/177916
3908 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3910 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3911 #endif // defined(OS_WIN)
3912 TEST_F(URLRequestTestHTTP
, MAYBE_GetTest_ManyCookies
) {
3913 ASSERT_TRUE(test_server_
.Start());
3915 int lower_bound
= 0;
3916 int upper_bound
= 1;
3918 // Double the number of cookies until the response header limits are
3920 while (DoManyCookiesRequest(upper_bound
)) {
3921 lower_bound
= upper_bound
;
3923 ASSERT_LT(upper_bound
, 1000000);
3926 int tolerance
= static_cast<int>(upper_bound
* 0.005);
3930 // Perform a binary search to find the highest possible number of cookies,
3931 // within the desired tolerance.
3932 while (upper_bound
- lower_bound
>= tolerance
) {
3933 int num_cookies
= (lower_bound
+ upper_bound
) / 2;
3935 if (DoManyCookiesRequest(num_cookies
))
3936 lower_bound
= num_cookies
;
3938 upper_bound
= num_cookies
;
3940 // Success: the test did not crash.
3943 TEST_F(URLRequestTestHTTP
, GetTest
) {
3944 ASSERT_TRUE(test_server_
.Start());
3948 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
3949 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
3952 EXPECT_TRUE(r
->is_pending());
3954 base::RunLoop().Run();
3956 EXPECT_EQ(1, d
.response_started_count());
3957 EXPECT_FALSE(d
.received_data_before_response());
3958 EXPECT_NE(0, d
.bytes_received());
3959 EXPECT_EQ(test_server_
.host_port_pair().host(),
3960 r
->GetSocketAddress().host());
3961 EXPECT_EQ(test_server_
.host_port_pair().port(),
3962 r
->GetSocketAddress().port());
3966 TEST_F(URLRequestTestHTTP
, GetTest_GetFullRequestHeaders
) {
3967 ASSERT_TRUE(test_server_
.Start());
3971 GURL
test_url(test_server_
.GetURL(std::string()));
3972 scoped_ptr
<URLRequest
> r(
3973 default_context_
.CreateRequest(test_url
, DEFAULT_PRIORITY
, &d
));
3975 HttpRequestHeaders headers
;
3976 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
3979 EXPECT_TRUE(r
->is_pending());
3981 base::RunLoop().Run();
3983 EXPECT_EQ(1, d
.response_started_count());
3984 EXPECT_FALSE(d
.received_data_before_response());
3985 EXPECT_NE(0, d
.bytes_received());
3986 EXPECT_EQ(test_server_
.host_port_pair().host(),
3987 r
->GetSocketAddress().host());
3988 EXPECT_EQ(test_server_
.host_port_pair().port(),
3989 r
->GetSocketAddress().port());
3991 EXPECT_TRUE(d
.have_full_request_headers());
3992 CheckFullRequestHeaders(d
.full_request_headers(), test_url
);
3996 TEST_F(URLRequestTestHTTP
, GetTestLoadTiming
) {
3997 ASSERT_TRUE(test_server_
.Start());
4001 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4002 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
4005 EXPECT_TRUE(r
->is_pending());
4007 base::RunLoop().Run();
4009 LoadTimingInfo load_timing_info
;
4010 r
->GetLoadTimingInfo(&load_timing_info
);
4011 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
4013 EXPECT_EQ(1, d
.response_started_count());
4014 EXPECT_FALSE(d
.received_data_before_response());
4015 EXPECT_NE(0, d
.bytes_received());
4016 EXPECT_EQ(test_server_
.host_port_pair().host(),
4017 r
->GetSocketAddress().host());
4018 EXPECT_EQ(test_server_
.host_port_pair().port(),
4019 r
->GetSocketAddress().port());
4023 TEST_F(URLRequestTestHTTP
, GetZippedTest
) {
4024 ASSERT_TRUE(test_server_
.Start());
4026 // Parameter that specifies the Content-Length field in the response:
4027 // C - Compressed length.
4028 // U - Uncompressed length.
4029 // L - Large length (larger than both C & U).
4030 // M - Medium length (between C & U).
4031 // S - Small length (smaller than both C & U).
4032 const char test_parameters
[] = "CULMS";
4033 const int num_tests
= arraysize(test_parameters
)- 1; // Skip NULL.
4034 // C & U should be OK.
4035 // L & M are larger than the data sent, and show an error.
4036 // S has too little data, but we seem to accept it.
4037 const bool test_expect_success
[num_tests
] =
4038 { true, true, false, false, true };
4040 for (int i
= 0; i
< num_tests
; i
++) {
4043 std::string test_file
=
4044 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4045 test_parameters
[i
]);
4047 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
4048 TestURLRequestContext
context(true);
4049 context
.set_network_delegate(&network_delegate
);
4052 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4053 test_server_
.GetURL(test_file
), DEFAULT_PRIORITY
, &d
));
4055 EXPECT_TRUE(r
->is_pending());
4057 base::RunLoop().Run();
4059 EXPECT_EQ(1, d
.response_started_count());
4060 EXPECT_FALSE(d
.received_data_before_response());
4061 VLOG(1) << " Received " << d
.bytes_received() << " bytes"
4062 << " status = " << r
->status().status()
4063 << " error = " << r
->status().error();
4064 if (test_expect_success
[i
]) {
4065 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status())
4066 << " Parameter = \"" << test_file
<< "\"";
4068 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
4069 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH
, r
->status().error())
4070 << " Parameter = \"" << test_file
<< "\"";
4076 TEST_F(URLRequestTestHTTP
, NetworkQualityEstimator
) {
4077 ASSERT_TRUE(test_server_
.Start());
4078 // Enable requests to local host to be used for network quality estimation.
4079 NetworkQualityEstimator
estimator(true);
4082 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
4083 TestURLRequestContext
context(true);
4084 context
.set_network_quality_estimator(&estimator
);
4085 context
.set_network_delegate(&network_delegate
);
4088 uint64_t min_transfer_size_in_bytes
=
4089 NetworkQualityEstimator::kMinTransferSizeInBytes
;
4090 // Create a long enough URL such that response size exceeds network quality
4091 // estimator's minimum transfer size.
4092 std::string url
= "echo.html?";
4093 url
.append(min_transfer_size_in_bytes
, 'x');
4095 scoped_ptr
<URLRequest
> r(
4096 context
.CreateRequest(test_server_
.GetURL(url
), DEFAULT_PRIORITY
, &d
));
4097 int sleep_duration_milliseconds
= 1;
4098 base::PlatformThread::Sleep(
4099 base::TimeDelta::FromMilliseconds(sleep_duration_milliseconds
));
4102 base::RunLoop().Run();
4104 NetworkQuality network_quality
=
4105 context
.network_quality_estimator()->GetEstimate();
4106 EXPECT_GE(network_quality
.fastest_rtt
,
4107 base::TimeDelta::FromMilliseconds(sleep_duration_milliseconds
));
4108 EXPECT_GT(network_quality
.fastest_rtt_confidence
, 0);
4109 EXPECT_GT(network_quality
.peak_throughput_kbps
, uint64_t(0));
4110 EXPECT_GT(network_quality
.peak_throughput_kbps_confidence
, 0);
4112 // Verify that histograms are not populated. They should populate only when
4113 // there is a change in ConnectionType.
4114 base::HistogramTester histogram_tester
;
4115 histogram_tester
.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4116 histogram_tester
.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4118 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4119 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI
);
4120 base::MessageLoop::current()->RunUntilIdle();
4121 histogram_tester
.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4122 histogram_tester
.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4125 TEST_F(URLRequestTestHTTP
, RedirectLoadTiming
) {
4126 ASSERT_TRUE(test_server_
.Start());
4128 GURL destination_url
= test_server_
.GetURL(std::string());
4130 test_server_
.GetURL("server-redirect?" + destination_url
.spec());
4132 scoped_ptr
<URLRequest
> req(
4133 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
4135 base::RunLoop().Run();
4137 EXPECT_EQ(1, d
.response_started_count());
4138 EXPECT_EQ(1, d
.received_redirect_count());
4139 EXPECT_EQ(destination_url
, req
->url());
4140 EXPECT_EQ(original_url
, req
->original_url());
4141 ASSERT_EQ(2U, req
->url_chain().size());
4142 EXPECT_EQ(original_url
, req
->url_chain()[0]);
4143 EXPECT_EQ(destination_url
, req
->url_chain()[1]);
4145 LoadTimingInfo load_timing_info_before_redirect
;
4146 EXPECT_TRUE(default_network_delegate_
.GetLoadTimingInfoBeforeRedirect(
4147 &load_timing_info_before_redirect
));
4148 TestLoadTimingNotReused(load_timing_info_before_redirect
,
4149 CONNECT_TIMING_HAS_DNS_TIMES
);
4151 LoadTimingInfo load_timing_info
;
4152 req
->GetLoadTimingInfo(&load_timing_info
);
4153 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
4155 // Check that a new socket was used on redirect, since the server does not
4156 // supposed keep-alive sockets, and that the times before the redirect are
4157 // before the ones recorded for the second request.
4158 EXPECT_NE(load_timing_info_before_redirect
.socket_log_id
,
4159 load_timing_info
.socket_log_id
);
4160 EXPECT_LE(load_timing_info_before_redirect
.receive_headers_end
,
4161 load_timing_info
.connect_timing
.connect_start
);
4164 TEST_F(URLRequestTestHTTP
, MultipleRedirectTest
) {
4165 ASSERT_TRUE(test_server_
.Start());
4167 GURL destination_url
= test_server_
.GetURL(std::string());
4168 GURL middle_redirect_url
=
4169 test_server_
.GetURL("server-redirect?" + destination_url
.spec());
4170 GURL original_url
= test_server_
.GetURL(
4171 "server-redirect?" + middle_redirect_url
.spec());
4173 scoped_ptr
<URLRequest
> req(
4174 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
4176 base::RunLoop().Run();
4178 EXPECT_EQ(1, d
.response_started_count());
4179 EXPECT_EQ(2, d
.received_redirect_count());
4180 EXPECT_EQ(destination_url
, req
->url());
4181 EXPECT_EQ(original_url
, req
->original_url());
4182 ASSERT_EQ(3U, req
->url_chain().size());
4183 EXPECT_EQ(original_url
, req
->url_chain()[0]);
4184 EXPECT_EQ(middle_redirect_url
, req
->url_chain()[1]);
4185 EXPECT_EQ(destination_url
, req
->url_chain()[2]);
4188 // First and second pieces of information logged by delegates to URLRequests.
4189 const char kFirstDelegateInfo
[] = "Wonderful delegate";
4190 const char kSecondDelegateInfo
[] = "Exciting delegate";
4192 // Logs delegate information to a URLRequest. The first string is logged
4193 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4194 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4195 // another asynchronous call is used to clear the delegate information
4196 // before calling a callback. The object then deletes itself.
4197 class AsyncDelegateLogger
: public base::RefCounted
<AsyncDelegateLogger
> {
4199 typedef base::Callback
<void()> Callback
;
4201 // Each time delegate information is added to the URLRequest, the resulting
4202 // load state is checked. The expected load state after each request is
4203 // passed in as an argument.
4204 static void Run(URLRequest
* url_request
,
4205 LoadState expected_first_load_state
,
4206 LoadState expected_second_load_state
,
4207 LoadState expected_third_load_state
,
4208 const Callback
& callback
) {
4209 AsyncDelegateLogger
* logger
= new AsyncDelegateLogger(
4211 expected_first_load_state
,
4212 expected_second_load_state
,
4213 expected_third_load_state
,
4218 // Checks that the log entries, starting with log_position, contain the
4219 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4220 // recorded. Returns the index of entry after the expected number of
4221 // events this logged, or entries.size() if there aren't enough entries.
4222 static size_t CheckDelegateInfo(const TestNetLogEntry::List
& entries
,
4223 size_t log_position
) {
4224 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4225 if (log_position
+ 3 >= entries
.size()) {
4226 ADD_FAILURE() << "Not enough log entries";
4227 return entries
.size();
4229 std::string delegate_info
;
4230 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
4231 EXPECT_EQ(NetLog::PHASE_BEGIN
, entries
[log_position
].phase
);
4232 EXPECT_TRUE(entries
[log_position
].GetStringValue("delegate_info",
4234 EXPECT_EQ(kFirstDelegateInfo
, delegate_info
);
4237 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
4238 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4241 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
4242 EXPECT_EQ(NetLog::PHASE_BEGIN
, entries
[log_position
].phase
);
4243 EXPECT_TRUE(entries
[log_position
].GetStringValue("delegate_info",
4245 EXPECT_EQ(kSecondDelegateInfo
, delegate_info
);
4248 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
4249 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4251 return log_position
+ 1;
4254 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4255 // Returns the position of the end message.
4256 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List
& entries
,
4257 size_t log_position
) {
4259 ExpectLogContainsSomewhereAfter(entries
,
4261 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4262 NetLog::PHASE_BEGIN
);
4263 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
,
4264 entries
[log_position
+ 1].type
);
4265 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
+ 1].phase
);
4266 return log_position
+ 1;
4270 friend class base::RefCounted
<AsyncDelegateLogger
>;
4272 AsyncDelegateLogger(URLRequest
* url_request
,
4273 LoadState expected_first_load_state
,
4274 LoadState expected_second_load_state
,
4275 LoadState expected_third_load_state
,
4276 const Callback
& callback
)
4277 : url_request_(url_request
),
4278 expected_first_load_state_(expected_first_load_state
),
4279 expected_second_load_state_(expected_second_load_state
),
4280 expected_third_load_state_(expected_third_load_state
),
4281 callback_(callback
) {
4284 ~AsyncDelegateLogger() {}
4287 url_request_
->LogBlockedBy(kFirstDelegateInfo
);
4288 LoadStateWithParam load_state
= url_request_
->GetLoadState();
4289 EXPECT_EQ(expected_first_load_state_
, load_state
.state
);
4290 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo
), load_state
.param
);
4291 base::MessageLoop::current()->PostTask(
4293 base::Bind(&AsyncDelegateLogger::LogSecondDelegate
, this));
4296 void LogSecondDelegate() {
4297 url_request_
->LogAndReportBlockedBy(kSecondDelegateInfo
);
4298 LoadStateWithParam load_state
= url_request_
->GetLoadState();
4299 EXPECT_EQ(expected_second_load_state_
, load_state
.state
);
4300 if (expected_second_load_state_
== LOAD_STATE_WAITING_FOR_DELEGATE
) {
4301 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo
), load_state
.param
);
4303 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo
), load_state
.param
);
4305 base::MessageLoop::current()->PostTask(
4307 base::Bind(&AsyncDelegateLogger::LogComplete
, this));
4310 void LogComplete() {
4311 url_request_
->LogUnblocked();
4312 LoadStateWithParam load_state
= url_request_
->GetLoadState();
4313 EXPECT_EQ(expected_third_load_state_
, load_state
.state
);
4314 if (expected_second_load_state_
== LOAD_STATE_WAITING_FOR_DELEGATE
)
4315 EXPECT_EQ(base::string16(), load_state
.param
);
4319 URLRequest
* url_request_
;
4320 const int expected_first_load_state_
;
4321 const int expected_second_load_state_
;
4322 const int expected_third_load_state_
;
4323 const Callback callback_
;
4325 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger
);
4328 // NetworkDelegate that logs delegate information before a request is started,
4329 // before headers are sent, when headers are read, and when auth information
4330 // is requested. Uses AsyncDelegateLogger.
4331 class AsyncLoggingNetworkDelegate
: public TestNetworkDelegate
{
4333 AsyncLoggingNetworkDelegate() {}
4334 ~AsyncLoggingNetworkDelegate() override
{}
4336 // NetworkDelegate implementation.
4337 int OnBeforeURLRequest(URLRequest
* request
,
4338 const CompletionCallback
& callback
,
4339 GURL
* new_url
) override
{
4340 TestNetworkDelegate::OnBeforeURLRequest(request
, callback
, new_url
);
4341 return RunCallbackAsynchronously(request
, callback
);
4344 int OnBeforeSendHeaders(URLRequest
* request
,
4345 const CompletionCallback
& callback
,
4346 HttpRequestHeaders
* headers
) override
{
4347 TestNetworkDelegate::OnBeforeSendHeaders(request
, callback
, headers
);
4348 return RunCallbackAsynchronously(request
, callback
);
4351 int OnHeadersReceived(
4352 URLRequest
* request
,
4353 const CompletionCallback
& callback
,
4354 const HttpResponseHeaders
* original_response_headers
,
4355 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
4356 GURL
* allowed_unsafe_redirect_url
) override
{
4357 TestNetworkDelegate::OnHeadersReceived(request
,
4359 original_response_headers
,
4360 override_response_headers
,
4361 allowed_unsafe_redirect_url
);
4362 return RunCallbackAsynchronously(request
, callback
);
4365 NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
4366 URLRequest
* request
,
4367 const AuthChallengeInfo
& auth_info
,
4368 const AuthCallback
& callback
,
4369 AuthCredentials
* credentials
) override
{
4370 AsyncDelegateLogger::Run(
4372 LOAD_STATE_WAITING_FOR_DELEGATE
,
4373 LOAD_STATE_WAITING_FOR_DELEGATE
,
4374 LOAD_STATE_WAITING_FOR_DELEGATE
,
4375 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume
,
4376 callback
, credentials
));
4377 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
4381 static int RunCallbackAsynchronously(
4382 URLRequest
* request
,
4383 const CompletionCallback
& callback
) {
4384 AsyncDelegateLogger::Run(
4386 LOAD_STATE_WAITING_FOR_DELEGATE
,
4387 LOAD_STATE_WAITING_FOR_DELEGATE
,
4388 LOAD_STATE_WAITING_FOR_DELEGATE
,
4389 base::Bind(callback
, OK
));
4390 return ERR_IO_PENDING
;
4393 static void SetAuthAndResume(const AuthCallback
& callback
,
4394 AuthCredentials
* credentials
) {
4395 *credentials
= AuthCredentials(kUser
, kSecret
);
4396 callback
.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
4399 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate
);
4402 // URLRequest::Delegate that logs delegate information when the headers
4403 // are received, when each read completes, and during redirects. Uses
4404 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4406 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4407 // advancing to the next step in most cases, as well as cancellation.
4408 class AsyncLoggingUrlRequestDelegate
: public TestDelegate
{
4412 CANCEL_ON_RECEIVED_REDIRECT
,
4413 CANCEL_ON_RESPONSE_STARTED
,
4414 CANCEL_ON_READ_COMPLETED
4417 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage
)
4418 : cancel_stage_(cancel_stage
) {
4419 if (cancel_stage
== CANCEL_ON_RECEIVED_REDIRECT
)
4420 set_cancel_in_received_redirect(true);
4421 else if (cancel_stage
== CANCEL_ON_RESPONSE_STARTED
)
4422 set_cancel_in_response_started(true);
4423 else if (cancel_stage
== CANCEL_ON_READ_COMPLETED
)
4424 set_cancel_in_received_data(true);
4426 ~AsyncLoggingUrlRequestDelegate() override
{}
4428 // URLRequest::Delegate implementation:
4429 void OnReceivedRedirect(URLRequest
* request
,
4430 const RedirectInfo
& redirect_info
,
4431 bool* defer_redirect
) override
{
4432 *defer_redirect
= true;
4433 AsyncDelegateLogger::Run(
4435 LOAD_STATE_WAITING_FOR_DELEGATE
,
4436 LOAD_STATE_WAITING_FOR_DELEGATE
,
4437 LOAD_STATE_WAITING_FOR_DELEGATE
,
4439 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete
,
4440 base::Unretained(this), request
, redirect_info
));
4443 void OnResponseStarted(URLRequest
* request
) override
{
4444 AsyncDelegateLogger::Run(
4446 LOAD_STATE_WAITING_FOR_DELEGATE
,
4447 LOAD_STATE_WAITING_FOR_DELEGATE
,
4448 LOAD_STATE_WAITING_FOR_DELEGATE
,
4450 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete
,
4451 base::Unretained(this), request
));
4454 void OnReadCompleted(URLRequest
* request
, int bytes_read
) override
{
4455 AsyncDelegateLogger::Run(
4461 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete
,
4462 base::Unretained(this), request
, bytes_read
));
4466 void OnReceivedRedirectLoggingComplete(URLRequest
* request
,
4467 const RedirectInfo
& redirect_info
) {
4468 bool defer_redirect
= false;
4469 TestDelegate::OnReceivedRedirect(request
, redirect_info
, &defer_redirect
);
4470 // FollowDeferredRedirect should not be called after cancellation.
4471 if (cancel_stage_
== CANCEL_ON_RECEIVED_REDIRECT
)
4473 if (!defer_redirect
)
4474 request
->FollowDeferredRedirect();
4477 void OnResponseStartedLoggingComplete(URLRequest
* request
) {
4478 // The parent class continues the request.
4479 TestDelegate::OnResponseStarted(request
);
4482 void AfterReadCompletedLoggingComplete(URLRequest
* request
, int bytes_read
) {
4483 // The parent class continues the request.
4484 TestDelegate::OnReadCompleted(request
, bytes_read
);
4487 const CancelStage cancel_stage_
;
4489 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate
);
4492 // Tests handling of delegate info before a request starts.
4493 TEST_F(URLRequestTestHTTP
, DelegateInfoBeforeStart
) {
4494 ASSERT_TRUE(test_server_
.Start());
4496 TestDelegate request_delegate
;
4497 TestURLRequestContext
context(true);
4498 context
.set_network_delegate(NULL
);
4499 context
.set_net_log(&net_log_
);
4503 scoped_ptr
<URLRequest
> r(
4504 context
.CreateRequest(test_server_
.GetURL("empty.html"),
4505 DEFAULT_PRIORITY
, &request_delegate
));
4506 LoadStateWithParam load_state
= r
->GetLoadState();
4507 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4508 EXPECT_EQ(base::string16(), load_state
.param
);
4510 AsyncDelegateLogger::Run(
4512 LOAD_STATE_WAITING_FOR_DELEGATE
,
4513 LOAD_STATE_WAITING_FOR_DELEGATE
,
4515 base::Bind(&URLRequest::Start
, base::Unretained(r
.get())));
4517 base::RunLoop().Run();
4519 EXPECT_EQ(200, r
->GetResponseCode());
4520 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4523 TestNetLogEntry::List entries
;
4524 net_log_
.GetEntries(&entries
);
4525 size_t log_position
= ExpectLogContainsSomewhereAfter(
4528 NetLog::TYPE_DELEGATE_INFO
,
4529 NetLog::PHASE_BEGIN
);
4531 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
, log_position
);
4533 // Nothing else should add any delegate info to the request.
4534 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4535 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4538 // Tests handling of delegate info from a network delegate.
4539 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfo
) {
4540 ASSERT_TRUE(test_server_
.Start());
4542 TestDelegate request_delegate
;
4543 AsyncLoggingNetworkDelegate network_delegate
;
4544 TestURLRequestContext
context(true);
4545 context
.set_network_delegate(&network_delegate
);
4546 context
.set_net_log(&net_log_
);
4550 scoped_ptr
<URLRequest
> r(
4551 context
.CreateRequest(test_server_
.GetURL("simple.html"),
4552 DEFAULT_PRIORITY
, &request_delegate
));
4553 LoadStateWithParam load_state
= r
->GetLoadState();
4554 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4555 EXPECT_EQ(base::string16(), load_state
.param
);
4558 base::RunLoop().Run();
4560 EXPECT_EQ(200, r
->GetResponseCode());
4561 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4562 EXPECT_EQ(1, network_delegate
.created_requests());
4563 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4565 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4567 size_t log_position
= 0;
4568 TestNetLogEntry::List entries
;
4569 net_log_
.GetEntries(&entries
);
4570 for (size_t i
= 0; i
< 3; ++i
) {
4571 log_position
= ExpectLogContainsSomewhereAfter(
4574 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4575 NetLog::PHASE_BEGIN
);
4577 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4580 ASSERT_LT(log_position
, entries
.size());
4581 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4582 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4585 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4586 entries
, log_position
+ 1);
4590 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4591 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4594 // Tests handling of delegate info from a network delegate in the case of an
4596 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfoRedirect
) {
4597 ASSERT_TRUE(test_server_
.Start());
4599 TestDelegate request_delegate
;
4600 AsyncLoggingNetworkDelegate network_delegate
;
4601 TestURLRequestContext
context(true);
4602 context
.set_network_delegate(&network_delegate
);
4603 context
.set_net_log(&net_log_
);
4607 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4608 test_server_
.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY
,
4609 &request_delegate
));
4610 LoadStateWithParam load_state
= r
->GetLoadState();
4611 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4612 EXPECT_EQ(base::string16(), load_state
.param
);
4615 base::RunLoop().Run();
4617 EXPECT_EQ(200, r
->GetResponseCode());
4618 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4619 EXPECT_EQ(2, network_delegate
.created_requests());
4620 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4622 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4624 size_t log_position
= 0;
4625 TestNetLogEntry::List entries
;
4626 net_log_
.GetEntries(&entries
);
4627 // The NetworkDelegate logged information in OnBeforeURLRequest,
4628 // OnBeforeSendHeaders, and OnHeadersReceived.
4629 for (size_t i
= 0; i
< 3; ++i
) {
4630 log_position
= ExpectLogContainsSomewhereAfter(
4633 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4634 NetLog::PHASE_BEGIN
);
4636 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4639 ASSERT_LT(log_position
, entries
.size());
4640 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4641 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4644 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4645 entries
, log_position
+ 1);
4649 // The URLRequest::Delegate then gets informed about the redirect.
4650 log_position
= ExpectLogContainsSomewhereAfter(
4653 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4654 NetLog::PHASE_BEGIN
);
4656 // The NetworkDelegate logged information in the same three events as before.
4657 for (size_t i
= 0; i
< 3; ++i
) {
4658 log_position
= ExpectLogContainsSomewhereAfter(
4661 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4662 NetLog::PHASE_BEGIN
);
4664 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4667 ASSERT_LT(log_position
, entries
.size());
4668 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4669 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4672 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4673 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4676 // Tests handling of delegate info from a network delegate in the case of HTTP
4678 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfoAuth
) {
4679 ASSERT_TRUE(test_server_
.Start());
4681 TestDelegate request_delegate
;
4682 AsyncLoggingNetworkDelegate network_delegate
;
4683 TestURLRequestContext
context(true);
4684 context
.set_network_delegate(&network_delegate
);
4685 context
.set_net_log(&net_log_
);
4689 scoped_ptr
<URLRequest
> r(
4690 context
.CreateRequest(test_server_
.GetURL("auth-basic"),
4691 DEFAULT_PRIORITY
, &request_delegate
));
4692 LoadStateWithParam load_state
= r
->GetLoadState();
4693 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4694 EXPECT_EQ(base::string16(), load_state
.param
);
4697 base::RunLoop().Run();
4699 EXPECT_EQ(200, r
->GetResponseCode());
4700 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4701 EXPECT_EQ(1, network_delegate
.created_requests());
4702 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4704 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4706 size_t log_position
= 0;
4707 TestNetLogEntry::List entries
;
4708 net_log_
.GetEntries(&entries
);
4709 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4710 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4711 // OnBeforeURLRequest and OnBeforeSendHeaders.
4712 for (size_t i
= 0; i
< 6; ++i
) {
4713 log_position
= ExpectLogContainsSomewhereAfter(
4716 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4717 NetLog::PHASE_BEGIN
);
4719 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4722 ASSERT_LT(log_position
, entries
.size());
4723 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4724 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4727 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4728 entries
, log_position
+ 1);
4732 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4733 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4736 // Tests handling of delegate info from a URLRequest::Delegate.
4737 TEST_F(URLRequestTestHTTP
, URLRequestDelegateInfo
) {
4738 ASSERT_TRUE(test_server_
.Start());
4740 AsyncLoggingUrlRequestDelegate
request_delegate(
4741 AsyncLoggingUrlRequestDelegate::NO_CANCEL
);
4742 TestURLRequestContext
context(true);
4743 context
.set_network_delegate(NULL
);
4744 context
.set_net_log(&net_log_
);
4748 // A chunked response with delays between chunks is used to make sure that
4749 // attempts by the URLRequest delegate to log information while reading the
4750 // body are ignored. Since they are ignored, this test is robust against
4751 // the possibility of multiple reads being combined in the unlikely event
4753 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4754 test_server_
.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY
,
4755 &request_delegate
));
4756 LoadStateWithParam load_state
= r
->GetLoadState();
4758 base::RunLoop().Run();
4760 EXPECT_EQ(200, r
->GetResponseCode());
4761 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4764 TestNetLogEntry::List entries
;
4765 net_log_
.GetEntries(&entries
);
4767 size_t log_position
= 0;
4769 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4770 entries
, log_position
);
4772 // The delegate info should only have been logged on header complete. Other
4773 // times it should silently be ignored.
4775 ExpectLogContainsSomewhereAfter(entries
,
4777 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4778 NetLog::PHASE_BEGIN
);
4780 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4783 ASSERT_LT(log_position
, entries
.size());
4784 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4785 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4787 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4788 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4789 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4790 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4793 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4794 // an HTTP redirect.
4795 TEST_F(URLRequestTestHTTP
, URLRequestDelegateInfoOnRedirect
) {
4796 ASSERT_TRUE(test_server_
.Start());
4798 AsyncLoggingUrlRequestDelegate
request_delegate(
4799 AsyncLoggingUrlRequestDelegate::NO_CANCEL
);
4800 TestURLRequestContext
context(true);
4801 context
.set_network_delegate(NULL
);
4802 context
.set_net_log(&net_log_
);
4806 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4807 test_server_
.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY
,
4808 &request_delegate
));
4809 LoadStateWithParam load_state
= r
->GetLoadState();
4811 base::RunLoop().Run();
4813 EXPECT_EQ(200, r
->GetResponseCode());
4814 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4817 TestNetLogEntry::List entries
;
4818 net_log_
.GetEntries(&entries
);
4820 // Delegate info should only have been logged in OnReceivedRedirect and
4821 // OnResponseStarted.
4822 size_t log_position
= 0;
4823 for (int i
= 0; i
< 2; ++i
) {
4825 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4826 entries
, log_position
) + 1;
4829 log_position
= ExpectLogContainsSomewhereAfter(
4832 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4833 NetLog::PHASE_BEGIN
);
4835 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4838 ASSERT_LT(log_position
, entries
.size());
4839 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4840 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4843 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4844 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4845 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4846 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4849 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4850 // an HTTP redirect, with cancellation at various points.
4851 TEST_F(URLRequestTestHTTP
, URLRequestDelegateOnRedirectCancelled
) {
4852 ASSERT_TRUE(test_server_
.Start());
4854 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages
[] = {
4855 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT
,
4856 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED
,
4857 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED
,
4860 for (size_t test_case
= 0; test_case
< arraysize(kCancelStages
);
4862 AsyncLoggingUrlRequestDelegate
request_delegate(kCancelStages
[test_case
]);
4863 TestURLRequestContext
context(true);
4865 context
.set_network_delegate(NULL
);
4866 context
.set_net_log(&net_log
);
4870 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4871 test_server_
.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY
,
4872 &request_delegate
));
4873 LoadStateWithParam load_state
= r
->GetLoadState();
4875 base::RunLoop().Run();
4876 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
4879 TestNetLogEntry::List entries
;
4880 net_log
.GetEntries(&entries
);
4882 // Delegate info is always logged in both OnReceivedRedirect and
4883 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4884 // OnResponseStarted delegate call is after cancellation, but logging is
4885 // still currently supported in that call.
4886 size_t log_position
= 0;
4887 for (int i
= 0; i
< 2; ++i
) {
4889 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4890 entries
, log_position
) + 1;
4893 log_position
= ExpectLogContainsSomewhereAfter(
4896 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4897 NetLog::PHASE_BEGIN
);
4899 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4902 ASSERT_LT(log_position
, entries
.size());
4903 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4904 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4907 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4908 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4909 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4910 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4916 const char kExtraHeader
[] = "Allow-Snafu";
4917 const char kExtraValue
[] = "fubar";
4919 class RedirectWithAdditionalHeadersDelegate
: public TestDelegate
{
4920 void OnReceivedRedirect(URLRequest
* request
,
4921 const RedirectInfo
& redirect_info
,
4922 bool* defer_redirect
) override
{
4923 TestDelegate::OnReceivedRedirect(request
, redirect_info
, defer_redirect
);
4924 request
->SetExtraRequestHeaderByName(kExtraHeader
, kExtraValue
, false);
4930 TEST_F(URLRequestTestHTTP
, RedirectWithAdditionalHeadersTest
) {
4931 ASSERT_TRUE(test_server_
.Start());
4933 GURL destination_url
= test_server_
.GetURL(
4934 "echoheader?" + std::string(kExtraHeader
));
4935 GURL original_url
= test_server_
.GetURL(
4936 "server-redirect?" + destination_url
.spec());
4937 RedirectWithAdditionalHeadersDelegate d
;
4938 scoped_ptr
<URLRequest
> req(
4939 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
4941 base::RunLoop().Run();
4944 const HttpRequestHeaders
& headers
= req
->extra_request_headers();
4945 EXPECT_TRUE(headers
.GetHeader(kExtraHeader
, &value
));
4946 EXPECT_EQ(kExtraValue
, value
);
4947 EXPECT_FALSE(req
->is_pending());
4948 EXPECT_FALSE(req
->is_redirecting());
4949 EXPECT_EQ(kExtraValue
, d
.data_received());
4954 const char kExtraHeaderToRemove
[] = "To-Be-Removed";
4956 class RedirectWithHeaderRemovalDelegate
: public TestDelegate
{
4957 void OnReceivedRedirect(URLRequest
* request
,
4958 const RedirectInfo
& redirect_info
,
4959 bool* defer_redirect
) override
{
4960 TestDelegate::OnReceivedRedirect(request
, redirect_info
, defer_redirect
);
4961 request
->RemoveRequestHeaderByName(kExtraHeaderToRemove
);
4967 TEST_F(URLRequestTestHTTP
, RedirectWithHeaderRemovalTest
) {
4968 ASSERT_TRUE(test_server_
.Start());
4970 GURL destination_url
= test_server_
.GetURL(
4971 "echoheader?" + std::string(kExtraHeaderToRemove
));
4972 GURL original_url
= test_server_
.GetURL(
4973 "server-redirect?" + destination_url
.spec());
4974 RedirectWithHeaderRemovalDelegate d
;
4975 scoped_ptr
<URLRequest
> req(
4976 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
4977 req
->SetExtraRequestHeaderByName(kExtraHeaderToRemove
, "dummy", false);
4979 base::RunLoop().Run();
4982 const HttpRequestHeaders
& headers
= req
->extra_request_headers();
4983 EXPECT_FALSE(headers
.GetHeader(kExtraHeaderToRemove
, &value
));
4984 EXPECT_FALSE(req
->is_pending());
4985 EXPECT_FALSE(req
->is_redirecting());
4986 EXPECT_EQ("None", d
.data_received());
4989 TEST_F(URLRequestTestHTTP
, CancelTest
) {
4992 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4993 GURL("http://www.google.com/"), DEFAULT_PRIORITY
, &d
));
4996 EXPECT_TRUE(r
->is_pending());
5000 base::RunLoop().Run();
5002 // We expect to receive OnResponseStarted even though the request has been
5004 EXPECT_EQ(1, d
.response_started_count());
5005 EXPECT_EQ(0, d
.bytes_received());
5006 EXPECT_FALSE(d
.received_data_before_response());
5010 TEST_F(URLRequestTestHTTP
, CancelTest2
) {
5011 ASSERT_TRUE(test_server_
.Start());
5015 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5016 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
5018 d
.set_cancel_in_response_started(true);
5021 EXPECT_TRUE(r
->is_pending());
5023 base::RunLoop().Run();
5025 EXPECT_EQ(1, d
.response_started_count());
5026 EXPECT_EQ(0, d
.bytes_received());
5027 EXPECT_FALSE(d
.received_data_before_response());
5028 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
5032 TEST_F(URLRequestTestHTTP
, CancelTest3
) {
5033 ASSERT_TRUE(test_server_
.Start());
5037 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5038 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
5040 d
.set_cancel_in_received_data(true);
5043 EXPECT_TRUE(r
->is_pending());
5045 base::RunLoop().Run();
5047 EXPECT_EQ(1, d
.response_started_count());
5048 // There is no guarantee about how much data was received
5049 // before the cancel was issued. It could have been 0 bytes,
5050 // or it could have been all the bytes.
5051 // EXPECT_EQ(0, d.bytes_received());
5052 EXPECT_FALSE(d
.received_data_before_response());
5053 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
5057 TEST_F(URLRequestTestHTTP
, CancelTest4
) {
5058 ASSERT_TRUE(test_server_
.Start());
5062 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5063 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
5066 EXPECT_TRUE(r
->is_pending());
5068 // The request will be implicitly canceled when it is destroyed. The
5069 // test delegate must not post a quit message when this happens because
5070 // this test doesn't actually have a message loop. The quit message would
5071 // get put on this thread's message queue and the next test would exit
5072 // early, causing problems.
5073 d
.set_quit_on_complete(false);
5075 // expect things to just cleanup properly.
5077 // we won't actually get a received reponse here because we've never run the
5079 EXPECT_FALSE(d
.received_data_before_response());
5080 EXPECT_EQ(0, d
.bytes_received());
5083 TEST_F(URLRequestTestHTTP
, CancelTest5
) {
5084 ASSERT_TRUE(test_server_
.Start());
5089 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5090 test_server_
.GetURL("cachetime"), DEFAULT_PRIORITY
, &d
));
5092 base::RunLoop().Run();
5093 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5096 // cancel read from cache (see bug 990242)
5099 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5100 test_server_
.GetURL("cachetime"), DEFAULT_PRIORITY
, &d
));
5103 base::RunLoop().Run();
5105 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
5106 EXPECT_EQ(1, d
.response_started_count());
5107 EXPECT_EQ(0, d
.bytes_received());
5108 EXPECT_FALSE(d
.received_data_before_response());
5112 TEST_F(URLRequestTestHTTP
, PostTest
) {
5113 ASSERT_TRUE(test_server_
.Start());
5114 HTTPUploadDataOperationTest("POST");
5117 TEST_F(URLRequestTestHTTP
, PutTest
) {
5118 ASSERT_TRUE(test_server_
.Start());
5119 HTTPUploadDataOperationTest("PUT");
5122 TEST_F(URLRequestTestHTTP
, PostEmptyTest
) {
5123 ASSERT_TRUE(test_server_
.Start());
5127 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5128 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
));
5129 r
->set_method("POST");
5132 EXPECT_TRUE(r
->is_pending());
5134 base::RunLoop().Run();
5136 ASSERT_EQ(1, d
.response_started_count())
5137 << "request failed: " << r
->status().status()
5138 << ", error: " << r
->status().error();
5140 EXPECT_FALSE(d
.received_data_before_response());
5141 EXPECT_TRUE(d
.data_received().empty());
5145 TEST_F(URLRequestTestHTTP
, PostFileTest
) {
5146 ASSERT_TRUE(test_server_
.Start());
5150 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5151 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
));
5152 r
->set_method("POST");
5155 PathService::Get(base::DIR_EXE
, &dir
);
5156 base::SetCurrentDirectory(dir
);
5158 ScopedVector
<UploadElementReader
> element_readers
;
5160 base::FilePath path
;
5161 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
5162 path
= path
.Append(FILE_PATH_LITERAL("net"));
5163 path
= path
.Append(FILE_PATH_LITERAL("data"));
5164 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
5165 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
5166 element_readers
.push_back(
5167 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5172 r
->set_upload(make_scoped_ptr
<UploadDataStream
>(
5173 new ElementsUploadDataStream(element_readers
.Pass(), 0)));
5176 EXPECT_TRUE(r
->is_pending());
5178 base::RunLoop().Run();
5181 ASSERT_EQ(true, base::GetFileSize(path
, &size64
));
5182 ASSERT_LE(size64
, std::numeric_limits
<int>::max());
5183 int size
= static_cast<int>(size64
);
5184 scoped_ptr
<char[]> buf(new char[size
]);
5186 ASSERT_EQ(size
, base::ReadFile(path
, buf
.get(), size
));
5188 ASSERT_EQ(1, d
.response_started_count())
5189 << "request failed: " << r
->status().status()
5190 << ", error: " << r
->status().error();
5192 EXPECT_FALSE(d
.received_data_before_response());
5194 EXPECT_EQ(size
, d
.bytes_received());
5195 EXPECT_EQ(std::string(&buf
[0], size
), d
.data_received());
5199 TEST_F(URLRequestTestHTTP
, PostUnreadableFileTest
) {
5200 ASSERT_TRUE(test_server_
.Start());
5204 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5205 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
));
5206 r
->set_method("POST");
5208 ScopedVector
<UploadElementReader
> element_readers
;
5210 element_readers
.push_back(new UploadFileElementReader(
5211 base::MessageLoopProxy::current().get(),
5212 base::FilePath(FILE_PATH_LITERAL(
5213 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5217 r
->set_upload(make_scoped_ptr
<UploadDataStream
>(
5218 new ElementsUploadDataStream(element_readers
.Pass(), 0)));
5221 EXPECT_TRUE(r
->is_pending());
5223 base::RunLoop().Run();
5225 EXPECT_TRUE(d
.request_failed());
5226 EXPECT_FALSE(d
.received_data_before_response());
5227 EXPECT_EQ(0, d
.bytes_received());
5228 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
5229 EXPECT_EQ(ERR_FILE_NOT_FOUND
, r
->status().error());
5233 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataBeforeStart
) {
5234 ASSERT_TRUE(test_server_
.Start());
5238 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5239 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
));
5240 r
->EnableChunkedUpload();
5241 r
->set_method("POST");
5242 AddChunksToUpload(r
.get());
5244 EXPECT_TRUE(r
->is_pending());
5246 base::RunLoop().Run();
5248 VerifyReceivedDataMatchesChunks(r
.get(), &d
);
5252 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataJustAfterStart
) {
5253 ASSERT_TRUE(test_server_
.Start());
5257 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5258 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
));
5259 r
->EnableChunkedUpload();
5260 r
->set_method("POST");
5262 EXPECT_TRUE(r
->is_pending());
5263 AddChunksToUpload(r
.get());
5264 base::RunLoop().Run();
5266 VerifyReceivedDataMatchesChunks(r
.get(), &d
);
5270 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataAfterStart
) {
5271 ASSERT_TRUE(test_server_
.Start());
5275 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5276 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
));
5277 r
->EnableChunkedUpload();
5278 r
->set_method("POST");
5280 EXPECT_TRUE(r
->is_pending());
5282 base::RunLoop().RunUntilIdle();
5283 AddChunksToUpload(r
.get());
5284 base::RunLoop().Run();
5286 VerifyReceivedDataMatchesChunks(r
.get(), &d
);
5290 TEST_F(URLRequestTestHTTP
, ResponseHeadersTest
) {
5291 ASSERT_TRUE(test_server_
.Start());
5294 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5295 test_server_
.GetURL("files/with-headers.html"), DEFAULT_PRIORITY
, &d
));
5297 base::RunLoop().Run();
5299 const HttpResponseHeaders
* headers
= req
->response_headers();
5301 // Simple sanity check that response_info() accesses the same data.
5302 EXPECT_EQ(headers
, req
->response_info().headers
.get());
5305 EXPECT_TRUE(headers
->GetNormalizedHeader("cache-control", &header
));
5306 EXPECT_EQ("private", header
);
5309 EXPECT_TRUE(headers
->GetNormalizedHeader("content-type", &header
));
5310 EXPECT_EQ("text/html; charset=ISO-8859-1", header
);
5312 // The response has two "X-Multiple-Entries" headers.
5313 // This verfies our output has them concatenated together.
5315 EXPECT_TRUE(headers
->GetNormalizedHeader("x-multiple-entries", &header
));
5316 EXPECT_EQ("a, b", header
);
5319 TEST_F(URLRequestTestHTTP
, ProcessSTS
) {
5320 SpawnedTestServer::SSLOptions
ssl_options(
5321 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN
);
5322 SpawnedTestServer
https_test_server(
5323 SpawnedTestServer::TYPE_HTTPS
,
5325 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5326 ASSERT_TRUE(https_test_server
.Start());
5328 std::string test_server_hostname
= https_test_server
.GetURL("").host();
5331 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5332 https_test_server
.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY
,
5335 base::RunLoop().Run();
5337 TransportSecurityState
* security_state
=
5338 default_context_
.transport_security_state();
5339 TransportSecurityState::DomainState domain_state
;
5340 EXPECT_TRUE(security_state
->GetDynamicDomainState(test_server_hostname
,
5342 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5343 domain_state
.sts
.upgrade_mode
);
5344 EXPECT_TRUE(domain_state
.sts
.include_subdomains
);
5345 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5346 #if defined(OS_ANDROID)
5347 // Android's CertVerifyProc does not (yet) handle pins.
5349 EXPECT_FALSE(domain_state
.HasPublicKeyPins());
5353 TEST_F(URLRequestTestHTTP
, STSNotProcessedOnIP
) {
5354 SpawnedTestServer
https_test_server(
5355 SpawnedTestServer::TYPE_HTTPS
, SpawnedTestServer::SSLOptions(),
5356 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5357 ASSERT_TRUE(https_test_server
.Start());
5358 // Make sure this test fails if the test server is changed to not
5359 // listen on an IP by default.
5360 ASSERT_TRUE(https_test_server
.GetURL("").HostIsIPAddress());
5361 std::string test_server_hostname
= https_test_server
.GetURL("").host();
5364 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5365 https_test_server
.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY
,
5368 base::RunLoop().Run();
5370 TransportSecurityState
* security_state
=
5371 default_context_
.transport_security_state();
5372 TransportSecurityState::DomainState domain_state
;
5373 EXPECT_FALSE(security_state
->GetDynamicDomainState(test_server_hostname
,
5377 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5378 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5379 // DomainState present because header rejected).
5380 #if defined(OS_ANDROID)
5381 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5383 #define MAYBE_ProcessPKP ProcessPKP
5386 // Tests that enabling HPKP on a domain does not affect the HSTS
5387 // validity/expiration.
5388 TEST_F(URLRequestTestHTTP
, MAYBE_ProcessPKP
) {
5389 SpawnedTestServer::SSLOptions
ssl_options(
5390 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN
);
5391 SpawnedTestServer
https_test_server(
5392 SpawnedTestServer::TYPE_HTTPS
,
5394 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5395 ASSERT_TRUE(https_test_server
.Start());
5397 std::string test_server_hostname
= https_test_server
.GetURL("").host();
5400 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5401 https_test_server
.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY
,
5404 base::RunLoop().Run();
5406 TransportSecurityState
* security_state
=
5407 default_context_
.transport_security_state();
5408 TransportSecurityState::DomainState domain_state
;
5409 EXPECT_TRUE(security_state
->GetDynamicDomainState(test_server_hostname
,
5411 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT
,
5412 domain_state
.sts
.upgrade_mode
);
5413 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5414 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5415 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5416 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5419 TEST_F(URLRequestTestHTTP
, PKPNotProcessedOnIP
) {
5420 SpawnedTestServer
https_test_server(
5421 SpawnedTestServer::TYPE_HTTPS
, SpawnedTestServer::SSLOptions(),
5422 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5423 ASSERT_TRUE(https_test_server
.Start());
5424 // Make sure this test fails if the test server is changed to not
5425 // listen on an IP by default.
5426 ASSERT_TRUE(https_test_server
.GetURL("").HostIsIPAddress());
5427 std::string test_server_hostname
= https_test_server
.GetURL("").host();
5430 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5431 https_test_server
.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY
,
5434 base::RunLoop().Run();
5436 TransportSecurityState
* security_state
=
5437 default_context_
.transport_security_state();
5438 TransportSecurityState::DomainState domain_state
;
5439 EXPECT_FALSE(security_state
->GetDynamicDomainState(test_server_hostname
,
5443 TEST_F(URLRequestTestHTTP
, ProcessSTSOnce
) {
5444 SpawnedTestServer::SSLOptions
ssl_options(
5445 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN
);
5446 SpawnedTestServer
https_test_server(
5447 SpawnedTestServer::TYPE_HTTPS
,
5449 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5450 ASSERT_TRUE(https_test_server
.Start());
5452 std::string test_server_hostname
= https_test_server
.GetURL("").host();
5455 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5456 https_test_server
.GetURL("files/hsts-multiple-headers.html"),
5457 DEFAULT_PRIORITY
, &d
));
5459 base::RunLoop().Run();
5461 // We should have set parameters from the first header, not the second.
5462 TransportSecurityState
* security_state
=
5463 default_context_
.transport_security_state();
5464 TransportSecurityState::DomainState domain_state
;
5465 EXPECT_TRUE(security_state
->GetDynamicDomainState(test_server_hostname
,
5467 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5468 domain_state
.sts
.upgrade_mode
);
5469 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5470 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5473 TEST_F(URLRequestTestHTTP
, ProcessSTSAndPKP
) {
5474 SpawnedTestServer::SSLOptions
ssl_options(
5475 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN
);
5476 SpawnedTestServer
https_test_server(
5477 SpawnedTestServer::TYPE_HTTPS
,
5479 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5480 ASSERT_TRUE(https_test_server
.Start());
5482 std::string test_server_hostname
= https_test_server
.GetURL("").host();
5485 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5486 https_test_server
.GetURL("files/hsts-and-hpkp-headers.html"),
5487 DEFAULT_PRIORITY
, &d
));
5489 base::RunLoop().Run();
5491 // We should have set parameters from the first header, not the second.
5492 TransportSecurityState
* security_state
=
5493 default_context_
.transport_security_state();
5494 TransportSecurityState::DomainState domain_state
;
5495 EXPECT_TRUE(security_state
->GetDynamicDomainState(test_server_hostname
,
5497 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5498 domain_state
.sts
.upgrade_mode
);
5499 #if defined(OS_ANDROID)
5500 // Android's CertVerifyProc does not (yet) handle pins.
5502 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5504 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5506 // Even though there is an HSTS header asserting includeSubdomains, it is
5507 // the *second* such header, and we MUST process only the first.
5508 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5509 // includeSubdomains does not occur in the test HPKP header.
5510 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5513 // Tests that when multiple HPKP headers are present, asserting different
5514 // policies, that only the first such policy is processed.
5515 TEST_F(URLRequestTestHTTP
, ProcessSTSAndPKP2
) {
5516 SpawnedTestServer::SSLOptions
ssl_options(
5517 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN
);
5518 SpawnedTestServer
https_test_server(
5519 SpawnedTestServer::TYPE_HTTPS
,
5521 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5522 ASSERT_TRUE(https_test_server
.Start());
5524 std::string test_server_hostname
= https_test_server
.GetURL("").host();
5527 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5528 https_test_server
.GetURL("files/hsts-and-hpkp-headers2.html"),
5529 DEFAULT_PRIORITY
, &d
));
5531 base::RunLoop().Run();
5533 TransportSecurityState
* security_state
=
5534 default_context_
.transport_security_state();
5535 TransportSecurityState::DomainState domain_state
;
5536 EXPECT_TRUE(security_state
->GetDynamicDomainState(test_server_hostname
,
5538 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5539 domain_state
.sts
.upgrade_mode
);
5540 #if defined(OS_ANDROID)
5541 // Android's CertVerifyProc does not (yet) handle pins.
5543 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5545 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5547 EXPECT_TRUE(domain_state
.sts
.include_subdomains
);
5548 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5551 TEST_F(URLRequestTestHTTP
, ContentTypeNormalizationTest
) {
5552 ASSERT_TRUE(test_server_
.Start());
5555 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5556 test_server_
.GetURL("files/content-type-normalization.html"),
5557 DEFAULT_PRIORITY
, &d
));
5559 base::RunLoop().Run();
5561 std::string mime_type
;
5562 req
->GetMimeType(&mime_type
);
5563 EXPECT_EQ("text/html", mime_type
);
5565 std::string charset
;
5566 req
->GetCharset(&charset
);
5567 EXPECT_EQ("utf-8", charset
);
5571 TEST_F(URLRequestTestHTTP
, ProtocolHandlerAndFactoryRestrictDataRedirects
) {
5572 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5573 GURL
data_url("data:,foo");
5574 DataProtocolHandler data_protocol_handler
;
5575 EXPECT_FALSE(data_protocol_handler
.IsSafeRedirectTarget(data_url
));
5577 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5578 EXPECT_FALSE(job_factory_
->IsSafeRedirectTarget(data_url
));
5581 #if !defined(DISABLE_FILE_SUPPORT)
5582 TEST_F(URLRequestTestHTTP
, ProtocolHandlerAndFactoryRestrictFileRedirects
) {
5583 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5584 GURL
file_url("file:///foo.txt");
5585 FileProtocolHandler
file_protocol_handler(base::MessageLoopProxy::current());
5586 EXPECT_FALSE(file_protocol_handler
.IsSafeRedirectTarget(file_url
));
5588 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5589 EXPECT_FALSE(job_factory_
->IsSafeRedirectTarget(file_url
));
5592 TEST_F(URLRequestTestHTTP
, RestrictFileRedirects
) {
5593 ASSERT_TRUE(test_server_
.Start());
5596 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5597 test_server_
.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY
,
5600 base::RunLoop().Run();
5602 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
5603 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, req
->status().error());
5605 #endif // !defined(DISABLE_FILE_SUPPORT)
5607 TEST_F(URLRequestTestHTTP
, RestrictDataRedirects
) {
5608 ASSERT_TRUE(test_server_
.Start());
5611 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5612 test_server_
.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY
,
5615 base::MessageLoop::current()->Run();
5617 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
5618 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, req
->status().error());
5621 TEST_F(URLRequestTestHTTP
, RedirectToInvalidURL
) {
5622 ASSERT_TRUE(test_server_
.Start());
5625 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5626 test_server_
.GetURL("files/redirect-to-invalid-url.html"),
5627 DEFAULT_PRIORITY
, &d
));
5629 base::RunLoop().Run();
5631 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
5632 EXPECT_EQ(ERR_INVALID_URL
, req
->status().error());
5635 // Make sure redirects are cached, despite not reading their bodies.
5636 TEST_F(URLRequestTestHTTP
, CacheRedirect
) {
5637 ASSERT_TRUE(test_server_
.Start());
5639 test_server_
.GetURL("files/redirect302-to-echo-cacheable");
5643 scoped_ptr
<URLRequest
> req(
5644 default_context_
.CreateRequest(redirect_url
, DEFAULT_PRIORITY
, &d
));
5646 base::RunLoop().Run();
5647 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5648 EXPECT_EQ(1, d
.received_redirect_count());
5649 EXPECT_EQ(test_server_
.GetURL("echo"), req
->url());
5654 d
.set_quit_on_redirect(true);
5655 scoped_ptr
<URLRequest
> req(
5656 default_context_
.CreateRequest(redirect_url
, DEFAULT_PRIORITY
, &d
));
5658 base::RunLoop().Run();
5660 EXPECT_EQ(1, d
.received_redirect_count());
5661 EXPECT_EQ(0, d
.response_started_count());
5662 EXPECT_TRUE(req
->was_cached());
5664 req
->FollowDeferredRedirect();
5665 base::RunLoop().Run();
5666 EXPECT_EQ(1, d
.received_redirect_count());
5667 EXPECT_EQ(1, d
.response_started_count());
5668 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5669 EXPECT_EQ(test_server_
.GetURL("echo"), req
->url());
5673 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5674 // when the headers are read, since the body won't have been read.
5675 TEST_F(URLRequestTestHTTP
, NoCacheOnNetworkDelegateRedirect
) {
5676 ASSERT_TRUE(test_server_
.Start());
5677 // URL that is normally cached.
5678 GURL initial_url
= test_server_
.GetURL("cachetime");
5681 // Set up the TestNetworkDelegate tp force a redirect.
5682 GURL redirect_to_url
= test_server_
.GetURL("echo");
5683 default_network_delegate_
.set_redirect_on_headers_received_url(
5687 scoped_ptr
<URLRequest
> req(
5688 default_context_
.CreateRequest(initial_url
, DEFAULT_PRIORITY
, &d
));
5690 base::RunLoop().Run();
5691 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5692 EXPECT_EQ(1, d
.received_redirect_count());
5693 EXPECT_EQ(redirect_to_url
, req
->url());
5698 scoped_ptr
<URLRequest
> req(
5699 default_context_
.CreateRequest(initial_url
, DEFAULT_PRIORITY
, &d
));
5701 base::RunLoop().Run();
5703 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5704 EXPECT_FALSE(req
->was_cached());
5705 EXPECT_EQ(0, d
.received_redirect_count());
5706 EXPECT_EQ(initial_url
, req
->url());
5710 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5712 TEST_F(URLRequestTestHTTP
, UnsafeRedirectToWhitelistedUnsafeURL
) {
5713 ASSERT_TRUE(test_server_
.Start());
5715 GURL
unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5716 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5717 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5721 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5722 test_server_
.GetURL("whatever"), DEFAULT_PRIORITY
, &d
));
5725 base::RunLoop().Run();
5727 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5729 EXPECT_EQ(2U, r
->url_chain().size());
5730 EXPECT_EQ(OK
, r
->status().error());
5731 EXPECT_EQ(unsafe_url
, r
->url());
5732 EXPECT_EQ("this-is-considered-an-unsafe-url", d
.data_received());
5736 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5737 // some other URL to the whitelist.
5738 TEST_F(URLRequestTestHTTP
, UnsafeRedirectToDifferentUnsafeURL
) {
5739 ASSERT_TRUE(test_server_
.Start());
5741 GURL
unsafe_url("data:text/html,something");
5742 GURL
different_unsafe_url("data:text/html,something-else");
5743 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5744 default_network_delegate_
.set_allowed_unsafe_redirect_url(
5745 different_unsafe_url
);
5749 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5750 test_server_
.GetURL("whatever"), DEFAULT_PRIORITY
, &d
));
5753 base::RunLoop().Run();
5755 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
5756 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, r
->status().error());
5760 // Redirects from an URL with fragment to an unsafe URL with fragment should
5761 // be allowed, and the reference fragment of the target URL should be preserved.
5762 TEST_F(URLRequestTestHTTP
, UnsafeRedirectWithDifferentReferenceFragment
) {
5763 ASSERT_TRUE(test_server_
.Start());
5765 GURL
original_url(test_server_
.GetURL("original#fragment1"));
5766 GURL
unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5767 GURL
expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5769 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5770 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5774 scoped_ptr
<URLRequest
> r(
5775 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
5778 base::RunLoop().Run();
5780 EXPECT_EQ(2U, r
->url_chain().size());
5781 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5782 EXPECT_EQ(OK
, r
->status().error());
5783 EXPECT_EQ(original_url
, r
->original_url());
5784 EXPECT_EQ(expected_url
, r
->url());
5788 // When a delegate has specified a safe redirect URL, but it does not match the
5789 // redirect target, then do not prevent the reference fragment from being added.
5790 TEST_F(URLRequestTestHTTP
, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl
) {
5791 ASSERT_TRUE(test_server_
.Start());
5793 GURL
original_url(test_server_
.GetURL("original#expected-fragment"));
5794 GURL
unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5795 GURL
redirect_url(test_server_
.GetURL("target"));
5796 GURL
expected_redirect_url(test_server_
.GetURL("target#expected-fragment"));
5798 default_network_delegate_
.set_redirect_on_headers_received_url(redirect_url
);
5799 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5803 scoped_ptr
<URLRequest
> r(
5804 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
5807 base::RunLoop().Run();
5809 EXPECT_EQ(2U, r
->url_chain().size());
5810 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5811 EXPECT_EQ(OK
, r
->status().error());
5812 EXPECT_EQ(original_url
, r
->original_url());
5813 EXPECT_EQ(expected_redirect_url
, r
->url());
5817 // When a delegate has specified a safe redirect URL, assume that the redirect
5818 // URL should not be changed. In particular, the reference fragment should not
5820 TEST_F(URLRequestTestHTTP
, RedirectWithReferenceFragment
) {
5821 ASSERT_TRUE(test_server_
.Start());
5823 GURL
original_url(test_server_
.GetURL("original#should-not-be-appended"));
5824 GURL
redirect_url("data:text/html,expect-no-reference-fragment");
5826 default_network_delegate_
.set_redirect_on_headers_received_url(redirect_url
);
5827 default_network_delegate_
.set_allowed_unsafe_redirect_url(redirect_url
);
5831 scoped_ptr
<URLRequest
> r(
5832 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
5835 base::RunLoop().Run();
5837 EXPECT_EQ(2U, r
->url_chain().size());
5838 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5839 EXPECT_EQ(OK
, r
->status().error());
5840 EXPECT_EQ(original_url
, r
->original_url());
5841 EXPECT_EQ(redirect_url
, r
->url());
5845 // When a URLRequestRedirectJob is created, the redirection must be followed and
5846 // the reference fragment of the target URL must not be modified.
5847 TEST_F(URLRequestTestHTTP
, RedirectJobWithReferenceFragment
) {
5848 ASSERT_TRUE(test_server_
.Start());
5850 GURL
original_url(test_server_
.GetURL("original#should-not-be-appended"));
5851 GURL
redirect_url(test_server_
.GetURL("echo"));
5854 scoped_ptr
<URLRequest
> r(
5855 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
5857 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
5858 r
.get(), &default_network_delegate_
, redirect_url
,
5859 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
5860 AddTestInterceptor()->set_main_intercept_job(job
);
5863 base::RunLoop().Run();
5865 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5866 EXPECT_EQ(OK
, r
->status().error());
5867 EXPECT_EQ(original_url
, r
->original_url());
5868 EXPECT_EQ(redirect_url
, r
->url());
5871 TEST_F(URLRequestTestHTTP
, NoUserPassInReferrer
) {
5872 ASSERT_TRUE(test_server_
.Start());
5875 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5876 test_server_
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
));
5877 req
->SetReferrer("http://user:pass@foo.com/");
5879 base::RunLoop().Run();
5881 EXPECT_EQ(std::string("http://foo.com/"), d
.data_received());
5884 TEST_F(URLRequestTestHTTP
, NoFragmentInReferrer
) {
5885 ASSERT_TRUE(test_server_
.Start());
5888 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5889 test_server_
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
));
5890 req
->SetReferrer("http://foo.com/test#fragment");
5892 base::RunLoop().Run();
5894 EXPECT_EQ(std::string("http://foo.com/test"), d
.data_received());
5897 TEST_F(URLRequestTestHTTP
, EmptyReferrerAfterValidReferrer
) {
5898 ASSERT_TRUE(test_server_
.Start());
5901 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5902 test_server_
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
));
5903 req
->SetReferrer("http://foo.com/test#fragment");
5904 req
->SetReferrer("");
5906 base::RunLoop().Run();
5908 EXPECT_EQ(std::string("None"), d
.data_received());
5911 // Defer network start and then resume, checking that the request was a success
5912 // and bytes were received.
5913 TEST_F(URLRequestTestHTTP
, DeferredBeforeNetworkStart
) {
5914 ASSERT_TRUE(test_server_
.Start());
5918 d
.set_quit_on_network_start(true);
5919 GURL
test_url(test_server_
.GetURL("echo"));
5920 scoped_ptr
<URLRequest
> req(
5921 default_context_
.CreateRequest(test_url
, DEFAULT_PRIORITY
, &d
));
5924 base::RunLoop().Run();
5926 EXPECT_EQ(1, d
.received_before_network_start_count());
5927 EXPECT_EQ(0, d
.response_started_count());
5929 req
->ResumeNetworkStart();
5930 base::RunLoop().Run();
5932 EXPECT_EQ(1, d
.response_started_count());
5933 EXPECT_NE(0, d
.bytes_received());
5934 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5938 // Check that OnBeforeNetworkStart is only called once even if there is a
5940 TEST_F(URLRequestTestHTTP
, BeforeNetworkStartCalledOnce
) {
5941 ASSERT_TRUE(test_server_
.Start());
5945 d
.set_quit_on_redirect(true);
5946 d
.set_quit_on_network_start(true);
5947 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5948 test_server_
.GetURL("server-redirect?echo"), DEFAULT_PRIORITY
, &d
));
5951 base::RunLoop().Run();
5953 EXPECT_EQ(1, d
.received_before_network_start_count());
5954 EXPECT_EQ(0, d
.response_started_count());
5955 EXPECT_EQ(0, d
.received_redirect_count());
5957 req
->ResumeNetworkStart();
5958 base::RunLoop().Run();
5960 EXPECT_EQ(1, d
.received_redirect_count());
5961 req
->FollowDeferredRedirect();
5962 base::RunLoop().Run();
5964 // Check that the redirect's new network transaction does not get propagated
5965 // to a second OnBeforeNetworkStart() notification.
5966 EXPECT_EQ(1, d
.received_before_network_start_count());
5968 EXPECT_EQ(1, d
.response_started_count());
5969 EXPECT_NE(0, d
.bytes_received());
5970 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5974 // Cancel the request after learning that the request would use the network.
5975 TEST_F(URLRequestTestHTTP
, CancelOnBeforeNetworkStart
) {
5976 ASSERT_TRUE(test_server_
.Start());
5980 d
.set_quit_on_network_start(true);
5981 GURL
test_url(test_server_
.GetURL("echo"));
5982 scoped_ptr
<URLRequest
> req(
5983 default_context_
.CreateRequest(test_url
, DEFAULT_PRIORITY
, &d
));
5986 base::RunLoop().Run();
5988 EXPECT_EQ(1, d
.received_before_network_start_count());
5989 EXPECT_EQ(0, d
.response_started_count());
5992 base::RunLoop().Run();
5994 EXPECT_EQ(1, d
.response_started_count());
5995 EXPECT_EQ(0, d
.bytes_received());
5996 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
6000 TEST_F(URLRequestTestHTTP
, CancelRedirect
) {
6001 ASSERT_TRUE(test_server_
.Start());
6005 d
.set_cancel_in_received_redirect(true);
6006 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6007 test_server_
.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY
, &d
));
6009 base::RunLoop().Run();
6011 EXPECT_EQ(1, d
.response_started_count());
6012 EXPECT_EQ(0, d
.bytes_received());
6013 EXPECT_FALSE(d
.received_data_before_response());
6014 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
6018 TEST_F(URLRequestTestHTTP
, DeferredRedirect
) {
6019 ASSERT_TRUE(test_server_
.Start());
6023 d
.set_quit_on_redirect(true);
6024 GURL
test_url(test_server_
.GetURL("files/redirect-test.html"));
6025 scoped_ptr
<URLRequest
> req(
6026 default_context_
.CreateRequest(test_url
, DEFAULT_PRIORITY
, &d
));
6029 base::RunLoop().Run();
6031 EXPECT_EQ(1, d
.received_redirect_count());
6033 req
->FollowDeferredRedirect();
6034 base::RunLoop().Run();
6036 EXPECT_EQ(1, d
.response_started_count());
6037 EXPECT_FALSE(d
.received_data_before_response());
6038 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
6040 base::FilePath path
;
6041 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
6042 path
= path
.Append(FILE_PATH_LITERAL("net"));
6043 path
= path
.Append(FILE_PATH_LITERAL("data"));
6044 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
6045 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
6047 std::string contents
;
6048 EXPECT_TRUE(base::ReadFileToString(path
, &contents
));
6049 EXPECT_EQ(contents
, d
.data_received());
6053 TEST_F(URLRequestTestHTTP
, DeferredRedirect_GetFullRequestHeaders
) {
6054 ASSERT_TRUE(test_server_
.Start());
6058 d
.set_quit_on_redirect(true);
6059 GURL
test_url(test_server_
.GetURL("files/redirect-test.html"));
6060 scoped_ptr
<URLRequest
> req(
6061 default_context_
.CreateRequest(test_url
, DEFAULT_PRIORITY
, &d
));
6063 EXPECT_FALSE(d
.have_full_request_headers());
6066 base::RunLoop().Run();
6068 EXPECT_EQ(1, d
.received_redirect_count());
6069 EXPECT_TRUE(d
.have_full_request_headers());
6070 CheckFullRequestHeaders(d
.full_request_headers(), test_url
);
6071 d
.ClearFullRequestHeaders();
6073 req
->FollowDeferredRedirect();
6074 base::RunLoop().Run();
6076 GURL
target_url(test_server_
.GetURL("files/with-headers.html"));
6077 EXPECT_EQ(1, d
.response_started_count());
6078 EXPECT_TRUE(d
.have_full_request_headers());
6079 CheckFullRequestHeaders(d
.full_request_headers(), target_url
);
6080 EXPECT_FALSE(d
.received_data_before_response());
6081 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
6083 base::FilePath path
;
6084 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
6085 path
= path
.Append(FILE_PATH_LITERAL("net"));
6086 path
= path
.Append(FILE_PATH_LITERAL("data"));
6087 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
6088 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
6090 std::string contents
;
6091 EXPECT_TRUE(base::ReadFileToString(path
, &contents
));
6092 EXPECT_EQ(contents
, d
.data_received());
6096 TEST_F(URLRequestTestHTTP
, CancelDeferredRedirect
) {
6097 ASSERT_TRUE(test_server_
.Start());
6101 d
.set_quit_on_redirect(true);
6102 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6103 test_server_
.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY
, &d
));
6105 base::RunLoop().Run();
6107 EXPECT_EQ(1, d
.received_redirect_count());
6110 base::RunLoop().Run();
6112 EXPECT_EQ(1, d
.response_started_count());
6113 EXPECT_EQ(0, d
.bytes_received());
6114 EXPECT_FALSE(d
.received_data_before_response());
6115 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
6119 TEST_F(URLRequestTestHTTP
, VaryHeader
) {
6120 ASSERT_TRUE(test_server_
.Start());
6122 // Populate the cache.
6125 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6126 test_server_
.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY
, &d
));
6127 HttpRequestHeaders headers
;
6128 headers
.SetHeader("foo", "1");
6129 req
->SetExtraRequestHeaders(headers
);
6131 base::RunLoop().Run();
6133 LoadTimingInfo load_timing_info
;
6134 req
->GetLoadTimingInfo(&load_timing_info
);
6135 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
6138 // Expect a cache hit.
6141 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6142 test_server_
.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY
, &d
));
6143 HttpRequestHeaders headers
;
6144 headers
.SetHeader("foo", "1");
6145 req
->SetExtraRequestHeaders(headers
);
6147 base::RunLoop().Run();
6149 EXPECT_TRUE(req
->was_cached());
6151 LoadTimingInfo load_timing_info
;
6152 req
->GetLoadTimingInfo(&load_timing_info
);
6153 TestLoadTimingCacheHitNoNetwork(load_timing_info
);
6156 // Expect a cache miss.
6159 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6160 test_server_
.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY
, &d
));
6161 HttpRequestHeaders headers
;
6162 headers
.SetHeader("foo", "2");
6163 req
->SetExtraRequestHeaders(headers
);
6165 base::RunLoop().Run();
6167 EXPECT_FALSE(req
->was_cached());
6169 LoadTimingInfo load_timing_info
;
6170 req
->GetLoadTimingInfo(&load_timing_info
);
6171 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
6175 TEST_F(URLRequestTestHTTP
, BasicAuth
) {
6176 ASSERT_TRUE(test_server_
.Start());
6178 // populate the cache
6181 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
6183 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6184 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
));
6187 base::RunLoop().Run();
6189 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
6192 // repeat request with end-to-end validation. since auth-basic results in a
6193 // cachable page, we expect this test to result in a 304. in which case, the
6194 // response should be fetched from the cache.
6197 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
6199 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6200 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
));
6201 r
->SetLoadFlags(LOAD_VALIDATE_CACHE
);
6204 base::RunLoop().Run();
6206 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
6208 // Should be the same cached document.
6209 EXPECT_TRUE(r
->was_cached());
6213 // Check that Set-Cookie headers in 401 responses are respected.
6214 // http://crbug.com/6450
6215 TEST_F(URLRequestTestHTTP
, BasicAuthWithCookies
) {
6216 ASSERT_TRUE(test_server_
.Start());
6218 GURL url_requiring_auth
=
6219 test_server_
.GetURL("auth-basic?set-cookie-if-challenged");
6221 // Request a page that will give a 401 containing a Set-Cookie header.
6222 // Verify that when the transaction is restarted, it includes the new cookie.
6224 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6225 TestURLRequestContext
context(true);
6226 context
.set_network_delegate(&network_delegate
);
6230 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
6232 scoped_ptr
<URLRequest
> r(
6233 context
.CreateRequest(url_requiring_auth
, DEFAULT_PRIORITY
, &d
));
6236 base::RunLoop().Run();
6238 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
6240 // Make sure we sent the cookie in the restarted transaction.
6241 EXPECT_TRUE(d
.data_received().find("Cookie: got_challenged=true")
6242 != std::string::npos
);
6245 // Same test as above, except this time the restart is initiated earlier
6246 // (without user intervention since identity is embedded in the URL).
6248 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6249 TestURLRequestContext
context(true);
6250 context
.set_network_delegate(&network_delegate
);
6255 GURL::Replacements replacements
;
6256 replacements
.SetUsernameStr("user2");
6257 replacements
.SetPasswordStr("secret");
6258 GURL url_with_identity
= url_requiring_auth
.ReplaceComponents(replacements
);
6260 scoped_ptr
<URLRequest
> r(
6261 context
.CreateRequest(url_with_identity
, DEFAULT_PRIORITY
, &d
));
6264 base::RunLoop().Run();
6266 EXPECT_TRUE(d
.data_received().find("user2/secret") != std::string::npos
);
6268 // Make sure we sent the cookie in the restarted transaction.
6269 EXPECT_TRUE(d
.data_received().find("Cookie: got_challenged=true")
6270 != std::string::npos
);
6274 // Tests that load timing works as expected with auth and the cache.
6275 TEST_F(URLRequestTestHTTP
, BasicAuthLoadTiming
) {
6276 ASSERT_TRUE(test_server_
.Start());
6278 // populate the cache
6281 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
6283 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6284 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
));
6287 base::RunLoop().Run();
6289 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
6291 LoadTimingInfo load_timing_info_before_auth
;
6292 EXPECT_TRUE(default_network_delegate_
.GetLoadTimingInfoBeforeAuth(
6293 &load_timing_info_before_auth
));
6294 TestLoadTimingNotReused(load_timing_info_before_auth
,
6295 CONNECT_TIMING_HAS_DNS_TIMES
);
6297 LoadTimingInfo load_timing_info
;
6298 r
->GetLoadTimingInfo(&load_timing_info
);
6299 // The test server does not support keep alive sockets, so the second
6300 // request with auth should use a new socket.
6301 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
6302 EXPECT_NE(load_timing_info_before_auth
.socket_log_id
,
6303 load_timing_info
.socket_log_id
);
6304 EXPECT_LE(load_timing_info_before_auth
.receive_headers_end
,
6305 load_timing_info
.connect_timing
.connect_start
);
6308 // Repeat request with end-to-end validation. Since auth-basic results in a
6309 // cachable page, we expect this test to result in a 304. In which case, the
6310 // response should be fetched from the cache.
6313 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
6315 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6316 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
));
6317 r
->SetLoadFlags(LOAD_VALIDATE_CACHE
);
6320 base::RunLoop().Run();
6322 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
6324 // Should be the same cached document.
6325 EXPECT_TRUE(r
->was_cached());
6327 // Since there was a request that went over the wire, the load timing
6328 // information should include connection times.
6329 LoadTimingInfo load_timing_info
;
6330 r
->GetLoadTimingInfo(&load_timing_info
);
6331 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
6335 // In this test, we do a POST which the server will 302 redirect.
6336 // The subsequent transaction should use GET, and should not send the
6337 // Content-Type header.
6338 // http://code.google.com/p/chromium/issues/detail?id=843
6339 TEST_F(URLRequestTestHTTP
, Post302RedirectGet
) {
6340 ASSERT_TRUE(test_server_
.Start());
6342 const char kData
[] = "hello world";
6345 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6346 test_server_
.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY
, &d
));
6347 req
->set_method("POST");
6348 req
->set_upload(CreateSimpleUploadData(kData
));
6350 // Set headers (some of which are specific to the POST).
6351 HttpRequestHeaders headers
;
6352 headers
.AddHeadersFromString(
6353 "Content-Type: multipart/form-data; "
6354 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6355 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6356 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6357 "Accept-Language: en-US,en\r\n"
6358 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6359 "Content-Length: 11\r\n"
6360 "Origin: http://localhost:1337/");
6361 req
->SetExtraRequestHeaders(headers
);
6363 base::RunLoop().Run();
6365 std::string mime_type
;
6366 req
->GetMimeType(&mime_type
);
6367 EXPECT_EQ("text/html", mime_type
);
6369 const std::string
& data
= d
.data_received();
6371 // Check that the post-specific headers were stripped:
6372 EXPECT_FALSE(ContainsString(data
, "Content-Length:"));
6373 EXPECT_FALSE(ContainsString(data
, "Content-Type:"));
6374 EXPECT_FALSE(ContainsString(data
, "Origin:"));
6376 // These extra request headers should not have been stripped.
6377 EXPECT_TRUE(ContainsString(data
, "Accept:"));
6378 EXPECT_TRUE(ContainsString(data
, "Accept-Language:"));
6379 EXPECT_TRUE(ContainsString(data
, "Accept-Charset:"));
6382 // The following tests check that we handle mutating the request for HTTP
6383 // redirects as expected.
6384 // See https://crbug.com/56373, https://crbug.com/102130, and
6385 // https://crbug.com/465517.
6387 TEST_F(URLRequestTestHTTP
, Redirect301Tests
) {
6388 ASSERT_TRUE(test_server_
.Start());
6390 const GURL url
= test_server_
.GetURL("files/redirect301-to-echo");
6391 const GURL https_redirect_url
=
6392 test_server_
.GetURL("files/redirect301-to-https");
6394 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6395 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6396 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6398 HTTPRedirectOriginHeaderTest(url
, "GET", "GET", url
.GetOrigin().spec());
6399 HTTPRedirectOriginHeaderTest(https_redirect_url
, "GET", "GET", "null");
6400 HTTPRedirectOriginHeaderTest(url
, "POST", "GET", std::string());
6401 HTTPRedirectOriginHeaderTest(https_redirect_url
, "POST", "GET",
6405 TEST_F(URLRequestTestHTTP
, Redirect302Tests
) {
6406 ASSERT_TRUE(test_server_
.Start());
6408 const GURL url
= test_server_
.GetURL("files/redirect302-to-echo");
6409 const GURL https_redirect_url
=
6410 test_server_
.GetURL("files/redirect302-to-https");
6412 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6413 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6414 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6416 HTTPRedirectOriginHeaderTest(url
, "GET", "GET", url
.GetOrigin().spec());
6417 HTTPRedirectOriginHeaderTest(https_redirect_url
, "GET", "GET", "null");
6418 HTTPRedirectOriginHeaderTest(url
, "POST", "GET", std::string());
6419 HTTPRedirectOriginHeaderTest(https_redirect_url
, "POST", "GET",
6423 TEST_F(URLRequestTestHTTP
, Redirect303Tests
) {
6424 ASSERT_TRUE(test_server_
.Start());
6426 const GURL url
= test_server_
.GetURL("files/redirect303-to-echo");
6427 const GURL https_redirect_url
=
6428 test_server_
.GetURL("files/redirect303-to-https");
6430 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6431 HTTPRedirectMethodTest(url
, "PUT", "GET", true);
6432 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6434 HTTPRedirectOriginHeaderTest(url
, "GET", "GET", url
.GetOrigin().spec());
6435 HTTPRedirectOriginHeaderTest(https_redirect_url
, "GET", "GET", "null");
6436 HTTPRedirectOriginHeaderTest(url
, "POST", "GET", std::string());
6437 HTTPRedirectOriginHeaderTest(https_redirect_url
, "POST", "GET",
6441 TEST_F(URLRequestTestHTTP
, Redirect307Tests
) {
6442 ASSERT_TRUE(test_server_
.Start());
6444 const GURL url
= test_server_
.GetURL("files/redirect307-to-echo");
6445 const GURL https_redirect_url
=
6446 test_server_
.GetURL("files/redirect307-to-https");
6448 HTTPRedirectMethodTest(url
, "POST", "POST", true);
6449 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6450 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6452 HTTPRedirectOriginHeaderTest(url
, "GET", "GET", url
.GetOrigin().spec());
6453 HTTPRedirectOriginHeaderTest(https_redirect_url
, "GET", "GET", "null");
6454 HTTPRedirectOriginHeaderTest(url
, "POST", "POST", url
.GetOrigin().spec());
6455 HTTPRedirectOriginHeaderTest(https_redirect_url
, "POST", "POST", "null");
6458 TEST_F(URLRequestTestHTTP
, Redirect308Tests
) {
6459 ASSERT_TRUE(test_server_
.Start());
6461 const GURL url
= test_server_
.GetURL("files/redirect308-to-echo");
6462 const GURL https_redirect_url
=
6463 test_server_
.GetURL("files/redirect308-to-https");
6465 HTTPRedirectMethodTest(url
, "POST", "POST", true);
6466 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6467 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6469 HTTPRedirectOriginHeaderTest(url
, "GET", "GET", url
.GetOrigin().spec());
6470 HTTPRedirectOriginHeaderTest(https_redirect_url
, "GET", "GET", "null");
6471 HTTPRedirectOriginHeaderTest(url
, "POST", "POST", url
.GetOrigin().spec());
6472 HTTPRedirectOriginHeaderTest(https_redirect_url
, "POST", "POST", "null");
6475 // Make sure that 308 responses without bodies are not treated as redirects.
6476 // Certain legacy apis that pre-date the response code expect this behavior
6477 // (Like Google Drive).
6478 TEST_F(URLRequestTestHTTP
, NoRedirectOn308WithoutLocationHeader
) {
6479 ASSERT_TRUE(test_server_
.Start());
6482 const GURL url
= test_server_
.GetURL("files/308-without-location-header");
6484 scoped_ptr
<URLRequest
> request(
6485 default_context_
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
6488 base::RunLoop().Run();
6489 EXPECT_EQ(URLRequestStatus::SUCCESS
, request
->status().status());
6490 EXPECT_EQ(OK
, request
->status().error());
6491 EXPECT_EQ(0, d
.received_redirect_count());
6492 EXPECT_EQ(308, request
->response_headers()->response_code());
6493 EXPECT_EQ("This is not a redirect.", d
.data_received());
6496 TEST_F(URLRequestTestHTTP
, Redirect302PreserveReferenceFragment
) {
6497 ASSERT_TRUE(test_server_
.Start());
6499 GURL
original_url(test_server_
.GetURL("files/redirect302-to-echo#fragment"));
6500 GURL
expected_url(test_server_
.GetURL("echo#fragment"));
6504 scoped_ptr
<URLRequest
> r(
6505 default_context_
.CreateRequest(original_url
, DEFAULT_PRIORITY
, &d
));
6508 base::RunLoop().Run();
6510 EXPECT_EQ(2U, r
->url_chain().size());
6511 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
6512 EXPECT_EQ(OK
, r
->status().error());
6513 EXPECT_EQ(original_url
, r
->original_url());
6514 EXPECT_EQ(expected_url
, r
->url());
6518 TEST_F(URLRequestTestHTTP
, RedirectPreserveFirstPartyURL
) {
6519 ASSERT_TRUE(test_server_
.Start());
6521 GURL
url(test_server_
.GetURL("files/redirect302-to-echo"));
6522 GURL
first_party_url("http://example.com");
6526 scoped_ptr
<URLRequest
> r(
6527 default_context_
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
6528 r
->set_first_party_for_cookies(first_party_url
);
6531 base::RunLoop().Run();
6533 EXPECT_EQ(2U, r
->url_chain().size());
6534 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
6535 EXPECT_EQ(OK
, r
->status().error());
6536 EXPECT_EQ(first_party_url
, r
->first_party_for_cookies());
6540 TEST_F(URLRequestTestHTTP
, RedirectUpdateFirstPartyURL
) {
6541 ASSERT_TRUE(test_server_
.Start());
6543 GURL
url(test_server_
.GetURL("files/redirect302-to-echo"));
6544 GURL
original_first_party_url("http://example.com");
6545 GURL
expected_first_party_url(test_server_
.GetURL("echo"));
6549 scoped_ptr
<URLRequest
> r(
6550 default_context_
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
6551 r
->set_first_party_for_cookies(original_first_party_url
);
6552 r
->set_first_party_url_policy(
6553 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
6556 base::RunLoop().Run();
6558 EXPECT_EQ(2U, r
->url_chain().size());
6559 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
6560 EXPECT_EQ(OK
, r
->status().error());
6561 EXPECT_EQ(expected_first_party_url
, r
->first_party_for_cookies());
6565 TEST_F(URLRequestTestHTTP
, InterceptPost302RedirectGet
) {
6566 ASSERT_TRUE(test_server_
.Start());
6568 const char kData
[] = "hello world";
6571 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6572 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
));
6573 req
->set_method("POST");
6574 req
->set_upload(CreateSimpleUploadData(kData
));
6575 HttpRequestHeaders headers
;
6576 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
6577 base::UintToString(arraysize(kData
) - 1));
6578 req
->SetExtraRequestHeaders(headers
);
6580 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
6581 req
.get(), &default_network_delegate_
, test_server_
.GetURL("echo"),
6582 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
6583 AddTestInterceptor()->set_main_intercept_job(job
);
6586 base::RunLoop().Run();
6587 EXPECT_EQ("GET", req
->method());
6590 TEST_F(URLRequestTestHTTP
, InterceptPost307RedirectPost
) {
6591 ASSERT_TRUE(test_server_
.Start());
6593 const char kData
[] = "hello world";
6596 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6597 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
));
6598 req
->set_method("POST");
6599 req
->set_upload(CreateSimpleUploadData(kData
));
6600 HttpRequestHeaders headers
;
6601 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
6602 base::UintToString(arraysize(kData
) - 1));
6603 req
->SetExtraRequestHeaders(headers
);
6605 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
6606 req
.get(), &default_network_delegate_
, test_server_
.GetURL("echo"),
6607 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT
,
6608 "Very Good Reason");
6609 AddTestInterceptor()->set_main_intercept_job(job
);
6612 base::RunLoop().Run();
6613 EXPECT_EQ("POST", req
->method());
6614 EXPECT_EQ(kData
, d
.data_received());
6617 // Check that default A-L header is sent.
6618 TEST_F(URLRequestTestHTTP
, DefaultAcceptLanguage
) {
6619 ASSERT_TRUE(test_server_
.Start());
6621 StaticHttpUserAgentSettings
settings("en", std::string());
6622 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6623 TestURLRequestContext
context(true);
6624 context
.set_network_delegate(&network_delegate
);
6625 context
.set_http_user_agent_settings(&settings
);
6629 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6630 test_server_
.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY
, &d
));
6632 base::RunLoop().Run();
6633 EXPECT_EQ("en", d
.data_received());
6636 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6637 TEST_F(URLRequestTestHTTP
, EmptyAcceptLanguage
) {
6638 ASSERT_TRUE(test_server_
.Start());
6640 std::string empty_string
; // Avoid most vexing parse on line below.
6641 StaticHttpUserAgentSettings
settings(empty_string
, empty_string
);
6642 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6643 TestURLRequestContext
context(true);
6644 context
.set_network_delegate(&network_delegate
);
6646 // We override the language after initialization because empty entries
6647 // get overridden by Init().
6648 context
.set_http_user_agent_settings(&settings
);
6651 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6652 test_server_
.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY
, &d
));
6654 base::RunLoop().Run();
6655 EXPECT_EQ("None", d
.data_received());
6658 // Check that if request overrides the A-L header, the default is not appended.
6659 // See http://crbug.com/20894
6660 TEST_F(URLRequestTestHTTP
, OverrideAcceptLanguage
) {
6661 ASSERT_TRUE(test_server_
.Start());
6664 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6665 test_server_
.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY
, &d
));
6666 HttpRequestHeaders headers
;
6667 headers
.SetHeader(HttpRequestHeaders::kAcceptLanguage
, "ru");
6668 req
->SetExtraRequestHeaders(headers
);
6670 base::RunLoop().Run();
6671 EXPECT_EQ(std::string("ru"), d
.data_received());
6674 // Check that default A-E header is sent.
6675 TEST_F(URLRequestTestHTTP
, DefaultAcceptEncoding
) {
6676 ASSERT_TRUE(test_server_
.Start());
6679 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6680 test_server_
.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY
, &d
));
6681 HttpRequestHeaders headers
;
6682 req
->SetExtraRequestHeaders(headers
);
6684 base::RunLoop().Run();
6685 EXPECT_TRUE(ContainsString(d
.data_received(), "gzip"));
6688 // Check that if request overrides the A-E header, the default is not appended.
6689 // See http://crbug.com/47381
6690 TEST_F(URLRequestTestHTTP
, OverrideAcceptEncoding
) {
6691 ASSERT_TRUE(test_server_
.Start());
6694 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6695 test_server_
.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY
, &d
));
6696 HttpRequestHeaders headers
;
6697 headers
.SetHeader(HttpRequestHeaders::kAcceptEncoding
, "identity");
6698 req
->SetExtraRequestHeaders(headers
);
6700 base::RunLoop().Run();
6701 EXPECT_FALSE(ContainsString(d
.data_received(), "gzip"));
6702 EXPECT_TRUE(ContainsString(d
.data_received(), "identity"));
6705 // Check that setting the A-C header sends the proper header.
6706 TEST_F(URLRequestTestHTTP
, SetAcceptCharset
) {
6707 ASSERT_TRUE(test_server_
.Start());
6710 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6711 test_server_
.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY
, &d
));
6712 HttpRequestHeaders headers
;
6713 headers
.SetHeader(HttpRequestHeaders::kAcceptCharset
, "koi-8r");
6714 req
->SetExtraRequestHeaders(headers
);
6716 base::RunLoop().Run();
6717 EXPECT_EQ(std::string("koi-8r"), d
.data_received());
6720 // Check that default User-Agent header is sent.
6721 TEST_F(URLRequestTestHTTP
, DefaultUserAgent
) {
6722 ASSERT_TRUE(test_server_
.Start());
6725 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6726 test_server_
.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY
, &d
));
6728 base::RunLoop().Run();
6729 EXPECT_EQ(default_context_
.http_user_agent_settings()->GetUserAgent(),
6733 // Check that if request overrides the User-Agent header,
6734 // the default is not appended.
6735 TEST_F(URLRequestTestHTTP
, OverrideUserAgent
) {
6736 ASSERT_TRUE(test_server_
.Start());
6739 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6740 test_server_
.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY
, &d
));
6741 HttpRequestHeaders headers
;
6742 headers
.SetHeader(HttpRequestHeaders::kUserAgent
, "Lynx (textmode)");
6743 req
->SetExtraRequestHeaders(headers
);
6745 base::RunLoop().Run();
6746 EXPECT_EQ(std::string("Lynx (textmode)"), d
.data_received());
6749 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6750 // User-Agent header to be sent but does not send the Accept-Language and
6751 // Accept-Charset headers.
6752 TEST_F(URLRequestTestHTTP
, EmptyHttpUserAgentSettings
) {
6753 ASSERT_TRUE(test_server_
.Start());
6755 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6756 TestURLRequestContext
context(true);
6757 context
.set_network_delegate(&network_delegate
);
6759 // We override the HttpUserAgentSettings after initialization because empty
6760 // entries get overridden by Init().
6761 context
.set_http_user_agent_settings(NULL
);
6764 const char* request
;
6765 const char* expected_response
;
6766 } tests
[] = { { "echoheader?Accept-Language", "None" },
6767 { "echoheader?Accept-Charset", "None" },
6768 { "echoheader?User-Agent", "" } };
6770 for (size_t i
= 0; i
< arraysize(tests
); i
++) {
6772 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6773 test_server_
.GetURL(tests
[i
].request
), DEFAULT_PRIORITY
, &d
));
6775 base::RunLoop().Run();
6776 EXPECT_EQ(tests
[i
].expected_response
, d
.data_received())
6777 << " Request = \"" << tests
[i
].request
<< "\"";
6781 // Make sure that URLRequest passes on its priority updates to
6782 // newly-created jobs after the first one.
6783 TEST_F(URLRequestTestHTTP
, SetSubsequentJobPriority
) {
6784 ASSERT_TRUE(test_server_
.Start());
6787 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6788 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
));
6789 EXPECT_EQ(DEFAULT_PRIORITY
, req
->priority());
6791 scoped_refptr
<URLRequestRedirectJob
> redirect_job
=
6792 new URLRequestRedirectJob(
6793 req
.get(), &default_network_delegate_
, test_server_
.GetURL("echo"),
6794 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
6795 AddTestInterceptor()->set_main_intercept_job(redirect_job
.get());
6797 req
->SetPriority(LOW
);
6799 EXPECT_TRUE(req
->is_pending());
6801 scoped_refptr
<URLRequestTestJob
> job
=
6802 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
6803 AddTestInterceptor()->set_main_intercept_job(job
.get());
6805 // Should trigger |job| to be started.
6806 base::RunLoop().Run();
6807 EXPECT_EQ(LOW
, job
->priority());
6810 // Check that creating a network request while entering/exiting suspend mode
6811 // fails as it should. This is the only case where an HttpTransactionFactory
6812 // does not return an HttpTransaction.
6813 TEST_F(URLRequestTestHTTP
, NetworkSuspendTest
) {
6814 // Create a new HttpNetworkLayer that thinks it's suspended.
6815 HttpNetworkSession::Params params
;
6816 params
.host_resolver
= default_context_
.host_resolver();
6817 params
.cert_verifier
= default_context_
.cert_verifier();
6818 params
.transport_security_state
= default_context_
.transport_security_state();
6819 params
.proxy_service
= default_context_
.proxy_service();
6820 params
.ssl_config_service
= default_context_
.ssl_config_service();
6821 params
.http_auth_handler_factory
=
6822 default_context_
.http_auth_handler_factory();
6823 params
.network_delegate
= &default_network_delegate_
;
6824 params
.http_server_properties
= default_context_
.http_server_properties();
6825 scoped_ptr
<HttpNetworkLayer
> network_layer(
6826 new HttpNetworkLayer(new HttpNetworkSession(params
)));
6827 network_layer
->OnSuspend();
6829 HttpCache
http_cache(network_layer
.release(), default_context_
.net_log(),
6830 HttpCache::DefaultBackend::InMemory(0));
6832 TestURLRequestContext
context(true);
6833 context
.set_http_transaction_factory(&http_cache
);
6837 scoped_ptr
<URLRequest
> req(
6838 context
.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY
, &d
));
6840 base::RunLoop().Run();
6842 EXPECT_TRUE(d
.request_failed());
6843 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
6844 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED
, req
->status().error());
6847 // Check that creating a network request while entering/exiting suspend mode
6848 // fails as it should in the case there is no cache. This is the only case
6849 // where an HttpTransactionFactory does not return an HttpTransaction.
6850 TEST_F(URLRequestTestHTTP
, NetworkSuspendTestNoCache
) {
6851 // Create a new HttpNetworkLayer that thinks it's suspended.
6852 HttpNetworkSession::Params params
;
6853 params
.host_resolver
= default_context_
.host_resolver();
6854 params
.cert_verifier
= default_context_
.cert_verifier();
6855 params
.transport_security_state
= default_context_
.transport_security_state();
6856 params
.proxy_service
= default_context_
.proxy_service();
6857 params
.ssl_config_service
= default_context_
.ssl_config_service();
6858 params
.http_auth_handler_factory
=
6859 default_context_
.http_auth_handler_factory();
6860 params
.network_delegate
= &default_network_delegate_
;
6861 params
.http_server_properties
= default_context_
.http_server_properties();
6862 HttpNetworkLayer
network_layer(new HttpNetworkSession(params
));
6863 network_layer
.OnSuspend();
6865 TestURLRequestContext
context(true);
6866 context
.set_http_transaction_factory(&network_layer
);
6870 scoped_ptr
<URLRequest
> req(
6871 context
.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY
, &d
));
6873 base::RunLoop().Run();
6875 EXPECT_TRUE(d
.request_failed());
6876 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
6877 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED
, req
->status().error());
6880 TEST_F(URLRequestTestHTTP
, NetworkAccessedSetOnNetworkRequest
) {
6881 ASSERT_TRUE(test_server_
.Start());
6884 GURL
test_url(test_server_
.GetURL(std::string()));
6885 scoped_ptr
<URLRequest
> req(
6886 default_context_
.CreateRequest(test_url
, DEFAULT_PRIORITY
, &d
));
6889 base::RunLoop().Run();
6891 EXPECT_TRUE(req
->response_info().network_accessed
);
6894 TEST_F(URLRequestTestHTTP
, NetworkAccessedClearOnCachedResponse
) {
6895 ASSERT_TRUE(test_server_
.Start());
6897 // Populate the cache.
6899 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6900 test_server_
.GetURL("cachetime"), DEFAULT_PRIORITY
, &d
));
6902 base::RunLoop().Run();
6904 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
6905 EXPECT_TRUE(req
->response_info().network_accessed
);
6906 EXPECT_FALSE(req
->response_info().was_cached
);
6908 req
= default_context_
.CreateRequest(test_server_
.GetURL("cachetime"),
6909 DEFAULT_PRIORITY
, &d
);
6911 base::RunLoop().Run();
6913 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
6914 EXPECT_FALSE(req
->response_info().network_accessed
);
6915 EXPECT_TRUE(req
->response_info().was_cached
);
6918 TEST_F(URLRequestTestHTTP
, NetworkAccessedClearOnLoadOnlyFromCache
) {
6919 ASSERT_TRUE(test_server_
.Start());
6922 GURL
test_url(test_server_
.GetURL(std::string()));
6923 scoped_ptr
<URLRequest
> req(
6924 default_context_
.CreateRequest(test_url
, DEFAULT_PRIORITY
, &d
));
6925 req
->SetLoadFlags(LOAD_ONLY_FROM_CACHE
);
6928 base::RunLoop().Run();
6930 EXPECT_FALSE(req
->response_info().network_accessed
);
6933 class URLRequestInterceptorTestHTTP
: public URLRequestTestHTTP
{
6935 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6936 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6937 // tests into the factory tests.
6938 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL
) {
6941 void SetUpFactory() override
{
6942 interceptor_
= new MockURLRequestInterceptor();
6943 job_factory_
.reset(new URLRequestInterceptingJobFactory(
6944 job_factory_
.Pass(), make_scoped_ptr(interceptor_
)));
6947 MockURLRequestInterceptor
* interceptor() const {
6948 return interceptor_
;
6952 MockURLRequestInterceptor
* interceptor_
;
6955 TEST_F(URLRequestInterceptorTestHTTP
,
6956 NetworkDelegateNotificationOnRedirectIntercept
) {
6957 interceptor()->set_intercept_redirect(true);
6958 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6959 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6961 ASSERT_TRUE(test_server()->Start());
6964 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
6965 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY
, &d
));
6967 base::RunLoop().Run();
6969 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6970 // Check we got one good response
6971 EXPECT_TRUE(req
->status().is_success());
6972 if (req
->status().is_success())
6973 EXPECT_EQ(200, req
->response_headers()->response_code());
6975 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d
.data_received());
6976 EXPECT_EQ(1, d
.response_started_count());
6977 EXPECT_EQ(0, d
.received_redirect_count());
6979 EXPECT_EQ(1, default_network_delegate()->created_requests());
6980 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6981 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6984 TEST_F(URLRequestInterceptorTestHTTP
,
6985 NetworkDelegateNotificationOnErrorIntercept
) {
6986 // Intercept that error and respond with an OK response.
6987 interceptor()->set_intercept_final_response(true);
6988 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6989 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6990 default_network_delegate()->set_can_be_intercepted_on_error(true);
6992 ASSERT_TRUE(test_server()->Start());
6995 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
6996 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY
,
6998 req
->set_method("GET");
7000 base::RunLoop().Run();
7002 EXPECT_TRUE(interceptor()->did_intercept_final());
7004 // Check we received one good response.
7005 EXPECT_TRUE(req
->status().is_success());
7006 if (req
->status().is_success())
7007 EXPECT_EQ(200, req
->response_headers()->response_code());
7008 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d
.data_received());
7009 EXPECT_EQ(1, d
.response_started_count());
7010 EXPECT_EQ(0, d
.received_redirect_count());
7012 EXPECT_EQ(1, default_network_delegate()->created_requests());
7013 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7014 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7017 TEST_F(URLRequestInterceptorTestHTTP
,
7018 NetworkDelegateNotificationOnResponseIntercept
) {
7019 // Intercept that error and respond with an OK response.
7020 interceptor()->set_intercept_final_response(true);
7022 // Intercept with a real URLRequestHttpJob.
7023 interceptor()->set_use_url_request_http_job(true);
7025 ASSERT_TRUE(test_server()->Start());
7028 scoped_ptr
<URLRequest
> req(default_context().CreateRequest(
7029 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY
, &d
));
7030 req
->set_method("GET");
7032 base::RunLoop().Run();
7034 EXPECT_TRUE(interceptor()->did_intercept_final());
7036 // Check we received one good response.
7037 EXPECT_TRUE(req
->status().is_success());
7038 if (req
->status().is_success())
7039 EXPECT_EQ(200, req
->response_headers()->response_code());
7040 EXPECT_EQ("hello", d
.data_received());
7041 EXPECT_EQ(1, d
.response_started_count());
7042 EXPECT_EQ(0, d
.received_redirect_count());
7044 EXPECT_EQ(1, default_network_delegate()->created_requests());
7045 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7046 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7049 class URLRequestTestReferrerPolicy
: public URLRequestTest
{
7051 URLRequestTestReferrerPolicy() {}
7053 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type
) {
7054 origin_server_
.reset(new SpawnedTestServer(
7055 origin_type
, SpawnedTestServer::kLocalhost
,
7056 origin_type
== SpawnedTestServer::TYPE_HTTPS
7057 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7059 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7060 ASSERT_TRUE(origin_server_
->Start());
7063 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type
,
7064 SpawnedTestServer::Type destination_type
) {
7065 origin_server_
.reset(new SpawnedTestServer(
7066 origin_type
, SpawnedTestServer::kLocalhost
,
7067 origin_type
== SpawnedTestServer::TYPE_HTTPS
7068 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7070 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7071 ASSERT_TRUE(origin_server_
->Start());
7073 destination_server_
.reset(new SpawnedTestServer(
7074 destination_type
, SpawnedTestServer::kLocalhost
,
7075 destination_type
== SpawnedTestServer::TYPE_HTTPS
7076 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7078 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7079 ASSERT_TRUE(destination_server_
->Start());
7082 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy
,
7083 const GURL
& referrer
,
7084 const GURL
& expected
) {
7085 // Create and execute the request: we'll only have a |destination_server_|
7086 // if the origins are meant to be distinct. Otherwise, we'll use the
7087 // |origin_server_| for both endpoints.
7088 GURL destination_url
=
7089 destination_server_
? destination_server_
->GetURL("echoheader?Referer")
7090 : origin_server_
->GetURL("echoheader?Referer");
7092 origin_server_
->GetURL("server-redirect?" + destination_url
.spec());
7095 scoped_ptr
<URLRequest
> req(
7096 default_context_
.CreateRequest(origin_url
, DEFAULT_PRIORITY
, &d
));
7097 req
->set_referrer_policy(policy
);
7098 req
->SetReferrer(referrer
.spec());
7100 base::RunLoop().Run();
7102 EXPECT_EQ(1, d
.response_started_count());
7103 EXPECT_EQ(1, d
.received_redirect_count());
7104 EXPECT_EQ(destination_url
, req
->url());
7105 EXPECT_TRUE(req
->status().is_success());
7106 EXPECT_EQ(200, req
->response_headers()->response_code());
7108 EXPECT_EQ(expected
.spec(), req
->referrer());
7109 if (expected
.is_empty())
7110 EXPECT_EQ("None", d
.data_received());
7112 EXPECT_EQ(expected
.spec(), d
.data_received());
7115 SpawnedTestServer
* origin_server() const { return origin_server_
.get(); }
7118 scoped_ptr
<SpawnedTestServer
> origin_server_
;
7119 scoped_ptr
<SpawnedTestServer
> destination_server_
;
7122 TEST_F(URLRequestTestReferrerPolicy
, HTTPToSameOriginHTTP
) {
7123 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP
);
7125 VerifyReferrerAfterRedirect(
7126 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
,
7127 origin_server()->GetURL("path/to/file.html"),
7128 origin_server()->GetURL("path/to/file.html"));
7130 VerifyReferrerAfterRedirect(
7131 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
,
7132 origin_server()->GetURL("path/to/file.html"),
7133 origin_server()->GetURL("path/to/file.html"));
7135 VerifyReferrerAfterRedirect(
7136 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
,
7137 origin_server()->GetURL("path/to/file.html"),
7138 origin_server()->GetURL("path/to/file.html"));
7140 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER
,
7141 origin_server()->GetURL("path/to/file.html"),
7142 origin_server()->GetURL("path/to/file.html"));
7145 TEST_F(URLRequestTestReferrerPolicy
, HTTPToCrossOriginHTTP
) {
7146 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP
,
7147 SpawnedTestServer::TYPE_HTTP
);
7149 VerifyReferrerAfterRedirect(
7150 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
,
7151 origin_server()->GetURL("path/to/file.html"),
7152 origin_server()->GetURL("path/to/file.html"));
7154 VerifyReferrerAfterRedirect(
7155 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
,
7156 origin_server()->GetURL("path/to/file.html"),
7157 origin_server()->GetURL(std::string()));
7159 VerifyReferrerAfterRedirect(
7160 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
,
7161 origin_server()->GetURL("path/to/file.html"),
7162 origin_server()->GetURL(std::string()));
7164 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER
,
7165 origin_server()->GetURL("path/to/file.html"),
7166 origin_server()->GetURL("path/to/file.html"));
7169 TEST_F(URLRequestTestReferrerPolicy
, HTTPSToSameOriginHTTPS
) {
7170 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS
);
7172 VerifyReferrerAfterRedirect(
7173 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
,
7174 origin_server()->GetURL("path/to/file.html"),
7175 origin_server()->GetURL("path/to/file.html"));
7177 VerifyReferrerAfterRedirect(
7178 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
,
7179 origin_server()->GetURL("path/to/file.html"),
7180 origin_server()->GetURL("path/to/file.html"));
7182 VerifyReferrerAfterRedirect(
7183 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
,
7184 origin_server()->GetURL("path/to/file.html"),
7185 origin_server()->GetURL("path/to/file.html"));
7187 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER
,
7188 origin_server()->GetURL("path/to/file.html"),
7189 origin_server()->GetURL("path/to/file.html"));
7192 TEST_F(URLRequestTestReferrerPolicy
, HTTPSToCrossOriginHTTPS
) {
7193 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS
,
7194 SpawnedTestServer::TYPE_HTTPS
);
7196 VerifyReferrerAfterRedirect(
7197 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
,
7198 origin_server()->GetURL("path/to/file.html"),
7199 origin_server()->GetURL("path/to/file.html"));
7201 VerifyReferrerAfterRedirect(
7202 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
,
7203 origin_server()->GetURL("path/to/file.html"),
7204 origin_server()->GetURL(std::string()));
7206 VerifyReferrerAfterRedirect(
7207 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
,
7208 origin_server()->GetURL("path/to/file.html"),
7209 origin_server()->GetURL(std::string()));
7211 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER
,
7212 origin_server()->GetURL("path/to/file.html"),
7213 origin_server()->GetURL("path/to/file.html"));
7216 TEST_F(URLRequestTestReferrerPolicy
, HTTPToHTTPS
) {
7217 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP
,
7218 SpawnedTestServer::TYPE_HTTPS
);
7220 VerifyReferrerAfterRedirect(
7221 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
,
7222 origin_server()->GetURL("path/to/file.html"),
7223 origin_server()->GetURL("path/to/file.html"));
7225 VerifyReferrerAfterRedirect(
7226 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
,
7227 origin_server()->GetURL("path/to/file.html"),
7228 origin_server()->GetURL(std::string()));
7230 VerifyReferrerAfterRedirect(
7231 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
,
7232 origin_server()->GetURL("path/to/file.html"),
7233 origin_server()->GetURL(std::string()));
7235 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER
,
7236 origin_server()->GetURL("path/to/file.html"),
7237 origin_server()->GetURL("path/to/file.html"));
7240 TEST_F(URLRequestTestReferrerPolicy
, HTTPSToHTTP
) {
7241 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS
,
7242 SpawnedTestServer::TYPE_HTTP
);
7244 VerifyReferrerAfterRedirect(
7245 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
,
7246 origin_server()->GetURL("path/to/file.html"), GURL());
7248 VerifyReferrerAfterRedirect(
7249 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN
,
7250 origin_server()->GetURL("path/to/file.html"), GURL());
7252 VerifyReferrerAfterRedirect(
7253 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN
,
7254 origin_server()->GetURL("path/to/file.html"),
7255 origin_server()->GetURL(std::string()));
7257 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER
,
7258 origin_server()->GetURL("path/to/file.html"),
7259 origin_server()->GetURL("path/to/file.html"));
7262 class HTTPSRequestTest
: public testing::Test
{
7264 HTTPSRequestTest() : default_context_(true) {
7265 default_context_
.set_network_delegate(&default_network_delegate_
);
7266 default_context_
.Init();
7268 ~HTTPSRequestTest() override
{}
7271 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
7272 TestURLRequestContext default_context_
;
7275 TEST_F(HTTPSRequestTest
, HTTPSGetTest
) {
7276 SpawnedTestServer
test_server(
7277 SpawnedTestServer::TYPE_HTTPS
,
7278 SpawnedTestServer::kLocalhost
,
7279 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7280 ASSERT_TRUE(test_server
.Start());
7284 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7285 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
7287 EXPECT_TRUE(r
->is_pending());
7289 base::RunLoop().Run();
7291 EXPECT_EQ(1, d
.response_started_count());
7292 EXPECT_FALSE(d
.received_data_before_response());
7293 EXPECT_NE(0, d
.bytes_received());
7294 CheckSSLInfo(r
->ssl_info());
7295 EXPECT_EQ(test_server
.host_port_pair().host(),
7296 r
->GetSocketAddress().host());
7297 EXPECT_EQ(test_server
.host_port_pair().port(),
7298 r
->GetSocketAddress().port());
7302 TEST_F(HTTPSRequestTest
, HTTPSMismatchedTest
) {
7303 SpawnedTestServer::SSLOptions
ssl_options(
7304 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
7305 SpawnedTestServer
test_server(
7306 SpawnedTestServer::TYPE_HTTPS
,
7308 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7309 ASSERT_TRUE(test_server
.Start());
7311 bool err_allowed
= true;
7312 for (int i
= 0; i
< 2 ; i
++, err_allowed
= !err_allowed
) {
7315 d
.set_allow_certificate_errors(err_allowed
);
7316 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7317 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
7320 EXPECT_TRUE(r
->is_pending());
7322 base::RunLoop().Run();
7324 EXPECT_EQ(1, d
.response_started_count());
7325 EXPECT_FALSE(d
.received_data_before_response());
7326 EXPECT_TRUE(d
.have_certificate_errors());
7328 EXPECT_NE(0, d
.bytes_received());
7329 CheckSSLInfo(r
->ssl_info());
7331 EXPECT_EQ(0, d
.bytes_received());
7337 TEST_F(HTTPSRequestTest
, HTTPSExpiredTest
) {
7338 SpawnedTestServer::SSLOptions
ssl_options(
7339 SpawnedTestServer::SSLOptions::CERT_EXPIRED
);
7340 SpawnedTestServer
test_server(
7341 SpawnedTestServer::TYPE_HTTPS
,
7343 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7344 ASSERT_TRUE(test_server
.Start());
7346 // Iterate from false to true, just so that we do the opposite of the
7347 // previous test in order to increase test coverage.
7348 bool err_allowed
= false;
7349 for (int i
= 0; i
< 2 ; i
++, err_allowed
= !err_allowed
) {
7352 d
.set_allow_certificate_errors(err_allowed
);
7353 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7354 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
7357 EXPECT_TRUE(r
->is_pending());
7359 base::RunLoop().Run();
7361 EXPECT_EQ(1, d
.response_started_count());
7362 EXPECT_FALSE(d
.received_data_before_response());
7363 EXPECT_TRUE(d
.have_certificate_errors());
7365 EXPECT_NE(0, d
.bytes_received());
7366 CheckSSLInfo(r
->ssl_info());
7368 EXPECT_EQ(0, d
.bytes_received());
7374 // Tests that servers which require a deprecated cipher suite still work.
7375 TEST_F(HTTPSRequestTest
, CipherFallbackTest
) {
7377 default_context_
.set_net_log(&net_log
);
7379 SpawnedTestServer::SSLOptions ssl_options
;
7380 ssl_options
.bulk_ciphers
= SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4
;
7381 SpawnedTestServer
test_server(
7382 SpawnedTestServer::TYPE_HTTPS
, ssl_options
,
7383 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7384 ASSERT_TRUE(test_server
.Start());
7387 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7388 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
7390 EXPECT_TRUE(r
->is_pending());
7392 base::RunLoop().Run();
7394 EXPECT_EQ(1, d
.response_started_count());
7395 EXPECT_FALSE(d
.received_data_before_response());
7396 EXPECT_NE(0, d
.bytes_received());
7397 CheckSSLInfo(r
->ssl_info());
7398 EXPECT_EQ(test_server
.host_port_pair().host(), r
->GetSocketAddress().host());
7399 EXPECT_EQ(test_server
.host_port_pair().port(), r
->GetSocketAddress().port());
7401 // No version downgrade should have been necessary.
7402 EXPECT_FALSE(r
->ssl_info().connection_status
&
7403 SSL_CONNECTION_VERSION_FALLBACK
);
7404 int expected_version
= SSL_CONNECTION_VERSION_TLS1_2
;
7405 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7406 SSL_PROTOCOL_VERSION_TLS1_2
) {
7407 expected_version
= SSL_CONNECTION_VERSION_TLS1_1
;
7409 EXPECT_EQ(expected_version
,
7410 SSLConnectionStatusToVersion(r
->ssl_info().connection_status
));
7412 TestNetLogEntry::List entries
;
7413 net_log
.GetEntries(&entries
);
7414 ExpectLogContainsSomewhere(entries
, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK
,
7415 NetLog::PHASE_NONE
);
7418 // This tests that a load of www.google.com with a certificate error sets
7419 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
7420 // the interstitial to be fatal.
7421 TEST_F(HTTPSRequestTest
, HTTPSPreloadedHSTSTest
) {
7422 SpawnedTestServer::SSLOptions
ssl_options(
7423 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
7424 SpawnedTestServer
test_server(
7425 SpawnedTestServer::TYPE_HTTPS
,
7427 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7428 ASSERT_TRUE(test_server
.Start());
7430 // We require that the URL be www.google.com in order to pick up the
7431 // preloaded HSTS entries in the TransportSecurityState. This means that we
7432 // have to use a MockHostResolver in order to direct www.google.com to the
7433 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7435 MockHostResolver host_resolver
;
7436 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
7437 TestURLRequestContext
context(true);
7438 context
.set_network_delegate(&network_delegate
);
7439 context
.set_host_resolver(&host_resolver
);
7440 TransportSecurityState transport_security_state
;
7441 context
.set_transport_security_state(&transport_security_state
);
7445 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
7446 GURL(base::StringPrintf("https://www.google.com:%d",
7447 test_server
.host_port_pair().port())),
7448 DEFAULT_PRIORITY
, &d
));
7451 EXPECT_TRUE(r
->is_pending());
7453 base::RunLoop().Run();
7455 EXPECT_EQ(1, d
.response_started_count());
7456 EXPECT_FALSE(d
.received_data_before_response());
7457 EXPECT_TRUE(d
.have_certificate_errors());
7458 EXPECT_TRUE(d
.certificate_errors_are_fatal());
7461 // This tests that cached HTTPS page loads do not cause any updates to the
7462 // TransportSecurityState.
7463 TEST_F(HTTPSRequestTest
, HTTPSErrorsNoClobberTSSTest
) {
7464 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7465 // matter. It just has to be any error.
7466 SpawnedTestServer::SSLOptions
ssl_options(
7467 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
7468 SpawnedTestServer
test_server(
7469 SpawnedTestServer::TYPE_HTTPS
,
7471 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7472 ASSERT_TRUE(test_server
.Start());
7474 // We require that the URL be www.google.com in order to pick up the static
7475 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7476 // that we have to use a MockHostResolver in order to direct www.google.com to
7477 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7479 MockHostResolver host_resolver
;
7480 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
7481 TestURLRequestContext
context(true);
7482 context
.set_network_delegate(&network_delegate
);
7483 context
.set_host_resolver(&host_resolver
);
7484 TransportSecurityState transport_security_state
;
7486 TransportSecurityState::DomainState static_domain_state
;
7487 EXPECT_TRUE(transport_security_state
.GetStaticDomainState(
7488 "www.google.com", &static_domain_state
));
7489 context
.set_transport_security_state(&transport_security_state
);
7492 TransportSecurityState::DomainState dynamic_domain_state
;
7493 EXPECT_FALSE(transport_security_state
.GetDynamicDomainState(
7494 "www.google.com", &dynamic_domain_state
));
7497 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
7498 GURL(base::StringPrintf("https://www.google.com:%d",
7499 test_server
.host_port_pair().port())),
7500 DEFAULT_PRIORITY
, &d
));
7503 EXPECT_TRUE(r
->is_pending());
7505 base::RunLoop().Run();
7507 EXPECT_EQ(1, d
.response_started_count());
7508 EXPECT_FALSE(d
.received_data_before_response());
7509 EXPECT_TRUE(d
.have_certificate_errors());
7510 EXPECT_TRUE(d
.certificate_errors_are_fatal());
7512 // Get a fresh copy of the states, and check that they haven't changed.
7513 TransportSecurityState::DomainState new_static_domain_state
;
7514 EXPECT_TRUE(transport_security_state
.GetStaticDomainState(
7515 "www.google.com", &new_static_domain_state
));
7516 TransportSecurityState::DomainState new_dynamic_domain_state
;
7517 EXPECT_FALSE(transport_security_state
.GetDynamicDomainState(
7518 "www.google.com", &new_dynamic_domain_state
));
7520 EXPECT_EQ(new_static_domain_state
.sts
.upgrade_mode
,
7521 static_domain_state
.sts
.upgrade_mode
);
7522 EXPECT_EQ(new_static_domain_state
.sts
.include_subdomains
,
7523 static_domain_state
.sts
.include_subdomains
);
7524 EXPECT_EQ(new_static_domain_state
.pkp
.include_subdomains
,
7525 static_domain_state
.pkp
.include_subdomains
);
7526 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state
.pkp
.spki_hashes
,
7527 static_domain_state
.pkp
.spki_hashes
));
7528 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state
.pkp
.bad_spki_hashes
,
7529 static_domain_state
.pkp
.bad_spki_hashes
));
7532 // Make sure HSTS preserves a POST request's method and body.
7533 TEST_F(HTTPSRequestTest
, HSTSPreservesPosts
) {
7534 static const char kData
[] = "hello world";
7536 SpawnedTestServer::SSLOptions
ssl_options(
7537 SpawnedTestServer::SSLOptions::CERT_OK
);
7538 SpawnedTestServer
test_server(
7539 SpawnedTestServer::TYPE_HTTPS
,
7541 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7542 ASSERT_TRUE(test_server
.Start());
7545 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7546 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
7547 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7549 MockHostResolver host_resolver
;
7551 // Force https for www.somewhere.com.
7552 TransportSecurityState transport_security_state
;
7553 base::Time expiry
= base::Time::Now() + base::TimeDelta::FromDays(1000);
7554 bool include_subdomains
= false;
7555 transport_security_state
.AddHSTS("www.somewhere.com", expiry
,
7556 include_subdomains
);
7558 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
7560 TestURLRequestContext
context(true);
7561 context
.set_host_resolver(&host_resolver
);
7562 context
.set_transport_security_state(&transport_security_state
);
7563 context
.set_network_delegate(&network_delegate
);
7567 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7568 // cause a certificate error. Ignore the error.
7569 d
.set_allow_certificate_errors(true);
7571 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
7572 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
7573 test_server
.host_port_pair().port())),
7574 DEFAULT_PRIORITY
, &d
));
7575 req
->set_method("POST");
7576 req
->set_upload(CreateSimpleUploadData(kData
));
7579 base::RunLoop().Run();
7581 EXPECT_EQ("https", req
->url().scheme());
7582 EXPECT_EQ("POST", req
->method());
7583 EXPECT_EQ(kData
, d
.data_received());
7585 LoadTimingInfo load_timing_info
;
7586 network_delegate
.GetLoadTimingInfoBeforeRedirect(&load_timing_info
);
7587 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7588 TestLoadTimingCacheHitNoNetwork(load_timing_info
);
7591 // Make sure that the CORS headers are added to cross-origin HSTS redirects.
7592 TEST_F(HTTPSRequestTest
, HSTSCrossOriginAddHeaders
) {
7593 static const char kOriginHeaderValue
[] = "http://www.example.com";
7595 SpawnedTestServer::SSLOptions
ssl_options(
7596 SpawnedTestServer::SSLOptions::CERT_OK
);
7597 SpawnedTestServer
test_server(
7598 SpawnedTestServer::TYPE_HTTPS
,
7600 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7601 ASSERT_TRUE(test_server
.Start());
7603 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7604 // address, so a MockHostResolver is needed to redirect example.net to the
7605 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7606 MockHostResolver host_resolver
;
7608 TransportSecurityState transport_security_state
;
7609 base::Time expiry
= base::Time::Now() + base::TimeDelta::FromDays(1);
7610 bool include_subdomains
= false;
7611 transport_security_state
.AddHSTS("example.net", expiry
, include_subdomains
);
7613 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
7615 MockCertVerifier cert_verifier
;
7616 cert_verifier
.set_default_result(OK
);
7618 TestURLRequestContext
context(true);
7619 context
.set_host_resolver(&host_resolver
);
7620 context
.set_transport_security_state(&transport_security_state
);
7621 context
.set_network_delegate(&network_delegate
);
7622 context
.set_cert_verifier(&cert_verifier
);
7625 GURL
hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7626 test_server
.host_port_pair().port()));
7627 url::Replacements
<char> replacements
;
7628 const char kNewScheme
[] = "https";
7629 replacements
.SetScheme(kNewScheme
, url::Component(0, strlen(kNewScheme
)));
7630 GURL hsts_https_url
= hsts_http_url
.ReplaceComponents(replacements
);
7633 // Quit on redirect to allow response header inspection upon redirect.
7634 d
.set_quit_on_redirect(true);
7636 scoped_ptr
<URLRequest
> req(
7637 context
.CreateRequest(hsts_http_url
, DEFAULT_PRIORITY
, &d
));
7638 // Set Origin header to simulate a cross-origin request.
7639 HttpRequestHeaders request_headers
;
7640 request_headers
.SetHeader("Origin", kOriginHeaderValue
);
7641 req
->SetExtraRequestHeaders(request_headers
);
7644 base::RunLoop().Run();
7646 EXPECT_EQ(1, d
.received_redirect_count());
7648 const HttpResponseHeaders
* headers
= req
->response_headers();
7649 std::string redirect_location
;
7650 EXPECT_TRUE(headers
->EnumerateHeader(NULL
, "Location", &redirect_location
));
7651 EXPECT_EQ(hsts_https_url
.spec(), redirect_location
);
7653 std::string received_cors_header
;
7654 EXPECT_TRUE(headers
->EnumerateHeader(NULL
, "Access-Control-Allow-Origin",
7655 &received_cors_header
));
7656 EXPECT_EQ(kOriginHeaderValue
, received_cors_header
);
7659 // This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7660 // are performed in net/websockets/websocket_end_to_end_test.cc.
7661 TEST(WebSocketURLRequestTest
, HSTSApplied
) {
7662 TestNetworkDelegate network_delegate
;
7663 TransportSecurityState transport_security_state
;
7664 base::Time expiry
= base::Time::Now() + base::TimeDelta::FromDays(1);
7665 bool include_subdomains
= false;
7666 transport_security_state
.AddHSTS("example.net", expiry
, include_subdomains
);
7667 TestURLRequestContext
context(true);
7668 context
.set_transport_security_state(&transport_security_state
);
7669 context
.set_network_delegate(&network_delegate
);
7671 GURL
ws_url("ws://example.net/echo");
7672 TestDelegate delegate
;
7673 scoped_ptr
<URLRequest
> request(
7674 context
.CreateRequest(ws_url
, DEFAULT_PRIORITY
, &delegate
));
7675 EXPECT_TRUE(request
->GetHSTSRedirect(&ws_url
));
7676 EXPECT_TRUE(ws_url
.SchemeIs("wss"));
7681 class SSLClientAuthTestDelegate
: public TestDelegate
{
7683 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7685 void OnCertificateRequested(URLRequest
* request
,
7686 SSLCertRequestInfo
* cert_request_info
) override
{
7687 on_certificate_requested_count_
++;
7688 base::MessageLoop::current()->Quit();
7690 int on_certificate_requested_count() {
7691 return on_certificate_requested_count_
;
7694 int on_certificate_requested_count_
;
7699 // TODO(davidben): Test the rest of the code. Specifically,
7700 // - Filtering which certificates to select.
7701 // - Sending a certificate back.
7702 // - Getting a certificate request in an SSL renegotiation sending the
7704 TEST_F(HTTPSRequestTest
, ClientAuthTest
) {
7705 SpawnedTestServer::SSLOptions ssl_options
;
7706 ssl_options
.request_client_certificate
= true;
7707 SpawnedTestServer
test_server(
7708 SpawnedTestServer::TYPE_HTTPS
,
7710 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7711 ASSERT_TRUE(test_server
.Start());
7713 SSLClientAuthTestDelegate d
;
7715 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7716 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
7719 EXPECT_TRUE(r
->is_pending());
7721 base::RunLoop().Run();
7723 EXPECT_EQ(1, d
.on_certificate_requested_count());
7724 EXPECT_FALSE(d
.received_data_before_response());
7725 EXPECT_EQ(0, d
.bytes_received());
7727 // Send no certificate.
7728 // TODO(davidben): Get temporary client cert import (with keys) working on
7729 // all platforms so we can test sending a cert as well.
7730 r
->ContinueWithCertificate(NULL
);
7732 base::RunLoop().Run();
7734 EXPECT_EQ(1, d
.response_started_count());
7735 EXPECT_FALSE(d
.received_data_before_response());
7736 EXPECT_NE(0, d
.bytes_received());
7740 TEST_F(HTTPSRequestTest
, ResumeTest
) {
7741 // Test that we attempt a session resume when making two connections to the
7743 SpawnedTestServer::SSLOptions ssl_options
;
7744 ssl_options
.record_resume
= true;
7745 SpawnedTestServer
test_server(
7746 SpawnedTestServer::TYPE_HTTPS
,
7748 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7749 ASSERT_TRUE(test_server
.Start());
7751 SSLClientSocket::ClearSessionCache();
7755 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7756 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
));
7759 EXPECT_TRUE(r
->is_pending());
7761 base::RunLoop().Run();
7763 EXPECT_EQ(1, d
.response_started_count());
7766 reinterpret_cast<HttpCache
*>(default_context_
.http_transaction_factory())->
7767 CloseAllConnections();
7771 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7772 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
));
7775 EXPECT_TRUE(r
->is_pending());
7777 base::RunLoop().Run();
7779 // The response will look like;
7784 // With a newline at the end which makes the split think that there are
7787 EXPECT_EQ(1, d
.response_started_count());
7788 std::vector
<std::string
> lines
;
7789 base::SplitString(d
.data_received(), '\n', &lines
);
7790 ASSERT_EQ(4u, lines
.size()) << d
.data_received();
7792 std::string session_id
;
7794 for (size_t i
= 0; i
< 2; i
++) {
7795 std::vector
<std::string
> parts
;
7796 base::SplitString(lines
[i
], '\t', &parts
);
7797 ASSERT_EQ(2u, parts
.size());
7799 EXPECT_EQ("insert", parts
[0]);
7800 session_id
= parts
[1];
7802 EXPECT_EQ("lookup", parts
[0]);
7803 EXPECT_EQ(session_id
, parts
[1]);
7809 // AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7810 // the result of fetching "ssl-session-cache" from the test server, indicates
7811 // that exactly two different sessions were inserted, with no lookups etc.
7812 static void AssertTwoDistinctSessionsInserted(const string
& session_info
) {
7813 std::vector
<std::string
> lines
;
7814 base::SplitString(session_info
, '\n', &lines
);
7815 ASSERT_EQ(3u, lines
.size()) << session_info
;
7817 std::string session_id
;
7818 for (size_t i
= 0; i
< 2; i
++) {
7819 std::vector
<std::string
> parts
;
7820 base::SplitString(lines
[i
], '\t', &parts
);
7821 ASSERT_EQ(2u, parts
.size());
7822 EXPECT_EQ("insert", parts
[0]);
7824 session_id
= parts
[1];
7826 EXPECT_NE(session_id
, parts
[1]);
7831 TEST_F(HTTPSRequestTest
, SSLSessionCacheShardTest
) {
7832 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7834 SpawnedTestServer::SSLOptions ssl_options
;
7835 ssl_options
.record_resume
= true;
7836 SpawnedTestServer
test_server(
7837 SpawnedTestServer::TYPE_HTTPS
,
7839 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7840 ASSERT_TRUE(test_server
.Start());
7842 SSLClientSocket::ClearSessionCache();
7846 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7847 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
));
7850 EXPECT_TRUE(r
->is_pending());
7852 base::RunLoop().Run();
7854 EXPECT_EQ(1, d
.response_started_count());
7857 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7858 HttpNetworkSession::Params params
;
7859 params
.host_resolver
= default_context_
.host_resolver();
7860 params
.cert_verifier
= default_context_
.cert_verifier();
7861 params
.transport_security_state
= default_context_
.transport_security_state();
7862 params
.proxy_service
= default_context_
.proxy_service();
7863 params
.ssl_config_service
= default_context_
.ssl_config_service();
7864 params
.http_auth_handler_factory
=
7865 default_context_
.http_auth_handler_factory();
7866 params
.network_delegate
= &default_network_delegate_
;
7867 params
.http_server_properties
= default_context_
.http_server_properties();
7868 params
.ssl_session_cache_shard
= "alternate";
7870 scoped_ptr
<HttpCache
> cache(new HttpCache(
7871 new HttpNetworkSession(params
),
7872 HttpCache::DefaultBackend::InMemory(0)));
7874 default_context_
.set_http_transaction_factory(cache
.get());
7878 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7879 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
));
7882 EXPECT_TRUE(r
->is_pending());
7884 base::RunLoop().Run();
7886 // The response will look like;
7890 // With a newline at the end which makes the split think that there are
7893 EXPECT_EQ(1, d
.response_started_count());
7894 AssertTwoDistinctSessionsInserted(d
.data_received());
7902 bool IsECDSACipherSuite(uint16_t cipher_suite
) {
7903 const char* key_exchange
;
7907 SSLCipherSuiteToStrings(&key_exchange
, &cipher
, &mac
, &is_aead
, cipher_suite
);
7908 return std::string(key_exchange
).find("ECDSA") != std::string::npos
;
7913 // Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7915 TEST_F(HTTPSRequestTest
, DisableECDSAOnXP
) {
7916 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
7917 LOG(INFO
) << "Skipping test on this version.";
7921 SpawnedTestServer
test_server(
7922 SpawnedTestServer::TYPE_HTTPS
,
7923 SpawnedTestServer::kLocalhost
,
7924 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7925 ASSERT_TRUE(test_server
.Start());
7928 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7929 test_server
.GetURL("client-cipher-list"), DEFAULT_PRIORITY
, &d
));
7931 EXPECT_TRUE(r
->is_pending());
7933 base::RunLoop().Run();
7935 EXPECT_EQ(1, d
.response_started_count());
7936 std::vector
<std::string
> lines
;
7937 base::SplitString(d
.data_received(), '\n', &lines
);
7939 for (size_t i
= 0; i
< lines
.size(); i
++) {
7941 ASSERT_TRUE(base::StringToInt(lines
[i
], &cipher_suite
));
7942 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite
))
7943 << "ClientHello advertised " << cipher_suite
;
7949 class TestSSLConfigService
: public SSLConfigService
{
7951 TestSSLConfigService(bool ev_enabled
,
7952 bool online_rev_checking
,
7953 bool rev_checking_required_local_anchors
)
7954 : ev_enabled_(ev_enabled
),
7955 online_rev_checking_(online_rev_checking
),
7956 rev_checking_required_local_anchors_(
7957 rev_checking_required_local_anchors
),
7958 min_version_(kDefaultSSLVersionMin
),
7959 fallback_min_version_(kDefaultSSLVersionFallbackMin
) {}
7961 void set_min_version(uint16 version
) {
7962 min_version_
= version
;
7965 void set_fallback_min_version(uint16 version
) {
7966 fallback_min_version_
= version
;
7969 // SSLConfigService:
7970 void GetSSLConfig(SSLConfig
* config
) override
{
7971 *config
= SSLConfig();
7972 config
->rev_checking_enabled
= online_rev_checking_
;
7973 config
->verify_ev_cert
= ev_enabled_
;
7974 config
->rev_checking_required_local_anchors
=
7975 rev_checking_required_local_anchors_
;
7976 if (fallback_min_version_
) {
7977 config
->version_fallback_min
= fallback_min_version_
;
7980 config
->version_min
= min_version_
;
7985 ~TestSSLConfigService() override
{}
7988 const bool ev_enabled_
;
7989 const bool online_rev_checking_
;
7990 const bool rev_checking_required_local_anchors_
;
7991 uint16 min_version_
;
7992 uint16 fallback_min_version_
;
7995 class FallbackTestURLRequestContext
: public TestURLRequestContext
{
7997 explicit FallbackTestURLRequestContext(bool delay_initialization
)
7998 : TestURLRequestContext(delay_initialization
) {}
8000 void set_fallback_min_version(uint16 version
) {
8001 TestSSLConfigService
*ssl_config_service
=
8002 new TestSSLConfigService(true /* check for EV */,
8003 false /* online revocation checking */,
8004 false /* require rev. checking for local
8006 ssl_config_service
->set_fallback_min_version(version
);
8007 set_ssl_config_service(ssl_config_service
);
8011 class HTTPSFallbackTest
: public testing::Test
{
8013 HTTPSFallbackTest() : context_(true) {}
8014 ~HTTPSFallbackTest() override
{}
8017 void DoFallbackTest(const SpawnedTestServer::SSLOptions
& ssl_options
) {
8020 delegate_
.set_allow_certificate_errors(true);
8022 SpawnedTestServer
test_server(
8023 SpawnedTestServer::TYPE_HTTPS
,
8025 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8026 ASSERT_TRUE(test_server
.Start());
8028 request_
= context_
.CreateRequest(test_server
.GetURL(std::string()),
8029 DEFAULT_PRIORITY
, &delegate_
);
8032 base::RunLoop().Run();
8035 void set_fallback_min_version(uint16 version
) {
8036 context_
.set_fallback_min_version(version
);
8039 void ExpectConnection(int version
) {
8040 EXPECT_EQ(1, delegate_
.response_started_count());
8041 EXPECT_NE(0, delegate_
.bytes_received());
8042 EXPECT_EQ(version
, SSLConnectionStatusToVersion(
8043 request_
->ssl_info().connection_status
));
8044 EXPECT_TRUE(request_
->ssl_info().connection_status
&
8045 SSL_CONNECTION_VERSION_FALLBACK
);
8048 void ExpectFailure(int error
) {
8049 EXPECT_EQ(1, delegate_
.response_started_count());
8050 EXPECT_FALSE(request_
->status().is_success());
8051 EXPECT_EQ(URLRequestStatus::FAILED
, request_
->status().status());
8052 EXPECT_EQ(error
, request_
->status().error());
8056 TestDelegate delegate_
;
8057 FallbackTestURLRequestContext context_
;
8058 scoped_ptr
<URLRequest
> request_
;
8061 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
8063 TEST_F(HTTPSFallbackTest
, TLSv1Fallback
) {
8064 SpawnedTestServer::SSLOptions
ssl_options(
8065 SpawnedTestServer::SSLOptions::CERT_OK
);
8066 ssl_options
.tls_intolerant
=
8067 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
8069 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
8070 ExpectConnection(SSL_CONNECTION_VERSION_TLS1
);
8073 // This test is disabled on Android because the remote test server doesn't cause
8075 #if !defined(OS_ANDROID)
8076 // Tests fallback to TLS 1.0 on connection reset.
8077 TEST_F(HTTPSFallbackTest
, TLSv1FallbackReset
) {
8078 SpawnedTestServer::SSLOptions
ssl_options(
8079 SpawnedTestServer::SSLOptions::CERT_OK
);
8080 ssl_options
.tls_intolerant
=
8081 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
8082 ssl_options
.tls_intolerance_type
=
8083 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET
;
8085 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
8086 ExpectConnection(SSL_CONNECTION_VERSION_TLS1
);
8088 #endif // !OS_ANDROID
8090 // Tests that we don't fallback on handshake failure with servers that implement
8091 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
8092 TEST_F(HTTPSFallbackTest
, FallbackSCSV
) {
8093 SpawnedTestServer::SSLOptions
ssl_options(
8094 SpawnedTestServer::SSLOptions::CERT_OK
);
8095 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
8096 // a version fallback.
8097 ssl_options
.tls_intolerant
=
8098 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
8099 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8100 // connections are rejected.
8101 ssl_options
.fallback_scsv_enabled
= true;
8103 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
8105 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8106 // intolerance. If the fallback SCSV is processed when the original error
8107 // that caused the fallback should be returned, which should be
8108 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8109 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
);
8112 // Tests that we don't fallback on connection closed with servers that implement
8113 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
8114 TEST_F(HTTPSFallbackTest
, FallbackSCSVClosed
) {
8115 SpawnedTestServer::SSLOptions
ssl_options(
8116 SpawnedTestServer::SSLOptions::CERT_OK
);
8117 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
8118 // a version fallback.
8119 ssl_options
.tls_intolerant
=
8120 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
8121 ssl_options
.tls_intolerance_type
=
8122 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE
;
8123 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8124 // connections are rejected.
8125 ssl_options
.fallback_scsv_enabled
= true;
8127 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
8129 // The original error should be replayed on rejected fallback.
8130 ExpectFailure(ERR_CONNECTION_CLOSED
);
8133 // Tests that the SSLv3 fallback doesn't happen.
8134 TEST_F(HTTPSFallbackTest
, SSLv3Fallback
) {
8135 SpawnedTestServer::SSLOptions
ssl_options(
8136 SpawnedTestServer::SSLOptions::CERT_OK
);
8137 ssl_options
.tls_intolerant
=
8138 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
8140 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
8141 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
);
8144 // Tests that the TLSv1 fallback triggers on closed connections.
8145 TEST_F(HTTPSFallbackTest
, SSLv3FallbackClosed
) {
8146 SpawnedTestServer::SSLOptions
ssl_options(
8147 SpawnedTestServer::SSLOptions::CERT_OK
);
8148 ssl_options
.tls_intolerant
=
8149 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
8150 ssl_options
.tls_intolerance_type
=
8151 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE
;
8153 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
8154 ExpectConnection(SSL_CONNECTION_VERSION_TLS1
);
8157 // Test that fallback probe connections don't cause sessions to be cached.
8158 TEST_F(HTTPSRequestTest
, FallbackProbeNoCache
) {
8159 SpawnedTestServer::SSLOptions
ssl_options(
8160 SpawnedTestServer::SSLOptions::CERT_OK
);
8161 ssl_options
.tls_intolerant
=
8162 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
8163 ssl_options
.tls_intolerance_type
=
8164 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE
;
8165 ssl_options
.record_resume
= true;
8167 SpawnedTestServer
test_server(
8168 SpawnedTestServer::TYPE_HTTPS
,
8170 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8171 ASSERT_TRUE(test_server
.Start());
8173 SSLClientSocket::ClearSessionCache();
8175 // Make a connection that does a probe fallback to TLSv1 but fails because
8176 // TLSv1 fallback is disabled. We don't wish a session for this connection to
8177 // be inserted locally.
8179 TestDelegate delegate
;
8180 FallbackTestURLRequestContext
context(true);
8182 context
.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2
);
8184 scoped_ptr
<URLRequest
> request(context
.CreateRequest(
8185 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &delegate
));
8188 base::RunLoop().Run();
8190 EXPECT_EQ(1, delegate
.response_started_count());
8191 EXPECT_FALSE(request
->status().is_success());
8192 EXPECT_EQ(URLRequestStatus::FAILED
, request
->status().status());
8193 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION
,
8194 request
->status().error());
8197 // Now allow TLSv1 fallback connections and request the session cache log.
8199 TestDelegate delegate
;
8200 FallbackTestURLRequestContext
context(true);
8201 context
.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1
);
8204 scoped_ptr
<URLRequest
> request(context
.CreateRequest(
8205 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &delegate
));
8208 base::RunLoop().Run();
8210 EXPECT_EQ(1, delegate
.response_started_count());
8211 EXPECT_NE(0, delegate
.bytes_received());
8213 SSL_CONNECTION_VERSION_TLS1
,
8214 SSLConnectionStatusToVersion(request
->ssl_info().connection_status
));
8215 EXPECT_TRUE(request
->ssl_info().connection_status
&
8216 SSL_CONNECTION_VERSION_FALLBACK
);
8218 std::vector
<std::string
> lines
;
8219 // If no sessions were cached then the server should have seen two sessions
8220 // inserted with no lookups.
8221 AssertTwoDistinctSessionsInserted(delegate
.data_received());
8225 class HTTPSSessionTest
: public testing::Test
{
8227 HTTPSSessionTest() : default_context_(true) {
8228 cert_verifier_
.set_default_result(OK
);
8230 default_context_
.set_network_delegate(&default_network_delegate_
);
8231 default_context_
.set_cert_verifier(&cert_verifier_
);
8232 default_context_
.Init();
8234 ~HTTPSSessionTest() override
{}
8237 MockCertVerifier cert_verifier_
;
8238 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
8239 TestURLRequestContext default_context_
;
8242 // Tests that session resumption is not attempted if an invalid certificate
8244 TEST_F(HTTPSSessionTest
, DontResumeSessionsForInvalidCertificates
) {
8245 SpawnedTestServer::SSLOptions ssl_options
;
8246 ssl_options
.record_resume
= true;
8247 SpawnedTestServer
test_server(
8248 SpawnedTestServer::TYPE_HTTPS
,
8250 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8251 ASSERT_TRUE(test_server
.Start());
8253 SSLClientSocket::ClearSessionCache();
8255 // Simulate the certificate being expired and attempt a connection.
8256 cert_verifier_
.set_default_result(ERR_CERT_DATE_INVALID
);
8259 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8260 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
));
8263 EXPECT_TRUE(r
->is_pending());
8265 base::RunLoop().Run();
8267 EXPECT_EQ(1, d
.response_started_count());
8270 reinterpret_cast<HttpCache
*>(default_context_
.http_transaction_factory())->
8271 CloseAllConnections();
8273 // Now change the certificate to be acceptable (so that the response is
8274 // loaded), and ensure that no session id is presented to the peer.
8275 cert_verifier_
.set_default_result(OK
);
8278 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8279 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
));
8282 EXPECT_TRUE(r
->is_pending());
8284 base::RunLoop().Run();
8286 // The response will look like;
8290 // With a newline at the end which makes the split think that there are
8293 // If a session was presented (eg: a bug), then the response would look
8299 EXPECT_EQ(1, d
.response_started_count());
8300 AssertTwoDistinctSessionsInserted(d
.data_received());
8304 // This the fingerprint of the "Testing CA" certificate used by the testserver.
8305 // See net/data/ssl/certificates/ocsp-test-root.pem.
8306 static const SHA1HashValue kOCSPTestCertFingerprint
=
8307 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8308 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8310 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8312 static const SHA256HashValue kOCSPTestCertSPKI
= { {
8313 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8314 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8315 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8316 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8319 // This is the policy OID contained in the certificates that testserver
8321 static const char kOCSPTestCertPolicy
[] = "1.3.6.1.4.1.11129.2.4.1";
8323 class HTTPSOCSPTest
: public HTTPSRequestTest
{
8328 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8329 kOCSPTestCertFingerprint
,
8330 kOCSPTestCertPolicy
)) {
8333 void SetUp() override
{
8334 SetupContext(&context_
);
8337 scoped_refptr
<X509Certificate
> root_cert
=
8338 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
8339 CHECK_NE(static_cast<X509Certificate
*>(NULL
), root_cert
.get());
8340 test_root_
.reset(new ScopedTestRoot(root_cert
.get()));
8342 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
8343 SetURLRequestContextForNSSHttpIO(&context_
);
8344 EnsureNSSHttpIOInit();
8348 void DoConnection(const SpawnedTestServer::SSLOptions
& ssl_options
,
8349 CertStatus
* out_cert_status
) {
8350 // We always overwrite out_cert_status.
8351 *out_cert_status
= 0;
8352 SpawnedTestServer
test_server(
8353 SpawnedTestServer::TYPE_HTTPS
,
8355 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8356 ASSERT_TRUE(test_server
.Start());
8359 d
.set_allow_certificate_errors(true);
8360 scoped_ptr
<URLRequest
> r(context_
.CreateRequest(
8361 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
));
8364 base::RunLoop().Run();
8366 EXPECT_EQ(1, d
.response_started_count());
8367 *out_cert_status
= r
->ssl_info().cert_status
;
8370 ~HTTPSOCSPTest() override
{
8371 #if defined(USE_NSS_CERTS) || defined(OS_IOS)
8372 ShutdownNSSHttpIO();
8377 // SetupContext configures the URLRequestContext that will be used for making
8378 // connetions to testserver. This can be overridden in test subclasses for
8379 // different behaviour.
8380 virtual void SetupContext(URLRequestContext
* context
) {
8381 context
->set_ssl_config_service(
8382 new TestSSLConfigService(true /* check for EV */,
8383 true /* online revocation checking */,
8384 false /* require rev. checking for local
8388 scoped_ptr
<ScopedTestRoot
> test_root_
;
8389 TestURLRequestContext context_
;
8390 scoped_ptr
<ScopedTestEVPolicy
> ev_test_policy_
;
8393 static CertStatus
ExpectedCertStatusForFailedOnlineRevocationCheck() {
8395 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8396 // have that ability on other platforms.
8397 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION
;
8403 // SystemSupportsHardFailRevocationChecking returns true iff the current
8404 // operating system supports revocation checking and can distinguish between
8405 // situations where a given certificate lacks any revocation information (eg:
8406 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8407 // revocation information cannot be obtained (eg: the CRL was unreachable).
8408 // If it does not, then tests which rely on 'hard fail' behaviour should be
8410 static bool SystemSupportsHardFailRevocationChecking() {
8411 #if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
8418 // SystemUsesChromiumEVMetadata returns true iff the current operating system
8419 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8420 // several tests are effected because our testing EV certificate won't be
8421 // recognised as EV.
8422 static bool SystemUsesChromiumEVMetadata() {
8423 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
8424 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8426 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8427 // On OS X and Android, we use the system to tell us whether a certificate is
8428 // EV or not and the system won't recognise our testing root.
8435 static bool SystemSupportsOCSP() {
8436 #if defined(USE_OPENSSL_CERTS)
8437 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8439 #elif defined(OS_WIN)
8440 return base::win::GetVersion() >= base::win::VERSION_VISTA
;
8441 #elif defined(OS_ANDROID)
8442 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8449 static bool SystemSupportsOCSPStapling() {
8450 #if defined(USE_NSS_CERTS)
8452 #elif defined(OS_WIN)
8453 return base::win::GetVersion() >= base::win::VERSION_VISTA
;
8459 TEST_F(HTTPSOCSPTest
, Valid
) {
8460 if (!SystemSupportsOCSP()) {
8461 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8465 SpawnedTestServer::SSLOptions
ssl_options(
8466 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8467 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
8469 CertStatus cert_status
;
8470 DoConnection(ssl_options
, &cert_status
);
8472 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
8474 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8475 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
8477 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8480 TEST_F(HTTPSOCSPTest
, Revoked
) {
8481 if (!SystemSupportsOCSP()) {
8482 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8486 SpawnedTestServer::SSLOptions
ssl_options(
8487 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8488 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
8490 CertStatus cert_status
;
8491 DoConnection(ssl_options
, &cert_status
);
8493 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
8494 // Doesn't pass on OS X yet for reasons that need to be investigated.
8495 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
8497 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8498 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8501 TEST_F(HTTPSOCSPTest
, Invalid
) {
8502 if (!SystemSupportsOCSP()) {
8503 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8507 SpawnedTestServer::SSLOptions
ssl_options(
8508 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8509 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
8511 CertStatus cert_status
;
8512 DoConnection(ssl_options
, &cert_status
);
8514 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8515 cert_status
& CERT_STATUS_ALL_ERRORS
);
8517 // Without a positive OCSP response, we shouldn't show the EV status.
8518 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8519 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8522 TEST_F(HTTPSOCSPTest
, ValidStapled
) {
8523 if (!SystemSupportsOCSPStapling()) {
8525 << "Skipping test because system doesn't support OCSP stapling";
8529 SpawnedTestServer::SSLOptions
ssl_options(
8530 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8531 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
8532 ssl_options
.staple_ocsp_response
= true;
8533 ssl_options
.ocsp_server_unavailable
= true;
8535 CertStatus cert_status
;
8536 DoConnection(ssl_options
, &cert_status
);
8538 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
8540 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8541 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
8543 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8546 // Disabled on NSS ports. See https://crbug.com/431716.
8547 #if defined(USE_NSS_CERTS)
8548 #define MAYBE_RevokedStapled DISABLED_RevokedStapled
8550 #define MAYBE_RevokedStapled RevokedStapled
8552 TEST_F(HTTPSOCSPTest
, MAYBE_RevokedStapled
) {
8553 if (!SystemSupportsOCSPStapling()) {
8555 << "Skipping test because system doesn't support OCSP stapling";
8559 SpawnedTestServer::SSLOptions
ssl_options(
8560 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8561 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
8562 ssl_options
.staple_ocsp_response
= true;
8563 ssl_options
.ocsp_server_unavailable
= true;
8565 CertStatus cert_status
;
8566 DoConnection(ssl_options
, &cert_status
);
8568 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
8569 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8570 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8573 class HTTPSHardFailTest
: public HTTPSOCSPTest
{
8575 void SetupContext(URLRequestContext
* context
) override
{
8576 context
->set_ssl_config_service(
8577 new TestSSLConfigService(false /* check for EV */,
8578 false /* online revocation checking */,
8579 true /* require rev. checking for local
8584 TEST_F(HTTPSHardFailTest
, FailsOnOCSPInvalid
) {
8585 if (!SystemSupportsOCSP()) {
8586 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8590 if (!SystemSupportsHardFailRevocationChecking()) {
8591 LOG(WARNING
) << "Skipping test because system doesn't support hard fail "
8592 << "revocation checking";
8596 SpawnedTestServer::SSLOptions
ssl_options(
8597 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8598 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
8600 CertStatus cert_status
;
8601 DoConnection(ssl_options
, &cert_status
);
8603 EXPECT_EQ(CERT_STATUS_REVOKED
,
8604 cert_status
& CERT_STATUS_REVOKED
);
8606 // Without a positive OCSP response, we shouldn't show the EV status.
8607 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8610 class HTTPSEVCRLSetTest
: public HTTPSOCSPTest
{
8612 void SetupContext(URLRequestContext
* context
) override
{
8613 context
->set_ssl_config_service(
8614 new TestSSLConfigService(true /* check for EV */,
8615 false /* online revocation checking */,
8616 false /* require rev. checking for local
8621 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndInvalidOCSP
) {
8622 if (!SystemSupportsOCSP()) {
8623 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8627 SpawnedTestServer::SSLOptions
ssl_options(
8628 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8629 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
8630 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
8632 CertStatus cert_status
;
8633 DoConnection(ssl_options
, &cert_status
);
8635 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8636 cert_status
& CERT_STATUS_ALL_ERRORS
);
8638 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8639 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8640 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
8643 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndRevokedOCSP
) {
8644 if (!SystemSupportsOCSP()) {
8645 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8649 SpawnedTestServer::SSLOptions
ssl_options(
8650 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8651 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
8652 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
8654 CertStatus cert_status
;
8655 DoConnection(ssl_options
, &cert_status
);
8657 // Currently only works for Windows. When using NSS or OS X, it's not
8658 // possible to determine whether the check failed because of actual
8659 // revocation or because there was an OCSP failure.
8661 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
8663 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
8666 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8667 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8668 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
8671 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndGoodOCSP
) {
8672 if (!SystemSupportsOCSP()) {
8673 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8677 SpawnedTestServer::SSLOptions
ssl_options(
8678 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8679 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
8680 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
8682 CertStatus cert_status
;
8683 DoConnection(ssl_options
, &cert_status
);
8685 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
8687 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8688 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
8689 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8690 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
8693 TEST_F(HTTPSEVCRLSetTest
, ExpiredCRLSet
) {
8694 if (!SystemSupportsOCSP()) {
8695 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8699 SpawnedTestServer::SSLOptions
ssl_options(
8700 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8701 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
8702 SSLConfigService::SetCRLSet(
8703 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
8705 CertStatus cert_status
;
8706 DoConnection(ssl_options
, &cert_status
);
8708 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8709 cert_status
& CERT_STATUS_ALL_ERRORS
);
8711 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8712 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8713 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
8716 TEST_F(HTTPSEVCRLSetTest
, FreshCRLSetCovered
) {
8717 if (!SystemSupportsOCSP()) {
8718 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8722 SpawnedTestServer::SSLOptions
ssl_options(
8723 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8724 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
8725 SSLConfigService::SetCRLSet(
8726 scoped_refptr
<CRLSet
>(CRLSet::ForTesting(
8727 false, &kOCSPTestCertSPKI
, "")));
8729 CertStatus cert_status
;
8730 DoConnection(ssl_options
, &cert_status
);
8732 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8733 // revocation check for EV.
8734 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
8735 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8736 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
8738 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
8741 TEST_F(HTTPSEVCRLSetTest
, FreshCRLSetNotCovered
) {
8742 if (!SystemSupportsOCSP()) {
8743 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8747 SpawnedTestServer::SSLOptions
ssl_options(
8748 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8749 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
8750 SSLConfigService::SetCRLSet(
8751 scoped_refptr
<CRLSet
>(CRLSet::EmptyCRLSetForTesting()));
8753 CertStatus cert_status
= 0;
8754 DoConnection(ssl_options
, &cert_status
);
8756 // Even with a fresh CRLSet, we should still do online revocation checks when
8757 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8759 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8760 cert_status
& CERT_STATUS_ALL_ERRORS
);
8762 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8763 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8764 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
8767 TEST_F(HTTPSEVCRLSetTest
, ExpiredCRLSetAndRevokedNonEVCert
) {
8768 // Test that when EV verification is requested, but online revocation
8769 // checking is disabled, and the leaf certificate is not in fact EV, that
8770 // no revocation checking actually happens.
8771 if (!SystemSupportsOCSP()) {
8772 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
8776 // Unmark the certificate's OID as EV, which should disable revocation
8777 // checking (as per the user preference)
8778 ev_test_policy_
.reset();
8780 SpawnedTestServer::SSLOptions
ssl_options(
8781 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8782 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
8783 SSLConfigService::SetCRLSet(
8784 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
8786 CertStatus cert_status
;
8787 DoConnection(ssl_options
, &cert_status
);
8789 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
8791 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8792 EXPECT_FALSE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8795 class HTTPSCRLSetTest
: public HTTPSOCSPTest
{
8797 void SetupContext(URLRequestContext
* context
) override
{
8798 context
->set_ssl_config_service(
8799 new TestSSLConfigService(false /* check for EV */,
8800 false /* online revocation checking */,
8801 false /* require rev. checking for local
8806 TEST_F(HTTPSCRLSetTest
, ExpiredCRLSet
) {
8807 SpawnedTestServer::SSLOptions
ssl_options(
8808 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8809 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
8810 SSLConfigService::SetCRLSet(
8811 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
8813 CertStatus cert_status
;
8814 DoConnection(ssl_options
, &cert_status
);
8816 // If we're not trying EV verification then, even if the CRLSet has expired,
8817 // we don't fall back to online revocation checks.
8818 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
8819 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8820 EXPECT_FALSE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
8823 TEST_F(HTTPSCRLSetTest
, CRLSetRevoked
) {
8824 #if defined(OS_ANDROID)
8825 LOG(WARNING
) << "Skipping test because system doesn't support CRLSets";
8829 SpawnedTestServer::SSLOptions
ssl_options(
8830 SpawnedTestServer::SSLOptions::CERT_AUTO
);
8831 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
8832 ssl_options
.cert_serial
= 10;
8833 SSLConfigService::SetCRLSet(
8834 scoped_refptr
<CRLSet
>(CRLSet::ForTesting(
8835 false, &kOCSPTestCertSPKI
, "\x0a")));
8837 CertStatus cert_status
= 0;
8838 DoConnection(ssl_options
, &cert_status
);
8840 // If the certificate is recorded as revoked in the CRLSet, that should be
8841 // reflected without online revocation checking.
8842 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
8843 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
8845 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
8847 #endif // !defined(OS_IOS)
8849 #if !defined(DISABLE_FTP_SUPPORT)
8850 class URLRequestTestFTP
: public URLRequestTest
{
8853 : test_server_(SpawnedTestServer::TYPE_FTP
, SpawnedTestServer::kLocalhost
,
8858 SpawnedTestServer test_server_
;
8861 // Make sure an FTP request using an unsafe ports fails.
8862 TEST_F(URLRequestTestFTP
, UnsafePort
) {
8863 ASSERT_TRUE(test_server_
.Start());
8865 URLRequestJobFactoryImpl job_factory
;
8866 FtpNetworkLayer
ftp_transaction_factory(default_context_
.host_resolver());
8868 GURL
url("ftp://127.0.0.1:7");
8869 job_factory
.SetProtocolHandler(
8871 new FtpProtocolHandler(&ftp_transaction_factory
));
8872 default_context_
.set_job_factory(&job_factory
);
8876 scoped_ptr
<URLRequest
> r(
8877 default_context_
.CreateRequest(url
, DEFAULT_PRIORITY
, &d
));
8879 EXPECT_TRUE(r
->is_pending());
8881 base::RunLoop().Run();
8883 EXPECT_FALSE(r
->is_pending());
8884 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
8885 EXPECT_EQ(ERR_UNSAFE_PORT
, r
->status().error());
8889 // Flaky, see http://crbug.com/25045.
8890 TEST_F(URLRequestTestFTP
, DISABLED_FTPDirectoryListing
) {
8891 ASSERT_TRUE(test_server_
.Start());
8895 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8896 test_server_
.GetURL("/"), DEFAULT_PRIORITY
, &d
));
8898 EXPECT_TRUE(r
->is_pending());
8900 base::RunLoop().Run();
8902 EXPECT_FALSE(r
->is_pending());
8903 EXPECT_EQ(1, d
.response_started_count());
8904 EXPECT_FALSE(d
.received_data_before_response());
8905 EXPECT_LT(0, d
.bytes_received());
8906 EXPECT_EQ(test_server_
.host_port_pair().host(),
8907 r
->GetSocketAddress().host());
8908 EXPECT_EQ(test_server_
.host_port_pair().port(),
8909 r
->GetSocketAddress().port());
8913 // Flaky, see http://crbug.com/25045.
8914 TEST_F(URLRequestTestFTP
, DISABLED_FTPGetTestAnonymous
) {
8915 ASSERT_TRUE(test_server_
.Start());
8917 base::FilePath app_path
;
8918 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8919 app_path
= app_path
.AppendASCII("LICENSE");
8922 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8923 test_server_
.GetURL("/LICENSE"), DEFAULT_PRIORITY
, &d
));
8925 EXPECT_TRUE(r
->is_pending());
8927 base::RunLoop().Run();
8929 int64 file_size
= 0;
8930 base::GetFileSize(app_path
, &file_size
);
8932 EXPECT_FALSE(r
->is_pending());
8933 EXPECT_EQ(1, d
.response_started_count());
8934 EXPECT_FALSE(d
.received_data_before_response());
8935 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
8936 EXPECT_EQ(test_server_
.host_port_pair().host(),
8937 r
->GetSocketAddress().host());
8938 EXPECT_EQ(test_server_
.host_port_pair().port(),
8939 r
->GetSocketAddress().port());
8943 // Flaky, see http://crbug.com/25045.
8944 TEST_F(URLRequestTestFTP
, DISABLED_FTPGetTest
) {
8945 ASSERT_TRUE(test_server_
.Start());
8947 base::FilePath app_path
;
8948 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8949 app_path
= app_path
.AppendASCII("LICENSE");
8952 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8953 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8954 DEFAULT_PRIORITY
, &d
));
8956 EXPECT_TRUE(r
->is_pending());
8958 base::RunLoop().Run();
8960 int64 file_size
= 0;
8961 base::GetFileSize(app_path
, &file_size
);
8963 EXPECT_FALSE(r
->is_pending());
8964 EXPECT_EQ(test_server_
.host_port_pair().host(),
8965 r
->GetSocketAddress().host());
8966 EXPECT_EQ(test_server_
.host_port_pair().port(),
8967 r
->GetSocketAddress().port());
8968 EXPECT_EQ(1, d
.response_started_count());
8969 EXPECT_FALSE(d
.received_data_before_response());
8970 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
8972 LoadTimingInfo load_timing_info
;
8973 r
->GetLoadTimingInfo(&load_timing_info
);
8974 TestLoadTimingNoHttpResponse(load_timing_info
);
8978 // Flaky, see http://crbug.com/25045.
8979 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongPassword
) {
8980 ASSERT_TRUE(test_server_
.Start());
8982 base::FilePath app_path
;
8983 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8984 app_path
= app_path
.AppendASCII("LICENSE");
8987 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8988 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome",
8990 DEFAULT_PRIORITY
, &d
));
8992 EXPECT_TRUE(r
->is_pending());
8994 base::RunLoop().Run();
8996 int64 file_size
= 0;
8997 base::GetFileSize(app_path
, &file_size
);
8999 EXPECT_FALSE(r
->is_pending());
9000 EXPECT_EQ(1, d
.response_started_count());
9001 EXPECT_FALSE(d
.received_data_before_response());
9002 EXPECT_EQ(d
.bytes_received(), 0);
9006 // Flaky, see http://crbug.com/25045.
9007 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongPasswordRestart
) {
9008 ASSERT_TRUE(test_server_
.Start());
9010 base::FilePath app_path
;
9011 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
9012 app_path
= app_path
.AppendASCII("LICENSE");
9014 // Set correct login credentials. The delegate will be asked for them when
9015 // the initial login with wrong credentials will fail.
9016 d
.set_credentials(AuthCredentials(kChrome
, kChrome
));
9018 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
9019 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome",
9021 DEFAULT_PRIORITY
, &d
));
9023 EXPECT_TRUE(r
->is_pending());
9025 base::RunLoop().Run();
9027 int64 file_size
= 0;
9028 base::GetFileSize(app_path
, &file_size
);
9030 EXPECT_FALSE(r
->is_pending());
9031 EXPECT_EQ(1, d
.response_started_count());
9032 EXPECT_FALSE(d
.received_data_before_response());
9033 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
9037 // Flaky, see http://crbug.com/25045.
9038 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongUser
) {
9039 ASSERT_TRUE(test_server_
.Start());
9041 base::FilePath app_path
;
9042 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
9043 app_path
= app_path
.AppendASCII("LICENSE");
9046 scoped_ptr
<URLRequest
> r(
9047 default_context_
.CreateRequest(test_server_
.GetURLWithUserAndPassword(
9048 "/LICENSE", "wrong_user", "chrome"),
9049 DEFAULT_PRIORITY
, &d
));
9051 EXPECT_TRUE(r
->is_pending());
9053 base::RunLoop().Run();
9055 int64 file_size
= 0;
9056 base::GetFileSize(app_path
, &file_size
);
9058 EXPECT_FALSE(r
->is_pending());
9059 EXPECT_EQ(1, d
.response_started_count());
9060 EXPECT_FALSE(d
.received_data_before_response());
9061 EXPECT_EQ(d
.bytes_received(), 0);
9065 // Flaky, see http://crbug.com/25045.
9066 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongUserRestart
) {
9067 ASSERT_TRUE(test_server_
.Start());
9069 base::FilePath app_path
;
9070 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
9071 app_path
= app_path
.AppendASCII("LICENSE");
9073 // Set correct login credentials. The delegate will be asked for them when
9074 // the initial login with wrong credentials will fail.
9075 d
.set_credentials(AuthCredentials(kChrome
, kChrome
));
9077 scoped_ptr
<URLRequest
> r(
9078 default_context_
.CreateRequest(test_server_
.GetURLWithUserAndPassword(
9079 "/LICENSE", "wrong_user", "chrome"),
9080 DEFAULT_PRIORITY
, &d
));
9082 EXPECT_TRUE(r
->is_pending());
9084 base::RunLoop().Run();
9086 int64 file_size
= 0;
9087 base::GetFileSize(app_path
, &file_size
);
9089 EXPECT_FALSE(r
->is_pending());
9090 EXPECT_EQ(1, d
.response_started_count());
9091 EXPECT_FALSE(d
.received_data_before_response());
9092 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
9096 // Flaky, see http://crbug.com/25045.
9097 TEST_F(URLRequestTestFTP
, DISABLED_FTPCacheURLCredentials
) {
9098 ASSERT_TRUE(test_server_
.Start());
9100 base::FilePath app_path
;
9101 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
9102 app_path
= app_path
.AppendASCII("LICENSE");
9104 scoped_ptr
<TestDelegate
> d(new TestDelegate
);
9106 // Pass correct login identity in the URL.
9107 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
9108 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
9109 DEFAULT_PRIORITY
, d
.get()));
9111 EXPECT_TRUE(r
->is_pending());
9113 base::RunLoop().Run();
9115 int64 file_size
= 0;
9116 base::GetFileSize(app_path
, &file_size
);
9118 EXPECT_FALSE(r
->is_pending());
9119 EXPECT_EQ(1, d
->response_started_count());
9120 EXPECT_FALSE(d
->received_data_before_response());
9121 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
9124 d
.reset(new TestDelegate
);
9126 // This request should use cached identity from previous request.
9127 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
9128 test_server_
.GetURL("/LICENSE"), DEFAULT_PRIORITY
, d
.get()));
9130 EXPECT_TRUE(r
->is_pending());
9132 base::RunLoop().Run();
9134 int64 file_size
= 0;
9135 base::GetFileSize(app_path
, &file_size
);
9137 EXPECT_FALSE(r
->is_pending());
9138 EXPECT_EQ(1, d
->response_started_count());
9139 EXPECT_FALSE(d
->received_data_before_response());
9140 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
9144 // Flaky, see http://crbug.com/25045.
9145 TEST_F(URLRequestTestFTP
, DISABLED_FTPCacheLoginBoxCredentials
) {
9146 ASSERT_TRUE(test_server_
.Start());
9148 base::FilePath app_path
;
9149 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
9150 app_path
= app_path
.AppendASCII("LICENSE");
9152 scoped_ptr
<TestDelegate
> d(new TestDelegate
);
9153 // Set correct login credentials. The delegate will be asked for them when
9154 // the initial login with wrong credentials will fail.
9155 d
->set_credentials(AuthCredentials(kChrome
, kChrome
));
9157 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
9158 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome",
9160 DEFAULT_PRIORITY
, d
.get()));
9162 EXPECT_TRUE(r
->is_pending());
9164 base::RunLoop().Run();
9166 int64 file_size
= 0;
9167 base::GetFileSize(app_path
, &file_size
);
9169 EXPECT_FALSE(r
->is_pending());
9170 EXPECT_EQ(1, d
->response_started_count());
9171 EXPECT_FALSE(d
->received_data_before_response());
9172 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
9175 // Use a new delegate without explicit credentials. The cached ones should be
9177 d
.reset(new TestDelegate
);
9179 // Don't pass wrong credentials in the URL, they would override valid cached
9181 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
9182 test_server_
.GetURL("/LICENSE"), DEFAULT_PRIORITY
, d
.get()));
9184 EXPECT_TRUE(r
->is_pending());
9186 base::RunLoop().Run();
9188 int64 file_size
= 0;
9189 base::GetFileSize(app_path
, &file_size
);
9191 EXPECT_FALSE(r
->is_pending());
9192 EXPECT_EQ(1, d
->response_started_count());
9193 EXPECT_FALSE(d
->received_data_before_response());
9194 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
9197 #endif // !defined(DISABLE_FTP_SUPPORT)
9199 TEST_F(URLRequestTest
, NetworkAccessedClearBeforeNetworkStart
) {
9201 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
9202 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
9203 d
.set_quit_on_network_start(true);
9205 EXPECT_FALSE(req
->response_info().network_accessed
);
9208 base::RunLoop().Run();
9210 EXPECT_EQ(1, d
.received_before_network_start_count());
9211 EXPECT_EQ(0, d
.response_started_count());
9212 EXPECT_FALSE(req
->response_info().network_accessed
);
9214 req
->ResumeNetworkStart();
9215 base::RunLoop().Run();
9218 TEST_F(URLRequestTest
, NetworkAccessedClearOnDataRequest
) {
9220 scoped_ptr
<URLRequest
> req(
9221 default_context_
.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY
, &d
));
9223 EXPECT_FALSE(req
->response_info().network_accessed
);
9226 base::RunLoop().Run();
9228 EXPECT_EQ(1, default_network_delegate_
.completed_requests());
9229 EXPECT_FALSE(req
->response_info().network_accessed
);
9232 TEST_F(URLRequestTest
, NetworkAccessedSetOnHostResolutionFailure
) {
9233 MockHostResolver host_resolver
;
9234 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
9235 TestURLRequestContext
context(true);
9236 context
.set_network_delegate(&network_delegate
);
9237 context
.set_host_resolver(&host_resolver
);
9238 host_resolver
.rules()->AddSimulatedFailure("*");
9242 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
9243 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
));
9245 EXPECT_FALSE(req
->response_info().network_accessed
);
9248 base::RunLoop().Run();
9249 EXPECT_TRUE(req
->response_info().network_accessed
);