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"
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/format_macros.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/message_loop/message_loop.h"
23 #include "base/message_loop/message_loop_proxy.h"
24 #include "base/path_service.h"
25 #include "base/run_loop.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/stringprintf.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "net/base/capturing_net_log.h"
33 #include "net/base/load_flags.h"
34 #include "net/base/load_timing_info.h"
35 #include "net/base/load_timing_info_test_util.h"
36 #include "net/base/net_errors.h"
37 #include "net/base/net_log.h"
38 #include "net/base/net_log_unittest.h"
39 #include "net/base/net_module.h"
40 #include "net/base/net_util.h"
41 #include "net/base/request_priority.h"
42 #include "net/base/test_data_directory.h"
43 #include "net/base/upload_bytes_element_reader.h"
44 #include "net/base/upload_data_stream.h"
45 #include "net/base/upload_file_element_reader.h"
46 #include "net/cert/ev_root_ca_metadata.h"
47 #include "net/cert/mock_cert_verifier.h"
48 #include "net/cert/test_root_certs.h"
49 #include "net/cookies/cookie_monster.h"
50 #include "net/cookies/cookie_store_test_helpers.h"
51 #include "net/disk_cache/disk_cache.h"
52 #include "net/dns/mock_host_resolver.h"
53 #include "net/ftp/ftp_network_layer.h"
54 #include "net/http/http_byte_range.h"
55 #include "net/http/http_cache.h"
56 #include "net/http/http_network_layer.h"
57 #include "net/http/http_network_session.h"
58 #include "net/http/http_request_headers.h"
59 #include "net/http/http_response_headers.h"
60 #include "net/http/http_util.h"
61 #include "net/ocsp/nss_ocsp.h"
62 #include "net/proxy/proxy_service.h"
63 #include "net/socket/ssl_client_socket.h"
64 #include "net/ssl/ssl_connection_status_flags.h"
65 #include "net/test/cert_test_util.h"
66 #include "net/test/spawned_test_server/spawned_test_server.h"
67 #include "net/url_request/data_protocol_handler.h"
68 #include "net/url_request/static_http_user_agent_settings.h"
69 #include "net/url_request/url_request.h"
70 #include "net/url_request/url_request_http_job.h"
71 #include "net/url_request/url_request_job_factory_impl.h"
72 #include "net/url_request/url_request_redirect_job.h"
73 #include "net/url_request/url_request_test_job.h"
74 #include "net/url_request/url_request_test_util.h"
75 #include "testing/gtest/include/gtest/gtest.h"
76 #include "testing/platform_test.h"
78 #if !defined(DISABLE_FILE_SUPPORT)
79 #include "net/base/filename_util.h"
80 #include "net/url_request/file_protocol_handler.h"
81 #include "net/url_request/url_request_file_dir_job.h"
84 #if !defined(DISABLE_FTP_SUPPORT)
85 #include "net/url_request/ftp_protocol_handler.h"
89 #include "base/win/scoped_com_initializer.h"
90 #include "base/win/scoped_comptr.h"
91 #include "base/win/windows_version.h"
94 using base::ASCIIToUTF16
;
101 const base::string16
kChrome(ASCIIToUTF16("chrome"));
102 const base::string16
kSecret(ASCIIToUTF16("secret"));
103 const base::string16
kUser(ASCIIToUTF16("user"));
105 // Tests load timing information in the case a fresh connection was used, with
107 void TestLoadTimingNotReused(const net::LoadTimingInfo
& load_timing_info
,
108 int connect_timing_flags
) {
109 EXPECT_FALSE(load_timing_info
.socket_reused
);
110 EXPECT_NE(net::NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
112 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
113 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
115 EXPECT_LE(load_timing_info
.request_start
,
116 load_timing_info
.connect_timing
.connect_start
);
117 ExpectConnectTimingHasTimes(load_timing_info
.connect_timing
,
118 connect_timing_flags
);
119 EXPECT_LE(load_timing_info
.connect_timing
.connect_end
,
120 load_timing_info
.send_start
);
121 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
122 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
124 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
125 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
128 // Same as above, but with proxy times.
129 void TestLoadTimingNotReusedWithProxy(
130 const net::LoadTimingInfo
& load_timing_info
,
131 int connect_timing_flags
) {
132 EXPECT_FALSE(load_timing_info
.socket_reused
);
133 EXPECT_NE(net::NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
135 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
136 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
138 EXPECT_LE(load_timing_info
.request_start
,
139 load_timing_info
.proxy_resolve_start
);
140 EXPECT_LE(load_timing_info
.proxy_resolve_start
,
141 load_timing_info
.proxy_resolve_end
);
142 EXPECT_LE(load_timing_info
.proxy_resolve_end
,
143 load_timing_info
.connect_timing
.connect_start
);
144 ExpectConnectTimingHasTimes(load_timing_info
.connect_timing
,
145 connect_timing_flags
);
146 EXPECT_LE(load_timing_info
.connect_timing
.connect_end
,
147 load_timing_info
.send_start
);
148 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
149 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
152 // Same as above, but with a reused socket and proxy times.
153 void TestLoadTimingReusedWithProxy(
154 const net::LoadTimingInfo
& load_timing_info
) {
155 EXPECT_TRUE(load_timing_info
.socket_reused
);
156 EXPECT_NE(net::NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
158 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
159 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
161 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
163 EXPECT_LE(load_timing_info
.request_start
,
164 load_timing_info
.proxy_resolve_start
);
165 EXPECT_LE(load_timing_info
.proxy_resolve_start
,
166 load_timing_info
.proxy_resolve_end
);
167 EXPECT_LE(load_timing_info
.proxy_resolve_end
,
168 load_timing_info
.send_start
);
169 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
170 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
173 // Tests load timing information in the case of a cache hit, when no cache
174 // validation request was sent over the wire.
175 base::StringPiece
TestNetResourceProvider(int key
) {
179 void FillBuffer(char* buffer
, size_t len
) {
180 static bool called
= false;
183 int seed
= static_cast<int>(Time::Now().ToInternalValue());
187 for (size_t i
= 0; i
< len
; i
++) {
188 buffer
[i
] = static_cast<char>(rand());
195 void TestLoadTimingCacheHitNoNetwork(
196 const net::LoadTimingInfo
& load_timing_info
) {
197 EXPECT_FALSE(load_timing_info
.socket_reused
);
198 EXPECT_EQ(net::NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
200 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
201 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
203 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
204 EXPECT_LE(load_timing_info
.request_start
, load_timing_info
.send_start
);
205 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
206 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
208 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
209 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
212 // Tests load timing in the case that there is no HTTP response. This can be
213 // used to test in the case of errors or non-HTTP requests.
214 void TestLoadTimingNoHttpResponse(
215 const net::LoadTimingInfo
& load_timing_info
) {
216 EXPECT_FALSE(load_timing_info
.socket_reused
);
217 EXPECT_EQ(net::NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
219 // Only the request times should be non-null.
220 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
221 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
223 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
225 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
226 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
227 EXPECT_TRUE(load_timing_info
.send_start
.is_null());
228 EXPECT_TRUE(load_timing_info
.send_end
.is_null());
229 EXPECT_TRUE(load_timing_info
.receive_headers_end
.is_null());
232 // Do a case-insensitive search through |haystack| for |needle|.
233 bool ContainsString(const std::string
& haystack
, const char* needle
) {
234 std::string::const_iterator it
=
235 std::search(haystack
.begin(),
238 needle
+ strlen(needle
),
239 base::CaseInsensitiveCompare
<char>());
240 return it
!= haystack
.end();
243 UploadDataStream
* CreateSimpleUploadData(const char* data
) {
244 scoped_ptr
<UploadElementReader
> reader(
245 new UploadBytesElementReader(data
, strlen(data
)));
246 return UploadDataStream::CreateWithReader(reader
.Pass(), 0);
249 // Verify that the SSLInfo of a successful SSL connection has valid values.
250 void CheckSSLInfo(const SSLInfo
& ssl_info
) {
251 // -1 means unknown. 0 means no encryption.
252 EXPECT_GT(ssl_info
.security_bits
, 0);
254 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
255 int cipher_suite
= SSLConnectionStatusToCipherSuite(
256 ssl_info
.connection_status
);
257 EXPECT_NE(0, cipher_suite
);
260 void CheckFullRequestHeaders(const HttpRequestHeaders
& headers
,
261 const GURL
& host_url
) {
262 std::string sent_value
;
264 EXPECT_TRUE(headers
.GetHeader("Host", &sent_value
));
265 EXPECT_EQ(GetHostAndOptionalPort(host_url
), sent_value
);
267 EXPECT_TRUE(headers
.GetHeader("Connection", &sent_value
));
268 EXPECT_EQ("keep-alive", sent_value
);
271 bool FingerprintsEqual(const HashValueVector
& a
, const HashValueVector
& b
) {
272 size_t size
= a
.size();
274 if (size
!= b
.size())
277 for (size_t i
= 0; i
< size
; ++i
) {
278 if (!a
[i
].Equals(b
[i
]))
284 #endif // !defined(OS_IOS)
286 // A network delegate that allows the user to choose a subset of request stages
287 // to block in. When blocking, the delegate can do one of the following:
288 // * synchronously return a pre-specified error code, or
289 // * asynchronously return that value via an automatically called callback,
291 // * block and wait for the user to do a callback.
292 // Additionally, the user may also specify a redirect URL -- then each request
293 // with the current URL different from the redirect target will be redirected
294 // to that target, in the on-before-URL-request stage, independent of whether
295 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
296 class BlockingNetworkDelegate
: public TestNetworkDelegate
{
298 // Stages in which the delegate can block.
301 ON_BEFORE_URL_REQUEST
= 1 << 0,
302 ON_BEFORE_SEND_HEADERS
= 1 << 1,
303 ON_HEADERS_RECEIVED
= 1 << 2,
304 ON_AUTH_REQUIRED
= 1 << 3
307 // Behavior during blocked stages. During other stages, just
308 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
310 SYNCHRONOUS
, // No callback, returns specified return values.
311 AUTO_CALLBACK
, // |this| posts a task to run the callback using the
312 // specified return codes.
313 USER_CALLBACK
, // User takes care of doing a callback. |retval_| and
314 // |auth_retval_| are ignored. In every blocking stage the
315 // message loop is quit.
318 // Creates a delegate which does not block at all.
319 explicit BlockingNetworkDelegate(BlockMode block_mode
);
321 // For users to trigger a callback returning |response|.
322 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
323 // Only call if |block_mode_| == USER_CALLBACK.
324 void DoCallback(int response
);
325 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response
);
328 void set_retval(int retval
) {
329 ASSERT_NE(USER_CALLBACK
, block_mode_
);
330 ASSERT_NE(ERR_IO_PENDING
, retval
);
331 ASSERT_NE(OK
, retval
);
335 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
336 // |auth_credentials_| will be passed with the response.
337 void set_auth_retval(AuthRequiredResponse auth_retval
) {
338 ASSERT_NE(USER_CALLBACK
, block_mode_
);
339 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING
, auth_retval
);
340 auth_retval_
= auth_retval
;
342 void set_auth_credentials(const AuthCredentials
& auth_credentials
) {
343 auth_credentials_
= auth_credentials
;
346 void set_redirect_url(const GURL
& url
) {
350 void set_block_on(int block_on
) {
351 block_on_
= block_on
;
354 // Allows the user to check in which state did we block.
355 Stage
stage_blocked_for_callback() const {
356 EXPECT_EQ(USER_CALLBACK
, block_mode_
);
357 return stage_blocked_for_callback_
;
361 void RunCallback(int response
, const CompletionCallback
& callback
);
362 void RunAuthCallback(AuthRequiredResponse response
,
363 const AuthCallback
& callback
);
365 // TestNetworkDelegate implementation.
366 virtual int OnBeforeURLRequest(URLRequest
* request
,
367 const CompletionCallback
& callback
,
368 GURL
* new_url
) OVERRIDE
;
370 virtual int OnBeforeSendHeaders(URLRequest
* request
,
371 const CompletionCallback
& callback
,
372 HttpRequestHeaders
* headers
) OVERRIDE
;
374 virtual int OnHeadersReceived(
376 const CompletionCallback
& callback
,
377 const HttpResponseHeaders
* original_response_headers
,
378 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
379 GURL
* allowed_unsafe_redirect_url
) OVERRIDE
;
381 virtual NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
383 const AuthChallengeInfo
& auth_info
,
384 const AuthCallback
& callback
,
385 AuthCredentials
* credentials
) OVERRIDE
;
387 // Resets the callbacks and |stage_blocked_for_callback_|.
390 // Checks whether we should block in |stage|. If yes, returns an error code
391 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
392 int MaybeBlockStage(Stage stage
, const CompletionCallback
& callback
);
394 // Configuration parameters, can be adjusted by public methods:
395 const BlockMode block_mode_
;
397 // Values returned on blocking stages when mode is SYNCHRONOUS or
398 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
399 int retval_
; // To be returned in non-auth stages.
400 AuthRequiredResponse auth_retval_
;
402 GURL redirect_url_
; // Used if non-empty during OnBeforeURLRequest.
403 int block_on_
; // Bit mask: in which stages to block.
405 // |auth_credentials_| will be copied to |*target_auth_credential_| on
407 AuthCredentials auth_credentials_
;
408 AuthCredentials
* target_auth_credentials_
;
410 // Internal variables, not set by not the user:
411 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
413 Stage stage_blocked_for_callback_
;
415 // Callback objects stored during blocking stages.
416 CompletionCallback callback_
;
417 AuthCallback auth_callback_
;
419 base::WeakPtrFactory
<BlockingNetworkDelegate
> weak_factory_
;
421 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate
);
424 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode
)
425 : block_mode_(block_mode
),
427 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION
),
429 target_auth_credentials_(NULL
),
430 stage_blocked_for_callback_(NOT_BLOCKED
),
431 weak_factory_(this) {
434 void BlockingNetworkDelegate::DoCallback(int response
) {
435 ASSERT_EQ(USER_CALLBACK
, block_mode_
);
436 ASSERT_NE(NOT_BLOCKED
, stage_blocked_for_callback_
);
437 ASSERT_NE(ON_AUTH_REQUIRED
, stage_blocked_for_callback_
);
438 CompletionCallback callback
= callback_
;
440 RunCallback(response
, callback
);
443 void BlockingNetworkDelegate::DoAuthCallback(
444 NetworkDelegate::AuthRequiredResponse response
) {
445 ASSERT_EQ(USER_CALLBACK
, block_mode_
);
446 ASSERT_EQ(ON_AUTH_REQUIRED
, stage_blocked_for_callback_
);
447 AuthCallback auth_callback
= auth_callback_
;
449 RunAuthCallback(response
, auth_callback
);
452 void BlockingNetworkDelegate::RunCallback(int response
,
453 const CompletionCallback
& callback
) {
454 callback
.Run(response
);
457 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response
,
458 const AuthCallback
& callback
) {
459 if (auth_retval_
== AUTH_REQUIRED_RESPONSE_SET_AUTH
) {
460 ASSERT_TRUE(target_auth_credentials_
!= NULL
);
461 *target_auth_credentials_
= auth_credentials_
;
463 callback
.Run(response
);
466 int BlockingNetworkDelegate::OnBeforeURLRequest(
468 const CompletionCallback
& callback
,
470 if (redirect_url_
== request
->url())
471 return OK
; // We've already seen this request and redirected elsewhere.
473 TestNetworkDelegate::OnBeforeURLRequest(request
, callback
, new_url
);
475 if (!redirect_url_
.is_empty())
476 *new_url
= redirect_url_
;
478 return MaybeBlockStage(ON_BEFORE_URL_REQUEST
, callback
);
481 int BlockingNetworkDelegate::OnBeforeSendHeaders(
483 const CompletionCallback
& callback
,
484 HttpRequestHeaders
* headers
) {
485 TestNetworkDelegate::OnBeforeSendHeaders(request
, callback
, headers
);
487 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS
, callback
);
490 int BlockingNetworkDelegate::OnHeadersReceived(
492 const CompletionCallback
& callback
,
493 const HttpResponseHeaders
* original_response_headers
,
494 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
495 GURL
* allowed_unsafe_redirect_url
) {
496 TestNetworkDelegate::OnHeadersReceived(request
,
498 original_response_headers
,
499 override_response_headers
,
500 allowed_unsafe_redirect_url
);
502 return MaybeBlockStage(ON_HEADERS_RECEIVED
, callback
);
505 NetworkDelegate::AuthRequiredResponse
BlockingNetworkDelegate::OnAuthRequired(
507 const AuthChallengeInfo
& auth_info
,
508 const AuthCallback
& callback
,
509 AuthCredentials
* credentials
) {
510 TestNetworkDelegate::OnAuthRequired(request
, auth_info
, callback
,
512 // Check that the user has provided callback for the previous blocked stage.
513 EXPECT_EQ(NOT_BLOCKED
, stage_blocked_for_callback_
);
515 if ((block_on_
& ON_AUTH_REQUIRED
) == 0) {
516 return AUTH_REQUIRED_RESPONSE_NO_ACTION
;
519 target_auth_credentials_
= credentials
;
521 switch (block_mode_
) {
523 if (auth_retval_
== AUTH_REQUIRED_RESPONSE_SET_AUTH
)
524 *target_auth_credentials_
= auth_credentials_
;
528 base::MessageLoop::current()->PostTask(
530 base::Bind(&BlockingNetworkDelegate::RunAuthCallback
,
531 weak_factory_
.GetWeakPtr(), auth_retval_
, callback
));
532 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
535 auth_callback_
= callback
;
536 stage_blocked_for_callback_
= ON_AUTH_REQUIRED
;
537 base::MessageLoop::current()->PostTask(FROM_HERE
,
538 base::MessageLoop::QuitClosure());
539 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
542 return AUTH_REQUIRED_RESPONSE_NO_ACTION
; // Dummy value.
545 void BlockingNetworkDelegate::Reset() {
546 EXPECT_NE(NOT_BLOCKED
, stage_blocked_for_callback_
);
547 stage_blocked_for_callback_
= NOT_BLOCKED
;
549 auth_callback_
.Reset();
552 int BlockingNetworkDelegate::MaybeBlockStage(
553 BlockingNetworkDelegate::Stage stage
,
554 const CompletionCallback
& callback
) {
555 // Check that the user has provided callback for the previous blocked stage.
556 EXPECT_EQ(NOT_BLOCKED
, stage_blocked_for_callback_
);
558 if ((block_on_
& stage
) == 0) {
562 switch (block_mode_
) {
564 EXPECT_NE(OK
, retval_
);
568 base::MessageLoop::current()->PostTask(
570 base::Bind(&BlockingNetworkDelegate::RunCallback
,
571 weak_factory_
.GetWeakPtr(), retval_
, callback
));
572 return ERR_IO_PENDING
;
575 callback_
= callback
;
576 stage_blocked_for_callback_
= stage
;
577 base::MessageLoop::current()->PostTask(FROM_HERE
,
578 base::MessageLoop::QuitClosure());
579 return ERR_IO_PENDING
;
585 class TestURLRequestContextWithProxy
: public TestURLRequestContext
{
587 // Does not own |delegate|.
588 TestURLRequestContextWithProxy(const std::string
& proxy
,
589 NetworkDelegate
* delegate
)
590 : TestURLRequestContext(true) {
591 context_storage_
.set_proxy_service(ProxyService::CreateFixed(proxy
));
592 set_network_delegate(delegate
);
595 virtual ~TestURLRequestContextWithProxy() {}
600 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
601 class URLRequestTest
: public PlatformTest
{
603 URLRequestTest() : default_context_(true) {
604 default_context_
.set_network_delegate(&default_network_delegate_
);
605 default_context_
.set_net_log(&net_log_
);
606 job_factory_
.SetProtocolHandler("data", new DataProtocolHandler
);
607 #if !defined(DISABLE_FILE_SUPPORT)
608 job_factory_
.SetProtocolHandler(
609 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
611 default_context_
.set_job_factory(&job_factory_
);
612 default_context_
.Init();
614 virtual ~URLRequestTest() {
615 // URLRequestJobs may post clean-up tasks on destruction.
616 base::RunLoop().RunUntilIdle();
619 // Adds the TestJobInterceptor to the default context.
620 TestJobInterceptor
* AddTestInterceptor() {
621 TestJobInterceptor
* protocol_handler_
= new TestJobInterceptor();
622 job_factory_
.SetProtocolHandler("http", NULL
);
623 job_factory_
.SetProtocolHandler("http", protocol_handler_
);
624 return protocol_handler_
;
628 CapturingNetLog net_log_
;
629 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
630 URLRequestJobFactoryImpl job_factory_
;
631 TestURLRequestContext default_context_
;
634 TEST_F(URLRequestTest
, AboutBlankTest
) {
637 URLRequest
r(GURL("about:blank"), DEFAULT_PRIORITY
, &d
, &default_context_
);
640 EXPECT_TRUE(r
.is_pending());
642 base::RunLoop().Run();
644 EXPECT_TRUE(!r
.is_pending());
645 EXPECT_FALSE(d
.received_data_before_response());
646 EXPECT_EQ(d
.bytes_received(), 0);
647 EXPECT_EQ("", r
.GetSocketAddress().host());
648 EXPECT_EQ(0, r
.GetSocketAddress().port());
650 HttpRequestHeaders headers
;
651 EXPECT_FALSE(r
.GetFullRequestHeaders(&headers
));
655 TEST_F(URLRequestTest
, DataURLImageTest
) {
658 // Use our nice little Chrome logo.
661 "data:image/png;base64,"
662 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
663 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
664 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
665 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
666 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
667 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
668 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
669 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
670 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
671 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
672 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
673 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
674 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
675 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
676 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
677 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
678 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
679 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
685 EXPECT_TRUE(r
.is_pending());
687 base::RunLoop().Run();
689 EXPECT_TRUE(!r
.is_pending());
690 EXPECT_FALSE(d
.received_data_before_response());
691 EXPECT_EQ(d
.bytes_received(), 911);
692 EXPECT_EQ("", r
.GetSocketAddress().host());
693 EXPECT_EQ(0, r
.GetSocketAddress().port());
695 HttpRequestHeaders headers
;
696 EXPECT_FALSE(r
.GetFullRequestHeaders(&headers
));
700 #if !defined(DISABLE_FILE_SUPPORT)
701 TEST_F(URLRequestTest
, FileTest
) {
702 base::FilePath app_path
;
703 PathService::Get(base::FILE_EXE
, &app_path
);
704 GURL app_url
= FilePathToFileURL(app_path
);
708 URLRequest
r(app_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
711 EXPECT_TRUE(r
.is_pending());
713 base::RunLoop().Run();
715 int64 file_size
= -1;
716 EXPECT_TRUE(base::GetFileSize(app_path
, &file_size
));
718 EXPECT_TRUE(!r
.is_pending());
719 EXPECT_EQ(1, d
.response_started_count());
720 EXPECT_FALSE(d
.received_data_before_response());
721 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
722 EXPECT_EQ("", r
.GetSocketAddress().host());
723 EXPECT_EQ(0, r
.GetSocketAddress().port());
725 HttpRequestHeaders headers
;
726 EXPECT_FALSE(r
.GetFullRequestHeaders(&headers
));
730 TEST_F(URLRequestTest
, FileTestCancel
) {
731 base::FilePath app_path
;
732 PathService::Get(base::FILE_EXE
, &app_path
);
733 GURL app_url
= FilePathToFileURL(app_path
);
737 URLRequest
r(app_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
740 EXPECT_TRUE(r
.is_pending());
743 // Async cancellation should be safe even when URLRequest has been already
745 base::RunLoop().RunUntilIdle();
748 TEST_F(URLRequestTest
, FileTestFullSpecifiedRange
) {
749 const size_t buffer_size
= 4000;
750 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
751 FillBuffer(buffer
.get(), buffer_size
);
753 base::FilePath temp_path
;
754 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
755 GURL temp_url
= FilePathToFileURL(temp_path
);
756 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
759 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
761 const size_t first_byte_position
= 500;
762 const size_t last_byte_position
= buffer_size
- first_byte_position
;
763 const size_t content_length
= last_byte_position
- first_byte_position
+ 1;
764 std::string
partial_buffer_string(buffer
.get() + first_byte_position
,
765 buffer
.get() + last_byte_position
+ 1);
769 URLRequest
r(temp_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
771 HttpRequestHeaders headers
;
773 HttpRequestHeaders::kRange
,
774 net::HttpByteRange::Bounded(
775 first_byte_position
, last_byte_position
).GetHeaderValue());
776 r
.SetExtraRequestHeaders(headers
);
778 EXPECT_TRUE(r
.is_pending());
780 base::RunLoop().Run();
781 EXPECT_TRUE(!r
.is_pending());
782 EXPECT_EQ(1, d
.response_started_count());
783 EXPECT_FALSE(d
.received_data_before_response());
784 EXPECT_EQ(static_cast<int>(content_length
), d
.bytes_received());
785 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
786 EXPECT_TRUE(partial_buffer_string
== d
.data_received());
789 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
792 TEST_F(URLRequestTest
, FileTestHalfSpecifiedRange
) {
793 const size_t buffer_size
= 4000;
794 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
795 FillBuffer(buffer
.get(), buffer_size
);
797 base::FilePath temp_path
;
798 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
799 GURL temp_url
= FilePathToFileURL(temp_path
);
800 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
803 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
805 const size_t first_byte_position
= 500;
806 const size_t last_byte_position
= buffer_size
- 1;
807 const size_t content_length
= last_byte_position
- first_byte_position
+ 1;
808 std::string
partial_buffer_string(buffer
.get() + first_byte_position
,
809 buffer
.get() + last_byte_position
+ 1);
813 URLRequest
r(temp_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
815 HttpRequestHeaders headers
;
816 headers
.SetHeader(HttpRequestHeaders::kRange
,
817 net::HttpByteRange::RightUnbounded(
818 first_byte_position
).GetHeaderValue());
819 r
.SetExtraRequestHeaders(headers
);
821 EXPECT_TRUE(r
.is_pending());
823 base::RunLoop().Run();
824 EXPECT_TRUE(!r
.is_pending());
825 EXPECT_EQ(1, d
.response_started_count());
826 EXPECT_FALSE(d
.received_data_before_response());
827 EXPECT_EQ(static_cast<int>(content_length
), d
.bytes_received());
828 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
829 EXPECT_TRUE(partial_buffer_string
== d
.data_received());
832 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
835 TEST_F(URLRequestTest
, FileTestMultipleRanges
) {
836 const size_t buffer_size
= 400000;
837 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
838 FillBuffer(buffer
.get(), buffer_size
);
840 base::FilePath temp_path
;
841 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
842 GURL temp_url
= FilePathToFileURL(temp_path
);
843 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
846 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
850 URLRequest
r(temp_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
852 HttpRequestHeaders headers
;
853 headers
.SetHeader(HttpRequestHeaders::kRange
, "bytes=0-0,10-200,200-300");
854 r
.SetExtraRequestHeaders(headers
);
856 EXPECT_TRUE(r
.is_pending());
858 base::RunLoop().Run();
859 EXPECT_TRUE(d
.request_failed());
862 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
865 TEST_F(URLRequestTest
, AllowFileURLs
) {
866 base::ScopedTempDir temp_dir
;
867 ASSERT_TRUE(temp_dir
.CreateUniqueTempDir());
868 base::FilePath test_file
;
869 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir
.path(), &test_file
));
870 std::string
test_data("monkey");
871 base::WriteFile(test_file
, test_data
.data(), test_data
.size());
872 GURL test_file_url
= net::FilePathToFileURL(test_file
);
876 TestNetworkDelegate network_delegate
;
877 network_delegate
.set_can_access_files(true);
878 default_context_
.set_network_delegate(&network_delegate
);
879 URLRequest
r(test_file_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
881 base::RunLoop().Run();
882 EXPECT_FALSE(d
.request_failed());
883 EXPECT_EQ(test_data
, d
.data_received());
888 TestNetworkDelegate network_delegate
;
889 network_delegate
.set_can_access_files(false);
890 default_context_
.set_network_delegate(&network_delegate
);
891 URLRequest
r(test_file_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
893 base::RunLoop().Run();
894 EXPECT_TRUE(d
.request_failed());
895 EXPECT_EQ("", d
.data_received());
900 TEST_F(URLRequestTest
, FileDirCancelTest
) {
901 // Put in mock resource provider.
902 NetModule::SetResourceProvider(TestNetResourceProvider
);
906 base::FilePath file_path
;
907 PathService::Get(base::DIR_SOURCE_ROOT
, &file_path
);
908 file_path
= file_path
.Append(FILE_PATH_LITERAL("net"));
909 file_path
= file_path
.Append(FILE_PATH_LITERAL("data"));
912 FilePathToFileURL(file_path
), DEFAULT_PRIORITY
, &d
, &default_context_
);
914 EXPECT_TRUE(req
.is_pending());
916 d
.set_cancel_in_received_data_pending(true);
918 base::RunLoop().Run();
921 // Take out mock resource provider.
922 NetModule::SetResourceProvider(NULL
);
925 TEST_F(URLRequestTest
, FileDirOutputSanity
) {
926 // Verify the general sanity of the the output of the file:
927 // directory lister by checking for the output of a known existing
929 const char sentinel_name
[] = "filedir-sentinel";
932 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
933 path
= path
.Append(FILE_PATH_LITERAL("net"));
934 path
= path
.Append(FILE_PATH_LITERAL("data"));
935 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
939 FilePathToFileURL(path
), DEFAULT_PRIORITY
, &d
, &default_context_
);
941 base::RunLoop().Run();
943 // Generate entry for the sentinel file.
944 base::FilePath sentinel_path
= path
.AppendASCII(sentinel_name
);
945 base::File::Info info
;
946 EXPECT_TRUE(base::GetFileInfo(sentinel_path
, &info
));
947 EXPECT_GT(info
.size
, 0);
948 std::string sentinel_output
= GetDirectoryListingEntry(
949 base::string16(sentinel_name
, sentinel_name
+ strlen(sentinel_name
)),
950 std::string(sentinel_name
),
955 ASSERT_LT(0, d
.bytes_received());
956 ASSERT_FALSE(d
.request_failed());
957 ASSERT_TRUE(req
.status().is_success());
958 // Check for the entry generated for the "sentinel" file.
959 const std::string
& data
= d
.data_received();
960 ASSERT_NE(data
.find(sentinel_output
), std::string::npos
);
963 TEST_F(URLRequestTest
, FileDirRedirectNoCrash
) {
964 // There is an implicit redirect when loading a file path that matches a
965 // directory and does not end with a slash. Ensure that following such
966 // redirects does not crash. See http://crbug.com/18686.
969 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
970 path
= path
.Append(FILE_PATH_LITERAL("net"));
971 path
= path
.Append(FILE_PATH_LITERAL("data"));
972 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
976 FilePathToFileURL(path
), DEFAULT_PRIORITY
, &d
, &default_context_
);
978 base::RunLoop().Run();
980 ASSERT_EQ(1, d
.received_redirect_count());
981 ASSERT_LT(0, d
.bytes_received());
982 ASSERT_FALSE(d
.request_failed());
983 ASSERT_TRUE(req
.status().is_success());
987 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
988 TEST_F(URLRequestTest
, FileDirRedirectSingleSlash
) {
990 URLRequest
req(GURL("file:///"), DEFAULT_PRIORITY
, &d
, &default_context_
);
992 base::RunLoop().Run();
994 ASSERT_EQ(1, d
.received_redirect_count());
995 ASSERT_FALSE(req
.status().is_success());
997 #endif // defined(OS_WIN)
999 #endif // !defined(DISABLE_FILE_SUPPORT)
1001 TEST_F(URLRequestTest
, InvalidUrlTest
) {
1004 URLRequest
r(GURL("invalid url"), DEFAULT_PRIORITY
, &d
, &default_context_
);
1007 EXPECT_TRUE(r
.is_pending());
1009 base::RunLoop().Run();
1010 EXPECT_TRUE(d
.request_failed());
1015 TEST_F(URLRequestTest
, ResolveShortcutTest
) {
1016 base::FilePath app_path
;
1017 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
1018 app_path
= app_path
.AppendASCII("net");
1019 app_path
= app_path
.AppendASCII("data");
1020 app_path
= app_path
.AppendASCII("url_request_unittest");
1021 app_path
= app_path
.AppendASCII("with-headers.html");
1023 std::wstring lnk_path
= app_path
.value() + L
".lnk";
1025 base::win::ScopedCOMInitializer com_initializer
;
1027 // Temporarily create a shortcut for test
1029 base::win::ScopedComPtr
<IShellLink
> shell
;
1030 ASSERT_TRUE(SUCCEEDED(shell
.CreateInstance(CLSID_ShellLink
, NULL
,
1031 CLSCTX_INPROC_SERVER
)));
1032 base::win::ScopedComPtr
<IPersistFile
> persist
;
1033 ASSERT_TRUE(SUCCEEDED(shell
.QueryInterface(persist
.Receive())));
1034 EXPECT_TRUE(SUCCEEDED(shell
->SetPath(app_path
.value().c_str())));
1035 EXPECT_TRUE(SUCCEEDED(shell
->SetDescription(L
"ResolveShortcutTest")));
1036 EXPECT_TRUE(SUCCEEDED(persist
->Save(lnk_path
.c_str(), TRUE
)));
1041 URLRequest
r(FilePathToFileURL(base::FilePath(lnk_path
)),
1047 EXPECT_TRUE(r
.is_pending());
1049 base::RunLoop().Run();
1051 WIN32_FILE_ATTRIBUTE_DATA data
;
1052 GetFileAttributesEx(app_path
.value().c_str(),
1053 GetFileExInfoStandard
, &data
);
1054 HANDLE file
= CreateFile(app_path
.value().c_str(), GENERIC_READ
,
1055 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
1056 FILE_ATTRIBUTE_NORMAL
, NULL
);
1057 EXPECT_NE(INVALID_HANDLE_VALUE
, file
);
1058 scoped_ptr
<char[]> buffer(new char[data
.nFileSizeLow
]);
1061 result
= ReadFile(file
, buffer
.get(), data
.nFileSizeLow
,
1063 std::string
content(buffer
.get(), read_size
);
1066 EXPECT_TRUE(!r
.is_pending());
1067 EXPECT_EQ(1, d
.received_redirect_count());
1068 EXPECT_EQ(content
, d
.data_received());
1071 // Clean the shortcut
1072 DeleteFile(lnk_path
.c_str());
1074 #endif // defined(OS_WIN)
1076 // Custom URLRequestJobs for use with interceptor tests
1077 class RestartTestJob
: public URLRequestTestJob
{
1079 RestartTestJob(URLRequest
* request
, NetworkDelegate
* network_delegate
)
1080 : URLRequestTestJob(request
, network_delegate
, true) {}
1082 virtual void StartAsync() OVERRIDE
{
1083 this->NotifyRestartRequired();
1086 virtual ~RestartTestJob() {}
1089 class CancelTestJob
: public URLRequestTestJob
{
1091 explicit CancelTestJob(URLRequest
* request
, NetworkDelegate
* network_delegate
)
1092 : URLRequestTestJob(request
, network_delegate
, true) {}
1094 virtual void StartAsync() OVERRIDE
{
1098 virtual ~CancelTestJob() {}
1101 class CancelThenRestartTestJob
: public URLRequestTestJob
{
1103 explicit CancelThenRestartTestJob(URLRequest
* request
,
1104 NetworkDelegate
* network_delegate
)
1105 : URLRequestTestJob(request
, network_delegate
, true) {
1108 virtual void StartAsync() OVERRIDE
{
1110 this->NotifyRestartRequired();
1113 virtual ~CancelThenRestartTestJob() {}
1116 // An Interceptor for use with interceptor tests
1117 class TestInterceptor
: URLRequest::Interceptor
{
1120 : intercept_main_request_(false), restart_main_request_(false),
1121 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1122 simulate_main_network_error_(false),
1123 intercept_redirect_(false), cancel_redirect_request_(false),
1124 intercept_final_response_(false), cancel_final_request_(false),
1125 did_intercept_main_(false), did_restart_main_(false),
1126 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1127 did_simulate_error_main_(false),
1128 did_intercept_redirect_(false), did_cancel_redirect_(false),
1129 did_intercept_final_(false), did_cancel_final_(false) {
1130 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1133 virtual ~TestInterceptor() {
1134 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1137 virtual URLRequestJob
* MaybeIntercept(
1138 URLRequest
* request
,
1139 NetworkDelegate
* network_delegate
) OVERRIDE
{
1140 if (restart_main_request_
) {
1141 restart_main_request_
= false;
1142 did_restart_main_
= true;
1143 return new RestartTestJob(request
, network_delegate
);
1145 if (cancel_main_request_
) {
1146 cancel_main_request_
= false;
1147 did_cancel_main_
= true;
1148 return new CancelTestJob(request
, network_delegate
);
1150 if (cancel_then_restart_main_request_
) {
1151 cancel_then_restart_main_request_
= false;
1152 did_cancel_then_restart_main_
= true;
1153 return new CancelThenRestartTestJob(request
, network_delegate
);
1155 if (simulate_main_network_error_
) {
1156 simulate_main_network_error_
= false;
1157 did_simulate_error_main_
= true;
1158 // will error since the requeted url is not one of its canned urls
1159 return new URLRequestTestJob(request
, network_delegate
, true);
1161 if (!intercept_main_request_
)
1163 intercept_main_request_
= false;
1164 did_intercept_main_
= true;
1165 URLRequestTestJob
* job
= new URLRequestTestJob(request
,
1170 job
->set_load_timing_info(main_request_load_timing_info_
);
1174 virtual URLRequestJob
* MaybeInterceptRedirect(
1175 URLRequest
* request
,
1176 NetworkDelegate
* network_delegate
,
1177 const GURL
& location
) OVERRIDE
{
1178 if (cancel_redirect_request_
) {
1179 cancel_redirect_request_
= false;
1180 did_cancel_redirect_
= true;
1181 return new CancelTestJob(request
, network_delegate
);
1183 if (!intercept_redirect_
)
1185 intercept_redirect_
= false;
1186 did_intercept_redirect_
= true;
1187 return new URLRequestTestJob(request
,
1194 virtual URLRequestJob
* MaybeInterceptResponse(
1195 URLRequest
* request
, NetworkDelegate
* network_delegate
) OVERRIDE
{
1196 if (cancel_final_request_
) {
1197 cancel_final_request_
= false;
1198 did_cancel_final_
= true;
1199 return new CancelTestJob(request
, network_delegate
);
1201 if (!intercept_final_response_
)
1203 intercept_final_response_
= false;
1204 did_intercept_final_
= true;
1205 return new URLRequestTestJob(request
,
1212 // Whether to intercept the main request, and if so the response to return and
1213 // the LoadTimingInfo to use.
1214 bool intercept_main_request_
;
1215 std::string main_headers_
;
1216 std::string main_data_
;
1217 LoadTimingInfo main_request_load_timing_info_
;
1219 // Other actions we take at MaybeIntercept time
1220 bool restart_main_request_
;
1221 bool cancel_main_request_
;
1222 bool cancel_then_restart_main_request_
;
1223 bool simulate_main_network_error_
;
1225 // Whether to intercept redirects, and if so the response to return.
1226 bool intercept_redirect_
;
1227 std::string redirect_headers_
;
1228 std::string redirect_data_
;
1230 // Other actions we can take at MaybeInterceptRedirect time
1231 bool cancel_redirect_request_
;
1233 // Whether to intercept final response, and if so the response to return.
1234 bool intercept_final_response_
;
1235 std::string final_headers_
;
1236 std::string final_data_
;
1238 // Other actions we can take at MaybeInterceptResponse time
1239 bool cancel_final_request_
;
1241 // If we did something or not
1242 bool did_intercept_main_
;
1243 bool did_restart_main_
;
1244 bool did_cancel_main_
;
1245 bool did_cancel_then_restart_main_
;
1246 bool did_simulate_error_main_
;
1247 bool did_intercept_redirect_
;
1248 bool did_cancel_redirect_
;
1249 bool did_intercept_final_
;
1250 bool did_cancel_final_
;
1252 // Static getters for canned response header and data strings
1254 static std::string
ok_data() {
1255 return URLRequestTestJob::test_data_1();
1258 static std::string
ok_headers() {
1259 return URLRequestTestJob::test_headers();
1262 static std::string
redirect_data() {
1263 return std::string();
1266 static std::string
redirect_headers() {
1267 return URLRequestTestJob::test_redirect_headers();
1270 static std::string
error_data() {
1271 return std::string("ohhh nooooo mr. bill!");
1274 static std::string
error_headers() {
1275 return URLRequestTestJob::test_error_headers();
1279 TEST_F(URLRequestTest
, Intercept
) {
1280 TestInterceptor interceptor
;
1282 // intercept the main request and respond with a simple response
1283 interceptor
.intercept_main_request_
= true;
1284 interceptor
.main_headers_
= TestInterceptor::ok_headers();
1285 interceptor
.main_data_
= TestInterceptor::ok_data();
1288 URLRequest
req(GURL("http://test_intercept/foo"),
1292 base::SupportsUserData::Data
* user_data0
= new base::SupportsUserData::Data();
1293 base::SupportsUserData::Data
* user_data1
= new base::SupportsUserData::Data();
1294 base::SupportsUserData::Data
* user_data2
= new base::SupportsUserData::Data();
1295 req
.SetUserData(NULL
, user_data0
);
1296 req
.SetUserData(&user_data1
, user_data1
);
1297 req
.SetUserData(&user_data2
, user_data2
);
1298 req
.set_method("GET");
1300 base::RunLoop().Run();
1302 // Make sure we can retrieve our specific user data
1303 EXPECT_EQ(user_data0
, req
.GetUserData(NULL
));
1304 EXPECT_EQ(user_data1
, req
.GetUserData(&user_data1
));
1305 EXPECT_EQ(user_data2
, req
.GetUserData(&user_data2
));
1307 // Check the interceptor got called as expected
1308 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1310 // Check we got one good response
1311 EXPECT_TRUE(req
.status().is_success());
1312 EXPECT_EQ(200, req
.response_headers()->response_code());
1313 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1314 EXPECT_EQ(1, d
.response_started_count());
1315 EXPECT_EQ(0, d
.received_redirect_count());
1318 TEST_F(URLRequestTest
, InterceptRedirect
) {
1319 TestInterceptor interceptor
;
1321 // intercept the main request and respond with a redirect
1322 interceptor
.intercept_main_request_
= true;
1323 interceptor
.main_headers_
= TestInterceptor::redirect_headers();
1324 interceptor
.main_data_
= TestInterceptor::redirect_data();
1326 // intercept that redirect and respond a final OK response
1327 interceptor
.intercept_redirect_
= true;
1328 interceptor
.redirect_headers_
= TestInterceptor::ok_headers();
1329 interceptor
.redirect_data_
= TestInterceptor::ok_data();
1332 URLRequest
req(GURL("http://test_intercept/foo"),
1336 req
.set_method("GET");
1338 base::RunLoop().Run();
1340 // Check the interceptor got called as expected
1341 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1342 EXPECT_TRUE(interceptor
.did_intercept_redirect_
);
1344 // Check we got one good response
1345 EXPECT_TRUE(req
.status().is_success());
1346 if (req
.status().is_success()) {
1347 EXPECT_EQ(200, req
.response_headers()->response_code());
1349 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1350 EXPECT_EQ(1, d
.response_started_count());
1351 EXPECT_EQ(0, d
.received_redirect_count());
1354 TEST_F(URLRequestTest
, InterceptServerError
) {
1355 TestInterceptor interceptor
;
1357 // intercept the main request to generate a server error response
1358 interceptor
.intercept_main_request_
= true;
1359 interceptor
.main_headers_
= TestInterceptor::error_headers();
1360 interceptor
.main_data_
= TestInterceptor::error_data();
1362 // intercept that error and respond with an OK response
1363 interceptor
.intercept_final_response_
= true;
1364 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1365 interceptor
.final_data_
= TestInterceptor::ok_data();
1368 URLRequest
req(GURL("http://test_intercept/foo"),
1372 req
.set_method("GET");
1374 base::RunLoop().Run();
1376 // Check the interceptor got called as expected
1377 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1378 EXPECT_TRUE(interceptor
.did_intercept_final_
);
1380 // Check we got one good response
1381 EXPECT_TRUE(req
.status().is_success());
1382 EXPECT_EQ(200, req
.response_headers()->response_code());
1383 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1384 EXPECT_EQ(1, d
.response_started_count());
1385 EXPECT_EQ(0, d
.received_redirect_count());
1388 TEST_F(URLRequestTest
, InterceptNetworkError
) {
1389 TestInterceptor interceptor
;
1391 // intercept the main request to simulate a network error
1392 interceptor
.simulate_main_network_error_
= true;
1394 // intercept that error and respond with an OK response
1395 interceptor
.intercept_final_response_
= true;
1396 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1397 interceptor
.final_data_
= TestInterceptor::ok_data();
1400 URLRequest
req(GURL("http://test_intercept/foo"),
1404 req
.set_method("GET");
1406 base::RunLoop().Run();
1408 // Check the interceptor got called as expected
1409 EXPECT_TRUE(interceptor
.did_simulate_error_main_
);
1410 EXPECT_TRUE(interceptor
.did_intercept_final_
);
1412 // Check we received one good response
1413 EXPECT_TRUE(req
.status().is_success());
1414 EXPECT_EQ(200, req
.response_headers()->response_code());
1415 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1416 EXPECT_EQ(1, d
.response_started_count());
1417 EXPECT_EQ(0, d
.received_redirect_count());
1420 TEST_F(URLRequestTest
, InterceptRestartRequired
) {
1421 TestInterceptor interceptor
;
1423 // restart the main request
1424 interceptor
.restart_main_request_
= true;
1426 // then intercept the new main request and respond with an OK response
1427 interceptor
.intercept_main_request_
= true;
1428 interceptor
.main_headers_
= TestInterceptor::ok_headers();
1429 interceptor
.main_data_
= TestInterceptor::ok_data();
1432 URLRequest
req(GURL("http://test_intercept/foo"),
1436 req
.set_method("GET");
1438 base::RunLoop().Run();
1440 // Check the interceptor got called as expected
1441 EXPECT_TRUE(interceptor
.did_restart_main_
);
1442 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1444 // Check we received one good response
1445 EXPECT_TRUE(req
.status().is_success());
1446 if (req
.status().is_success()) {
1447 EXPECT_EQ(200, req
.response_headers()->response_code());
1449 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1450 EXPECT_EQ(1, d
.response_started_count());
1451 EXPECT_EQ(0, d
.received_redirect_count());
1454 TEST_F(URLRequestTest
, InterceptRespectsCancelMain
) {
1455 TestInterceptor interceptor
;
1457 // intercept the main request and cancel from within the restarted job
1458 interceptor
.cancel_main_request_
= true;
1460 // setup to intercept final response and override it with an OK response
1461 interceptor
.intercept_final_response_
= true;
1462 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1463 interceptor
.final_data_
= TestInterceptor::ok_data();
1466 URLRequest
req(GURL("http://test_intercept/foo"),
1470 req
.set_method("GET");
1472 base::RunLoop().Run();
1474 // Check the interceptor got called as expected
1475 EXPECT_TRUE(interceptor
.did_cancel_main_
);
1476 EXPECT_FALSE(interceptor
.did_intercept_final_
);
1478 // Check we see a canceled request
1479 EXPECT_FALSE(req
.status().is_success());
1480 EXPECT_EQ(URLRequestStatus::CANCELED
, req
.status().status());
1483 TEST_F(URLRequestTest
, InterceptRespectsCancelRedirect
) {
1484 TestInterceptor interceptor
;
1486 // intercept the main request and respond with a redirect
1487 interceptor
.intercept_main_request_
= true;
1488 interceptor
.main_headers_
= TestInterceptor::redirect_headers();
1489 interceptor
.main_data_
= TestInterceptor::redirect_data();
1491 // intercept the redirect and cancel from within that job
1492 interceptor
.cancel_redirect_request_
= true;
1494 // setup to intercept final response and override it with an OK response
1495 interceptor
.intercept_final_response_
= true;
1496 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1497 interceptor
.final_data_
= TestInterceptor::ok_data();
1500 URLRequest
req(GURL("http://test_intercept/foo"),
1504 req
.set_method("GET");
1506 base::RunLoop().Run();
1508 // Check the interceptor got called as expected
1509 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1510 EXPECT_TRUE(interceptor
.did_cancel_redirect_
);
1511 EXPECT_FALSE(interceptor
.did_intercept_final_
);
1513 // Check we see a canceled request
1514 EXPECT_FALSE(req
.status().is_success());
1515 EXPECT_EQ(URLRequestStatus::CANCELED
, req
.status().status());
1518 TEST_F(URLRequestTest
, InterceptRespectsCancelFinal
) {
1519 TestInterceptor interceptor
;
1521 // intercept the main request to simulate a network error
1522 interceptor
.simulate_main_network_error_
= true;
1524 // setup to intercept final response and cancel from within that job
1525 interceptor
.cancel_final_request_
= true;
1528 URLRequest
req(GURL("http://test_intercept/foo"),
1532 req
.set_method("GET");
1534 base::RunLoop().Run();
1536 // Check the interceptor got called as expected
1537 EXPECT_TRUE(interceptor
.did_simulate_error_main_
);
1538 EXPECT_TRUE(interceptor
.did_cancel_final_
);
1540 // Check we see a canceled request
1541 EXPECT_FALSE(req
.status().is_success());
1542 EXPECT_EQ(URLRequestStatus::CANCELED
, req
.status().status());
1545 TEST_F(URLRequestTest
, InterceptRespectsCancelInRestart
) {
1546 TestInterceptor interceptor
;
1548 // intercept the main request and cancel then restart from within that job
1549 interceptor
.cancel_then_restart_main_request_
= true;
1551 // setup to intercept final response and override it with an OK response
1552 interceptor
.intercept_final_response_
= true;
1553 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1554 interceptor
.final_data_
= TestInterceptor::ok_data();
1557 URLRequest
req(GURL("http://test_intercept/foo"),
1561 req
.set_method("GET");
1563 base::RunLoop().Run();
1565 // Check the interceptor got called as expected
1566 EXPECT_TRUE(interceptor
.did_cancel_then_restart_main_
);
1567 EXPECT_FALSE(interceptor
.did_intercept_final_
);
1569 // Check we see a canceled request
1570 EXPECT_FALSE(req
.status().is_success());
1571 EXPECT_EQ(URLRequestStatus::CANCELED
, req
.status().status());
1574 LoadTimingInfo
RunLoadTimingTest(const LoadTimingInfo
& job_load_timing
,
1575 URLRequestContext
* context
) {
1576 TestInterceptor interceptor
;
1577 interceptor
.intercept_main_request_
= true;
1578 interceptor
.main_request_load_timing_info_
= job_load_timing
;
1581 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, context
);
1583 base::RunLoop().Run();
1585 LoadTimingInfo resulting_load_timing
;
1586 req
.GetLoadTimingInfo(&resulting_load_timing
);
1588 // None of these should be modified by the URLRequest.
1589 EXPECT_EQ(job_load_timing
.socket_reused
, resulting_load_timing
.socket_reused
);
1590 EXPECT_EQ(job_load_timing
.socket_log_id
, resulting_load_timing
.socket_log_id
);
1591 EXPECT_EQ(job_load_timing
.send_start
, resulting_load_timing
.send_start
);
1592 EXPECT_EQ(job_load_timing
.send_end
, resulting_load_timing
.send_end
);
1593 EXPECT_EQ(job_load_timing
.receive_headers_end
,
1594 resulting_load_timing
.receive_headers_end
);
1596 return resulting_load_timing
;
1599 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1600 // reused. |connect_time_flags| is used to indicate if there should be dns
1601 // or SSL times, and |used_proxy| is used for proxy times.
1602 LoadTimingInfo
NormalLoadTimingInfo(base::TimeTicks now
,
1603 int connect_time_flags
,
1605 LoadTimingInfo load_timing
;
1606 load_timing
.socket_log_id
= 1;
1609 load_timing
.proxy_resolve_start
= now
+ base::TimeDelta::FromDays(1);
1610 load_timing
.proxy_resolve_end
= now
+ base::TimeDelta::FromDays(2);
1613 LoadTimingInfo::ConnectTiming
& connect_timing
= load_timing
.connect_timing
;
1614 if (connect_time_flags
& CONNECT_TIMING_HAS_DNS_TIMES
) {
1615 connect_timing
.dns_start
= now
+ base::TimeDelta::FromDays(3);
1616 connect_timing
.dns_end
= now
+ base::TimeDelta::FromDays(4);
1618 connect_timing
.connect_start
= now
+ base::TimeDelta::FromDays(5);
1619 if (connect_time_flags
& CONNECT_TIMING_HAS_SSL_TIMES
) {
1620 connect_timing
.ssl_start
= now
+ base::TimeDelta::FromDays(6);
1621 connect_timing
.ssl_end
= now
+ base::TimeDelta::FromDays(7);
1623 connect_timing
.connect_end
= now
+ base::TimeDelta::FromDays(8);
1625 load_timing
.send_start
= now
+ base::TimeDelta::FromDays(9);
1626 load_timing
.send_end
= now
+ base::TimeDelta::FromDays(10);
1627 load_timing
.receive_headers_end
= now
+ base::TimeDelta::FromDays(11);
1631 // Same as above, but in the case of a reused socket.
1632 LoadTimingInfo
NormalLoadTimingInfoReused(base::TimeTicks now
,
1634 LoadTimingInfo load_timing
;
1635 load_timing
.socket_log_id
= 1;
1636 load_timing
.socket_reused
= true;
1639 load_timing
.proxy_resolve_start
= now
+ base::TimeDelta::FromDays(1);
1640 load_timing
.proxy_resolve_end
= now
+ base::TimeDelta::FromDays(2);
1643 load_timing
.send_start
= now
+ base::TimeDelta::FromDays(9);
1644 load_timing
.send_end
= now
+ base::TimeDelta::FromDays(10);
1645 load_timing
.receive_headers_end
= now
+ base::TimeDelta::FromDays(11);
1649 // Basic test that the intercept + load timing tests work.
1650 TEST_F(URLRequestTest
, InterceptLoadTiming
) {
1651 base::TimeTicks now
= base::TimeTicks::Now();
1652 LoadTimingInfo job_load_timing
=
1653 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_DNS_TIMES
, false);
1655 LoadTimingInfo load_timing_result
=
1656 RunLoadTimingTest(job_load_timing
, &default_context_
);
1658 // Nothing should have been changed by the URLRequest.
1659 EXPECT_EQ(job_load_timing
.proxy_resolve_start
,
1660 load_timing_result
.proxy_resolve_start
);
1661 EXPECT_EQ(job_load_timing
.proxy_resolve_end
,
1662 load_timing_result
.proxy_resolve_end
);
1663 EXPECT_EQ(job_load_timing
.connect_timing
.dns_start
,
1664 load_timing_result
.connect_timing
.dns_start
);
1665 EXPECT_EQ(job_load_timing
.connect_timing
.dns_end
,
1666 load_timing_result
.connect_timing
.dns_end
);
1667 EXPECT_EQ(job_load_timing
.connect_timing
.connect_start
,
1668 load_timing_result
.connect_timing
.connect_start
);
1669 EXPECT_EQ(job_load_timing
.connect_timing
.connect_end
,
1670 load_timing_result
.connect_timing
.connect_end
);
1671 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_start
,
1672 load_timing_result
.connect_timing
.ssl_start
);
1673 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_end
,
1674 load_timing_result
.connect_timing
.ssl_end
);
1676 // Redundant sanity check.
1677 TestLoadTimingNotReused(load_timing_result
, CONNECT_TIMING_HAS_DNS_TIMES
);
1680 // Another basic test, with proxy and SSL times, but no DNS times.
1681 TEST_F(URLRequestTest
, InterceptLoadTimingProxy
) {
1682 base::TimeTicks now
= base::TimeTicks::Now();
1683 LoadTimingInfo job_load_timing
=
1684 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_SSL_TIMES
, true);
1686 LoadTimingInfo load_timing_result
=
1687 RunLoadTimingTest(job_load_timing
, &default_context_
);
1689 // Nothing should have been changed by the URLRequest.
1690 EXPECT_EQ(job_load_timing
.proxy_resolve_start
,
1691 load_timing_result
.proxy_resolve_start
);
1692 EXPECT_EQ(job_load_timing
.proxy_resolve_end
,
1693 load_timing_result
.proxy_resolve_end
);
1694 EXPECT_EQ(job_load_timing
.connect_timing
.dns_start
,
1695 load_timing_result
.connect_timing
.dns_start
);
1696 EXPECT_EQ(job_load_timing
.connect_timing
.dns_end
,
1697 load_timing_result
.connect_timing
.dns_end
);
1698 EXPECT_EQ(job_load_timing
.connect_timing
.connect_start
,
1699 load_timing_result
.connect_timing
.connect_start
);
1700 EXPECT_EQ(job_load_timing
.connect_timing
.connect_end
,
1701 load_timing_result
.connect_timing
.connect_end
);
1702 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_start
,
1703 load_timing_result
.connect_timing
.ssl_start
);
1704 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_end
,
1705 load_timing_result
.connect_timing
.ssl_end
);
1707 // Redundant sanity check.
1708 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1709 CONNECT_TIMING_HAS_SSL_TIMES
);
1712 // Make sure that URLRequest correctly adjusts proxy times when they're before
1713 // |request_start|, due to already having a connected socket. This happens in
1714 // the case of reusing a SPDY session. The connected socket is not considered
1715 // reused in this test (May be a preconnect).
1717 // To mix things up from the test above, assumes DNS times but no SSL times.
1718 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyProxyResolution
) {
1719 base::TimeTicks now
= base::TimeTicks::Now();
1720 LoadTimingInfo job_load_timing
=
1721 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_DNS_TIMES
, true);
1722 job_load_timing
.proxy_resolve_start
= now
- base::TimeDelta::FromDays(6);
1723 job_load_timing
.proxy_resolve_end
= now
- base::TimeDelta::FromDays(5);
1724 job_load_timing
.connect_timing
.dns_start
= now
- base::TimeDelta::FromDays(4);
1725 job_load_timing
.connect_timing
.dns_end
= now
- base::TimeDelta::FromDays(3);
1726 job_load_timing
.connect_timing
.connect_start
=
1727 now
- base::TimeDelta::FromDays(2);
1728 job_load_timing
.connect_timing
.connect_end
=
1729 now
- base::TimeDelta::FromDays(1);
1731 LoadTimingInfo load_timing_result
=
1732 RunLoadTimingTest(job_load_timing
, &default_context_
);
1734 // Proxy times, connect times, and DNS times should all be replaced with
1736 EXPECT_EQ(load_timing_result
.request_start
,
1737 load_timing_result
.proxy_resolve_start
);
1738 EXPECT_EQ(load_timing_result
.request_start
,
1739 load_timing_result
.proxy_resolve_end
);
1740 EXPECT_EQ(load_timing_result
.request_start
,
1741 load_timing_result
.connect_timing
.dns_start
);
1742 EXPECT_EQ(load_timing_result
.request_start
,
1743 load_timing_result
.connect_timing
.dns_end
);
1744 EXPECT_EQ(load_timing_result
.request_start
,
1745 load_timing_result
.connect_timing
.connect_start
);
1746 EXPECT_EQ(load_timing_result
.request_start
,
1747 load_timing_result
.connect_timing
.connect_end
);
1749 // Other times should have been left null.
1750 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1751 CONNECT_TIMING_HAS_DNS_TIMES
);
1754 // Same as above, but in the reused case.
1755 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyProxyResolutionReused
) {
1756 base::TimeTicks now
= base::TimeTicks::Now();
1757 LoadTimingInfo job_load_timing
= NormalLoadTimingInfoReused(now
, true);
1758 job_load_timing
.proxy_resolve_start
= now
- base::TimeDelta::FromDays(4);
1759 job_load_timing
.proxy_resolve_end
= now
- base::TimeDelta::FromDays(3);
1761 LoadTimingInfo load_timing_result
=
1762 RunLoadTimingTest(job_load_timing
, &default_context_
);
1764 // Proxy times and connect times should all be replaced with request_start.
1765 EXPECT_EQ(load_timing_result
.request_start
,
1766 load_timing_result
.proxy_resolve_start
);
1767 EXPECT_EQ(load_timing_result
.request_start
,
1768 load_timing_result
.proxy_resolve_end
);
1770 // Other times should have been left null.
1771 TestLoadTimingReusedWithProxy(load_timing_result
);
1774 // Make sure that URLRequest correctly adjusts connect times when they're before
1775 // |request_start|, due to reusing a connected socket. The connected socket is
1776 // not considered reused in this test (May be a preconnect).
1778 // To mix things up, the request has SSL times, but no DNS times.
1779 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyConnect
) {
1780 base::TimeTicks now
= base::TimeTicks::Now();
1781 LoadTimingInfo job_load_timing
=
1782 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_SSL_TIMES
, false);
1783 job_load_timing
.connect_timing
.connect_start
=
1784 now
- base::TimeDelta::FromDays(1);
1785 job_load_timing
.connect_timing
.ssl_start
= now
- base::TimeDelta::FromDays(2);
1786 job_load_timing
.connect_timing
.ssl_end
= now
- base::TimeDelta::FromDays(3);
1787 job_load_timing
.connect_timing
.connect_end
=
1788 now
- base::TimeDelta::FromDays(4);
1790 LoadTimingInfo load_timing_result
=
1791 RunLoadTimingTest(job_load_timing
, &default_context_
);
1793 // Connect times, and SSL times should be replaced with request_start.
1794 EXPECT_EQ(load_timing_result
.request_start
,
1795 load_timing_result
.connect_timing
.connect_start
);
1796 EXPECT_EQ(load_timing_result
.request_start
,
1797 load_timing_result
.connect_timing
.ssl_start
);
1798 EXPECT_EQ(load_timing_result
.request_start
,
1799 load_timing_result
.connect_timing
.ssl_end
);
1800 EXPECT_EQ(load_timing_result
.request_start
,
1801 load_timing_result
.connect_timing
.connect_end
);
1803 // Other times should have been left null.
1804 TestLoadTimingNotReused(load_timing_result
, CONNECT_TIMING_HAS_SSL_TIMES
);
1807 // Make sure that URLRequest correctly adjusts connect times when they're before
1808 // |request_start|, due to reusing a connected socket in the case that there
1809 // are also proxy times. The connected socket is not considered reused in this
1810 // test (May be a preconnect).
1812 // In this test, there are no SSL or DNS times.
1813 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyConnectWithProxy
) {
1814 base::TimeTicks now
= base::TimeTicks::Now();
1815 LoadTimingInfo job_load_timing
=
1816 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY
, true);
1817 job_load_timing
.connect_timing
.connect_start
=
1818 now
- base::TimeDelta::FromDays(1);
1819 job_load_timing
.connect_timing
.connect_end
=
1820 now
- base::TimeDelta::FromDays(2);
1822 LoadTimingInfo load_timing_result
=
1823 RunLoadTimingTest(job_load_timing
, &default_context_
);
1825 // Connect times should be replaced with proxy_resolve_end.
1826 EXPECT_EQ(load_timing_result
.proxy_resolve_end
,
1827 load_timing_result
.connect_timing
.connect_start
);
1828 EXPECT_EQ(load_timing_result
.proxy_resolve_end
,
1829 load_timing_result
.connect_timing
.connect_end
);
1831 // Other times should have been left null.
1832 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1833 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY
);
1836 // Check that two different URL requests have different identifiers.
1837 TEST_F(URLRequestTest
, Identifiers
) {
1839 TestURLRequestContext context
;
1841 GURL("http://example.com"), DEFAULT_PRIORITY
, &d
, &context
);
1842 TestURLRequest
other_req(
1843 GURL("http://example.com"), DEFAULT_PRIORITY
, &d
, &context
);
1845 ASSERT_NE(req
.identifier(), other_req
.identifier());
1848 // Check that a failure to connect to the proxy is reported to the network
1850 TEST_F(URLRequestTest
, NetworkDelegateProxyError
) {
1851 MockHostResolver host_resolver
;
1852 host_resolver
.rules()->AddSimulatedFailure("*");
1854 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
1855 TestURLRequestContextWithProxy
context("myproxy:70", &network_delegate
);
1858 URLRequest
req(GURL("http://example.com"), DEFAULT_PRIORITY
, &d
, &context
);
1859 req
.set_method("GET");
1862 base::RunLoop().Run();
1864 // Check we see a failed request.
1865 EXPECT_FALSE(req
.status().is_success());
1866 // The proxy server is not set before failure.
1867 EXPECT_TRUE(req
.proxy_server().IsEmpty());
1868 EXPECT_EQ(URLRequestStatus::FAILED
, req
.status().status());
1869 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED
, req
.status().error());
1871 EXPECT_EQ(1, network_delegate
.error_count());
1872 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED
, network_delegate
.last_error());
1873 EXPECT_EQ(1, network_delegate
.completed_requests());
1876 // Make sure that net::NetworkDelegate::NotifyCompleted is called if
1877 // content is empty.
1878 TEST_F(URLRequestTest
, RequestCompletionForEmptyResponse
) {
1880 URLRequest
req(GURL("data:,"), DEFAULT_PRIORITY
, &d
, &default_context_
);
1882 base::RunLoop().Run();
1883 EXPECT_EQ("", d
.data_received());
1884 EXPECT_EQ(1, default_network_delegate_
.completed_requests());
1887 // Make sure that SetPriority actually sets the URLRequest's priority
1888 // correctly, both before and after start.
1889 TEST_F(URLRequestTest
, SetPriorityBasic
) {
1891 URLRequest
req(GURL("http://test_intercept/foo"),
1895 EXPECT_EQ(DEFAULT_PRIORITY
, req
.priority());
1897 req
.SetPriority(LOW
);
1898 EXPECT_EQ(LOW
, req
.priority());
1901 EXPECT_EQ(LOW
, req
.priority());
1903 req
.SetPriority(MEDIUM
);
1904 EXPECT_EQ(MEDIUM
, req
.priority());
1907 // Make sure that URLRequest calls SetPriority on a job before calling
1909 TEST_F(URLRequestTest
, SetJobPriorityBeforeJobStart
) {
1911 URLRequest
req(GURL("http://test_intercept/foo"),
1915 EXPECT_EQ(DEFAULT_PRIORITY
, req
.priority());
1917 scoped_refptr
<URLRequestTestJob
> job
=
1918 new URLRequestTestJob(&req
, &default_network_delegate_
);
1919 AddTestInterceptor()->set_main_intercept_job(job
.get());
1920 EXPECT_EQ(DEFAULT_PRIORITY
, job
->priority());
1922 req
.SetPriority(LOW
);
1925 EXPECT_EQ(LOW
, job
->priority());
1928 // Make sure that URLRequest passes on its priority updates to its
1930 TEST_F(URLRequestTest
, SetJobPriority
) {
1932 URLRequest
req(GURL("http://test_intercept/foo"),
1937 scoped_refptr
<URLRequestTestJob
> job
=
1938 new URLRequestTestJob(&req
, &default_network_delegate_
);
1939 AddTestInterceptor()->set_main_intercept_job(job
.get());
1941 req
.SetPriority(LOW
);
1943 EXPECT_EQ(LOW
, job
->priority());
1945 req
.SetPriority(MEDIUM
);
1946 EXPECT_EQ(MEDIUM
, req
.priority());
1947 EXPECT_EQ(MEDIUM
, job
->priority());
1950 // Setting the IGNORE_LIMITS load flag should be okay if the priority
1951 // is MAXIMUM_PRIORITY.
1952 TEST_F(URLRequestTest
, PriorityIgnoreLimits
) {
1954 URLRequest
req(GURL("http://test_intercept/foo"),
1958 EXPECT_EQ(MAXIMUM_PRIORITY
, req
.priority());
1960 scoped_refptr
<URLRequestTestJob
> job
=
1961 new URLRequestTestJob(&req
, &default_network_delegate_
);
1962 AddTestInterceptor()->set_main_intercept_job(job
.get());
1964 req
.SetLoadFlags(LOAD_IGNORE_LIMITS
);
1965 EXPECT_EQ(MAXIMUM_PRIORITY
, req
.priority());
1967 req
.SetPriority(MAXIMUM_PRIORITY
);
1968 EXPECT_EQ(MAXIMUM_PRIORITY
, req
.priority());
1971 EXPECT_EQ(MAXIMUM_PRIORITY
, req
.priority());
1972 EXPECT_EQ(MAXIMUM_PRIORITY
, job
->priority());
1975 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1976 #if !defined(OS_IOS)
1977 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
1978 // This is to work around mysterious failures in chrome_frame_net_tests. See:
1979 // http://crbug.com/114369
1980 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1981 class LocalHttpTestServer
: public SpawnedTestServer
{
1983 explicit LocalHttpTestServer(const base::FilePath
& document_root
)
1984 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP
,
1985 ScopedCustomUrlRequestTestHttpHost::value(),
1987 LocalHttpTestServer()
1988 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP
,
1989 ScopedCustomUrlRequestTestHttpHost::value(),
1990 base::FilePath()) {}
1993 TEST_F(URLRequestTest
, DelayedCookieCallback
) {
1994 LocalHttpTestServer test_server
;
1995 ASSERT_TRUE(test_server
.Start());
1997 TestURLRequestContext context
;
1998 scoped_refptr
<DelayedCookieMonster
> delayed_cm
=
1999 new DelayedCookieMonster();
2000 scoped_refptr
<CookieStore
> cookie_store
= delayed_cm
;
2001 context
.set_cookie_store(delayed_cm
.get());
2005 TestNetworkDelegate network_delegate
;
2006 context
.set_network_delegate(&network_delegate
);
2008 URLRequest
req(test_server
.GetURL("set-cookie?CookieToNotSend=1"),
2013 base::RunLoop().Run();
2014 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2015 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2016 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2019 // Verify that the cookie is set.
2021 TestNetworkDelegate network_delegate
;
2022 context
.set_network_delegate(&network_delegate
);
2024 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2029 base::RunLoop().Run();
2031 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2032 != std::string::npos
);
2033 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2034 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2038 TEST_F(URLRequestTest
, DoNotSendCookies
) {
2039 LocalHttpTestServer test_server
;
2040 ASSERT_TRUE(test_server
.Start());
2044 TestNetworkDelegate network_delegate
;
2045 default_context_
.set_network_delegate(&network_delegate
);
2047 URLRequest
req(test_server
.GetURL("set-cookie?CookieToNotSend=1"),
2052 base::RunLoop().Run();
2053 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2054 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2057 // Verify that the cookie is set.
2059 TestNetworkDelegate network_delegate
;
2060 default_context_
.set_network_delegate(&network_delegate
);
2062 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2067 base::RunLoop().Run();
2069 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2070 != std::string::npos
);
2071 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2072 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2075 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2077 TestNetworkDelegate network_delegate
;
2078 default_context_
.set_network_delegate(&network_delegate
);
2080 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2084 req
.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES
);
2086 base::RunLoop().Run();
2088 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2089 == std::string::npos
);
2091 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2092 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2093 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2097 TEST_F(URLRequestTest
, DoNotSaveCookies
) {
2098 LocalHttpTestServer test_server
;
2099 ASSERT_TRUE(test_server
.Start());
2103 TestNetworkDelegate network_delegate
;
2104 default_context_
.set_network_delegate(&network_delegate
);
2106 URLRequest
req(test_server
.GetURL("set-cookie?CookieToNotUpdate=2"),
2111 base::RunLoop().Run();
2113 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2114 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2115 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2118 // Try to set-up another cookie and update the previous cookie.
2120 TestNetworkDelegate network_delegate
;
2121 default_context_
.set_network_delegate(&network_delegate
);
2124 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2128 req
.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES
);
2131 base::RunLoop().Run();
2133 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2134 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2135 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2136 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2139 // Verify the cookies weren't saved or updated.
2141 TestNetworkDelegate network_delegate
;
2142 default_context_
.set_network_delegate(&network_delegate
);
2144 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2149 base::RunLoop().Run();
2151 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2152 == std::string::npos
);
2153 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2154 != std::string::npos
);
2156 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2157 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2158 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2162 TEST_F(URLRequestTest
, DoNotSendCookies_ViaPolicy
) {
2163 LocalHttpTestServer test_server
;
2164 ASSERT_TRUE(test_server
.Start());
2168 TestNetworkDelegate network_delegate
;
2169 default_context_
.set_network_delegate(&network_delegate
);
2171 URLRequest
req(test_server
.GetURL("set-cookie?CookieToNotSend=1"),
2176 base::RunLoop().Run();
2178 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2179 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2182 // Verify that the cookie is set.
2184 TestNetworkDelegate network_delegate
;
2185 default_context_
.set_network_delegate(&network_delegate
);
2187 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2192 base::RunLoop().Run();
2194 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2195 != std::string::npos
);
2197 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2198 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2201 // Verify that the cookie isn't sent.
2203 TestNetworkDelegate network_delegate
;
2204 default_context_
.set_network_delegate(&network_delegate
);
2206 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES
);
2207 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2212 base::RunLoop().Run();
2214 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2215 == std::string::npos
);
2217 EXPECT_EQ(1, network_delegate
.blocked_get_cookies_count());
2218 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2222 TEST_F(URLRequestTest
, DoNotSaveCookies_ViaPolicy
) {
2223 LocalHttpTestServer test_server
;
2224 ASSERT_TRUE(test_server
.Start());
2228 TestNetworkDelegate network_delegate
;
2229 default_context_
.set_network_delegate(&network_delegate
);
2231 URLRequest
req(test_server
.GetURL("set-cookie?CookieToNotUpdate=2"),
2236 base::RunLoop().Run();
2238 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2239 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2242 // Try to set-up another cookie and update the previous cookie.
2244 TestNetworkDelegate network_delegate
;
2245 default_context_
.set_network_delegate(&network_delegate
);
2247 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE
);
2249 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2255 base::RunLoop().Run();
2257 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2258 EXPECT_EQ(2, network_delegate
.blocked_set_cookie_count());
2261 // Verify the cookies weren't saved or updated.
2263 TestNetworkDelegate network_delegate
;
2264 default_context_
.set_network_delegate(&network_delegate
);
2266 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2271 base::RunLoop().Run();
2273 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2274 == std::string::npos
);
2275 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2276 != std::string::npos
);
2278 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2279 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2283 TEST_F(URLRequestTest
, DoNotSaveEmptyCookies
) {
2284 LocalHttpTestServer test_server
;
2285 ASSERT_TRUE(test_server
.Start());
2287 // Set up an empty cookie.
2289 TestNetworkDelegate network_delegate
;
2290 default_context_
.set_network_delegate(&network_delegate
);
2292 URLRequest
req(test_server
.GetURL("set-cookie"),
2297 base::RunLoop().Run();
2299 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2300 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2301 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2305 TEST_F(URLRequestTest
, DoNotSendCookies_ViaPolicy_Async
) {
2306 LocalHttpTestServer test_server
;
2307 ASSERT_TRUE(test_server
.Start());
2311 TestNetworkDelegate network_delegate
;
2312 default_context_
.set_network_delegate(&network_delegate
);
2314 URLRequest
req(test_server
.GetURL("set-cookie?CookieToNotSend=1"),
2319 base::RunLoop().Run();
2321 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2322 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2325 // Verify that the cookie is set.
2327 TestNetworkDelegate network_delegate
;
2328 default_context_
.set_network_delegate(&network_delegate
);
2330 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2335 base::RunLoop().Run();
2337 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2338 != std::string::npos
);
2340 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2341 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2344 // Verify that the cookie isn't sent.
2346 TestNetworkDelegate network_delegate
;
2347 default_context_
.set_network_delegate(&network_delegate
);
2349 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES
);
2350 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2355 base::RunLoop().Run();
2357 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2358 == std::string::npos
);
2360 EXPECT_EQ(1, network_delegate
.blocked_get_cookies_count());
2361 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2365 TEST_F(URLRequestTest
, DoNotSaveCookies_ViaPolicy_Async
) {
2366 LocalHttpTestServer test_server
;
2367 ASSERT_TRUE(test_server
.Start());
2371 TestNetworkDelegate network_delegate
;
2372 default_context_
.set_network_delegate(&network_delegate
);
2374 URLRequest
req(test_server
.GetURL("set-cookie?CookieToNotUpdate=2"),
2379 base::RunLoop().Run();
2381 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2382 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2385 // Try to set-up another cookie and update the previous cookie.
2387 TestNetworkDelegate network_delegate
;
2388 default_context_
.set_network_delegate(&network_delegate
);
2390 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE
);
2392 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2398 base::RunLoop().Run();
2400 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2401 EXPECT_EQ(2, network_delegate
.blocked_set_cookie_count());
2404 // Verify the cookies weren't saved or updated.
2406 TestNetworkDelegate network_delegate
;
2407 default_context_
.set_network_delegate(&network_delegate
);
2409 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
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 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2427 // value for the |fixed_date| argument given to the constructor.
2428 class FixedDateNetworkDelegate
: public TestNetworkDelegate
{
2430 explicit FixedDateNetworkDelegate(const std::string
& fixed_date
)
2431 : fixed_date_(fixed_date
) {}
2432 virtual ~FixedDateNetworkDelegate() {}
2434 // net::NetworkDelegate implementation
2435 virtual int OnHeadersReceived(
2436 net::URLRequest
* request
,
2437 const net::CompletionCallback
& callback
,
2438 const net::HttpResponseHeaders
* original_response_headers
,
2439 scoped_refptr
<net::HttpResponseHeaders
>* override_response_headers
,
2440 GURL
* allowed_unsafe_redirect_url
) OVERRIDE
;
2443 std::string fixed_date_
;
2445 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate
);
2448 int FixedDateNetworkDelegate::OnHeadersReceived(
2449 net::URLRequest
* request
,
2450 const net::CompletionCallback
& callback
,
2451 const net::HttpResponseHeaders
* original_response_headers
,
2452 scoped_refptr
<net::HttpResponseHeaders
>* override_response_headers
,
2453 GURL
* allowed_unsafe_redirect_url
) {
2454 net::HttpResponseHeaders
* new_response_headers
=
2455 new net::HttpResponseHeaders(original_response_headers
->raw_headers());
2457 new_response_headers
->RemoveHeader("Date");
2458 new_response_headers
->AddHeader("Date: " + fixed_date_
);
2460 *override_response_headers
= new_response_headers
;
2461 return TestNetworkDelegate::OnHeadersReceived(request
,
2463 original_response_headers
,
2464 override_response_headers
,
2465 allowed_unsafe_redirect_url
);
2468 // Test that cookie expiration times are adjusted for server/client clock
2469 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2470 // headers by defaulting to GMT. (crbug.com/135131)
2471 TEST_F(URLRequestTest
, AcceptClockSkewCookieWithWrongDateTimezone
) {
2472 LocalHttpTestServer test_server
;
2473 ASSERT_TRUE(test_server
.Start());
2475 // Set up an expired cookie.
2477 TestNetworkDelegate network_delegate
;
2478 default_context_
.set_network_delegate(&network_delegate
);
2482 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2487 base::RunLoop().Run();
2489 // Verify that the cookie is not set.
2491 TestNetworkDelegate network_delegate
;
2492 default_context_
.set_network_delegate(&network_delegate
);
2494 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2499 base::RunLoop().Run();
2501 EXPECT_TRUE(d
.data_received().find("StillGood=1") == std::string::npos
);
2503 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2505 FixedDateNetworkDelegate
network_delegate("18-Apr-1977 22:49:13 UTC");
2506 default_context_
.set_network_delegate(&network_delegate
);
2510 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2515 base::RunLoop().Run();
2517 // Verify that the cookie is set.
2519 TestNetworkDelegate network_delegate
;
2520 default_context_
.set_network_delegate(&network_delegate
);
2522 URLRequest
req(test_server
.GetURL("echoheader?Cookie"),
2527 base::RunLoop().Run();
2529 EXPECT_TRUE(d
.data_received().find("StillGood=1") != std::string::npos
);
2534 // Check that it is impossible to change the referrer in the extra headers of
2536 TEST_F(URLRequestTest
, DoNotOverrideReferrer
) {
2537 LocalHttpTestServer test_server
;
2538 ASSERT_TRUE(test_server
.Start());
2540 // If extra headers contain referer and the request contains a referer,
2541 // only the latter shall be respected.
2544 URLRequest
req(test_server
.GetURL("echoheader?Referer"),
2548 req
.SetReferrer("http://foo.com/");
2550 HttpRequestHeaders headers
;
2551 headers
.SetHeader(HttpRequestHeaders::kReferer
, "http://bar.com/");
2552 req
.SetExtraRequestHeaders(headers
);
2555 base::RunLoop().Run();
2557 EXPECT_EQ("http://foo.com/", d
.data_received());
2560 // If extra headers contain a referer but the request does not, no referer
2561 // shall be sent in the header.
2564 URLRequest
req(test_server
.GetURL("echoheader?Referer"),
2569 HttpRequestHeaders headers
;
2570 headers
.SetHeader(HttpRequestHeaders::kReferer
, "http://bar.com/");
2571 req
.SetExtraRequestHeaders(headers
);
2572 req
.SetLoadFlags(LOAD_VALIDATE_CACHE
);
2575 base::RunLoop().Run();
2577 EXPECT_EQ("None", d
.data_received());
2581 class URLRequestTestHTTP
: public URLRequestTest
{
2583 URLRequestTestHTTP()
2584 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2585 "net/data/url_request_unittest"))) {
2589 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2590 // |request_method| is the method to use for the initial request.
2591 // |redirect_method| is the method that is expected to be used for the second
2592 // request, after redirection.
2593 // If |include_data| is true, data is uploaded with the request. The
2594 // response body is expected to match it exactly, if and only if
2595 // |request_method| == |redirect_method|.
2596 void HTTPRedirectMethodTest(const GURL
& redirect_url
,
2597 const std::string
& request_method
,
2598 const std::string
& redirect_method
,
2599 bool include_data
) {
2600 static const char kData
[] = "hello world";
2602 URLRequest
req(redirect_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
2603 req
.set_method(request_method
);
2605 req
.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
2606 HttpRequestHeaders headers
;
2607 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
2608 base::UintToString(arraysize(kData
) - 1));
2609 req
.SetExtraRequestHeaders(headers
);
2612 base::RunLoop().Run();
2613 EXPECT_EQ(redirect_method
, req
.method());
2614 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
2615 EXPECT_EQ(OK
, req
.status().error());
2617 if (request_method
== redirect_method
) {
2618 EXPECT_EQ(kData
, d
.data_received());
2620 EXPECT_NE(kData
, d
.data_received());
2624 LOG(WARNING
) << "Request method was: " << request_method
;
2627 void HTTPUploadDataOperationTest(const std::string
& method
) {
2628 const int kMsgSize
= 20000; // multiple of 10
2629 const int kIterations
= 50;
2630 char* uploadBytes
= new char[kMsgSize
+1];
2631 char* ptr
= uploadBytes
;
2633 for (int idx
= 0; idx
< kMsgSize
/10; idx
++) {
2634 memcpy(ptr
, "----------", 10);
2636 if (idx
% 100 == 0) {
2643 uploadBytes
[kMsgSize
] = '\0';
2645 for (int i
= 0; i
< kIterations
; ++i
) {
2648 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, &default_context_
);
2649 r
.set_method(method
.c_str());
2651 r
.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes
)));
2654 EXPECT_TRUE(r
.is_pending());
2656 base::RunLoop().Run();
2658 ASSERT_EQ(1, d
.response_started_count())
2659 << "request failed: " << r
.status().status()
2660 << ", os error: " << r
.status().error();
2662 EXPECT_FALSE(d
.received_data_before_response());
2663 EXPECT_EQ(uploadBytes
, d
.data_received());
2665 delete[] uploadBytes
;
2668 void AddChunksToUpload(URLRequest
* r
) {
2669 r
->AppendChunkToUpload("a", 1, false);
2670 r
->AppendChunkToUpload("bcd", 3, false);
2671 r
->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2672 r
->AppendChunkToUpload("\r\n\r\n", 4, false);
2673 r
->AppendChunkToUpload("0", 1, false);
2674 r
->AppendChunkToUpload("2323", 4, true);
2677 void VerifyReceivedDataMatchesChunks(URLRequest
* r
, TestDelegate
* d
) {
2678 // This should match the chunks sent by AddChunksToUpload().
2679 const std::string expected_data
=
2680 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2682 ASSERT_EQ(1, d
->response_started_count())
2683 << "request failed: " << r
->status().status()
2684 << ", os error: " << r
->status().error();
2686 EXPECT_FALSE(d
->received_data_before_response());
2688 EXPECT_EQ(expected_data
.size(), static_cast<size_t>(d
->bytes_received()));
2689 EXPECT_EQ(expected_data
, d
->data_received());
2692 bool DoManyCookiesRequest(int num_cookies
) {
2694 URLRequest
r(test_server_
.GetURL("set-many-cookies?" +
2695 base::IntToString(num_cookies
)),
2701 EXPECT_TRUE(r
.is_pending());
2703 base::RunLoop().Run();
2705 bool is_success
= r
.status().is_success();
2708 EXPECT_TRUE(r
.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG
);
2709 // The test server appears to be unable to handle subsequent requests
2710 // after this error is triggered. Force it to restart.
2711 EXPECT_TRUE(test_server_
.Stop());
2712 EXPECT_TRUE(test_server_
.Start());
2718 LocalHttpTestServer test_server_
;
2721 // In this unit test, we're using the HTTPTestServer as a proxy server and
2722 // issuing a CONNECT request with the magic host name "www.redirect.com".
2723 // The HTTPTestServer will return a 302 response, which we should not
2725 TEST_F(URLRequestTestHTTP
, ProxyTunnelRedirectTest
) {
2726 ASSERT_TRUE(test_server_
.Start());
2728 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
2729 TestURLRequestContextWithProxy
context(
2730 test_server_
.host_port_pair().ToString(), &network_delegate
);
2735 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY
, &d
, &context
);
2737 EXPECT_TRUE(r
.is_pending());
2739 base::RunLoop().Run();
2741 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
2742 // The proxy server is not set before failure.
2743 EXPECT_TRUE(r
.proxy_server().IsEmpty());
2744 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
.status().error());
2745 EXPECT_EQ(1, d
.response_started_count());
2746 // We should not have followed the redirect.
2747 EXPECT_EQ(0, d
.received_redirect_count());
2751 // This is the same as the previous test, but checks that the network delegate
2752 // registers the error.
2753 TEST_F(URLRequestTestHTTP
, NetworkDelegateTunnelConnectionFailed
) {
2754 ASSERT_TRUE(test_server_
.Start());
2756 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
2757 TestURLRequestContextWithProxy
context(
2758 test_server_
.host_port_pair().ToString(), &network_delegate
);
2763 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY
, &d
, &context
);
2765 EXPECT_TRUE(r
.is_pending());
2767 base::RunLoop().Run();
2769 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
2770 // The proxy server is not set before failure.
2771 EXPECT_TRUE(r
.proxy_server().IsEmpty());
2772 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
.status().error());
2773 EXPECT_EQ(1, d
.response_started_count());
2774 // We should not have followed the redirect.
2775 EXPECT_EQ(0, d
.received_redirect_count());
2777 EXPECT_EQ(1, network_delegate
.error_count());
2778 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, network_delegate
.last_error());
2782 // Tests that we can block and asynchronously return OK in various stages.
2783 TEST_F(URLRequestTestHTTP
, NetworkDelegateBlockAsynchronously
) {
2784 static const BlockingNetworkDelegate::Stage blocking_stages
[] = {
2785 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
2786 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
2787 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2789 static const size_t blocking_stages_length
= arraysize(blocking_stages
);
2791 ASSERT_TRUE(test_server_
.Start());
2794 BlockingNetworkDelegate
network_delegate(
2795 BlockingNetworkDelegate::USER_CALLBACK
);
2796 network_delegate
.set_block_on(
2797 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
|
2798 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
|
2799 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
2801 TestURLRequestContext
context(true);
2802 context
.set_network_delegate(&network_delegate
);
2807 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
, &context
);
2810 for (size_t i
= 0; i
< blocking_stages_length
; ++i
) {
2811 base::RunLoop().Run();
2812 EXPECT_EQ(blocking_stages
[i
],
2813 network_delegate
.stage_blocked_for_callback());
2814 network_delegate
.DoCallback(OK
);
2816 base::RunLoop().Run();
2817 EXPECT_EQ(200, r
.GetResponseCode());
2818 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
2819 EXPECT_EQ(1, network_delegate
.created_requests());
2820 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2822 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2825 // Tests that the network delegate can block and cancel a request.
2826 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequest
) {
2827 ASSERT_TRUE(test_server_
.Start());
2830 BlockingNetworkDelegate
network_delegate(
2831 BlockingNetworkDelegate::AUTO_CALLBACK
);
2832 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
2833 network_delegate
.set_retval(ERR_EMPTY_RESPONSE
);
2835 TestURLRequestContextWithProxy
context(
2836 test_server_
.host_port_pair().ToString(), &network_delegate
);
2840 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context
);
2843 base::RunLoop().Run();
2845 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
2846 // The proxy server is not set before cancellation.
2847 EXPECT_TRUE(r
.proxy_server().IsEmpty());
2848 EXPECT_EQ(ERR_EMPTY_RESPONSE
, r
.status().error());
2849 EXPECT_EQ(1, network_delegate
.created_requests());
2850 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2852 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2855 // Helper function for NetworkDelegateCancelRequestAsynchronously and
2856 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2857 // delegate operating in |block_mode| and a request for |url|. It blocks the
2858 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2859 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode
,
2860 BlockingNetworkDelegate::Stage stage
,
2863 BlockingNetworkDelegate
network_delegate(block_mode
);
2864 network_delegate
.set_retval(ERR_BLOCKED_BY_CLIENT
);
2865 network_delegate
.set_block_on(stage
);
2867 TestURLRequestContext
context(true);
2868 context
.set_network_delegate(&network_delegate
);
2872 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
2875 base::RunLoop().Run();
2877 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
2878 // The proxy server is not set before cancellation.
2879 EXPECT_TRUE(r
.proxy_server().IsEmpty());
2880 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT
, r
.status().error());
2881 EXPECT_EQ(1, network_delegate
.created_requests());
2882 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2884 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2887 // The following 3 tests check that the network delegate can cancel a request
2888 // synchronously in various stages of the request.
2889 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously1
) {
2890 ASSERT_TRUE(test_server_
.Start());
2891 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
2892 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
2893 test_server_
.GetURL(std::string()));
2896 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously2
) {
2897 ASSERT_TRUE(test_server_
.Start());
2898 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
2899 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
2900 test_server_
.GetURL(std::string()));
2903 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously3
) {
2904 ASSERT_TRUE(test_server_
.Start());
2905 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
2906 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
2907 test_server_
.GetURL(std::string()));
2910 // The following 3 tests check that the network delegate can cancel a request
2911 // asynchronously in various stages of the request.
2912 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously1
) {
2913 ASSERT_TRUE(test_server_
.Start());
2914 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
2915 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
2916 test_server_
.GetURL(std::string()));
2919 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously2
) {
2920 ASSERT_TRUE(test_server_
.Start());
2921 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
2922 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
2923 test_server_
.GetURL(std::string()));
2926 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously3
) {
2927 ASSERT_TRUE(test_server_
.Start());
2928 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
2929 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
2930 test_server_
.GetURL(std::string()));
2933 // Tests that the network delegate can block and redirect a request to a new
2935 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequest
) {
2936 ASSERT_TRUE(test_server_
.Start());
2939 BlockingNetworkDelegate
network_delegate(
2940 BlockingNetworkDelegate::AUTO_CALLBACK
);
2941 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
2942 GURL
redirect_url(test_server_
.GetURL("simple.html"));
2943 network_delegate
.set_redirect_url(redirect_url
);
2945 TestURLRequestContextWithProxy
context(
2946 test_server_
.host_port_pair().ToString(), &network_delegate
);
2949 GURL
original_url(test_server_
.GetURL("empty.html"));
2950 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &context
);
2953 base::RunLoop().Run();
2955 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
2956 EXPECT_TRUE(r
.proxy_server().Equals(test_server_
.host_port_pair()));
2958 1, network_delegate
.observed_before_proxy_headers_sent_callbacks());
2960 network_delegate
.last_observed_proxy().Equals(
2961 test_server_
.host_port_pair()));
2963 EXPECT_EQ(0, r
.status().error());
2964 EXPECT_EQ(redirect_url
, r
.url());
2965 EXPECT_EQ(original_url
, r
.original_url());
2966 EXPECT_EQ(2U, r
.url_chain().size());
2967 EXPECT_EQ(1, network_delegate
.created_requests());
2968 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2970 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2973 // Tests that the network delegate can block and redirect a request to a new
2974 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2975 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestSynchronously
) {
2976 ASSERT_TRUE(test_server_
.Start());
2979 BlockingNetworkDelegate
network_delegate(
2980 BlockingNetworkDelegate::SYNCHRONOUS
);
2981 GURL
redirect_url(test_server_
.GetURL("simple.html"));
2982 network_delegate
.set_redirect_url(redirect_url
);
2984 TestURLRequestContextWithProxy
context(
2985 test_server_
.host_port_pair().ToString(), &network_delegate
);
2988 GURL
original_url(test_server_
.GetURL("empty.html"));
2989 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &context
);
2992 base::RunLoop().Run();
2994 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
2995 EXPECT_TRUE(r
.proxy_server().Equals(test_server_
.host_port_pair()));
2997 1, network_delegate
.observed_before_proxy_headers_sent_callbacks());
2999 network_delegate
.last_observed_proxy().Equals(
3000 test_server_
.host_port_pair()));
3001 EXPECT_EQ(0, r
.status().error());
3002 EXPECT_EQ(redirect_url
, r
.url());
3003 EXPECT_EQ(original_url
, r
.original_url());
3004 EXPECT_EQ(2U, r
.url_chain().size());
3005 EXPECT_EQ(1, network_delegate
.created_requests());
3006 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3008 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3011 // Tests that redirects caused by the network delegate preserve POST data.
3012 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestPost
) {
3013 ASSERT_TRUE(test_server_
.Start());
3015 const char kData
[] = "hello world";
3018 BlockingNetworkDelegate
network_delegate(
3019 BlockingNetworkDelegate::AUTO_CALLBACK
);
3020 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3021 GURL
redirect_url(test_server_
.GetURL("echo"));
3022 network_delegate
.set_redirect_url(redirect_url
);
3024 TestURLRequestContext
context(true);
3025 context
.set_network_delegate(&network_delegate
);
3029 GURL
original_url(test_server_
.GetURL("empty.html"));
3030 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &context
);
3031 r
.set_method("POST");
3032 r
.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
3033 HttpRequestHeaders headers
;
3034 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
3035 base::UintToString(arraysize(kData
) - 1));
3036 r
.SetExtraRequestHeaders(headers
);
3038 base::RunLoop().Run();
3040 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3041 EXPECT_EQ(0, r
.status().error());
3042 EXPECT_EQ(redirect_url
, r
.url());
3043 EXPECT_EQ(original_url
, r
.original_url());
3044 EXPECT_EQ(2U, r
.url_chain().size());
3045 EXPECT_EQ(1, network_delegate
.created_requests());
3046 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3047 EXPECT_EQ("POST", r
.method());
3048 EXPECT_EQ(kData
, d
.data_received());
3050 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3053 // Tests that the network delegate can block and redirect a request to a new
3054 // URL during OnHeadersReceived.
3055 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestOnHeadersReceived
) {
3056 ASSERT_TRUE(test_server_
.Start());
3059 BlockingNetworkDelegate
network_delegate(
3060 BlockingNetworkDelegate::AUTO_CALLBACK
);
3061 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
3062 GURL
redirect_url(test_server_
.GetURL("simple.html"));
3063 network_delegate
.set_redirect_on_headers_received_url(redirect_url
);
3065 TestURLRequestContextWithProxy
context(
3066 test_server_
.host_port_pair().ToString(), &network_delegate
);
3069 GURL
original_url(test_server_
.GetURL("empty.html"));
3070 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &context
);
3073 base::RunLoop().Run();
3075 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3076 EXPECT_TRUE(r
.proxy_server().Equals(test_server_
.host_port_pair()));
3078 2, network_delegate
.observed_before_proxy_headers_sent_callbacks());
3080 network_delegate
.last_observed_proxy().Equals(
3081 test_server_
.host_port_pair()));
3082 EXPECT_EQ(net::OK
, r
.status().error());
3083 EXPECT_EQ(redirect_url
, r
.url());
3084 EXPECT_EQ(original_url
, r
.original_url());
3085 EXPECT_EQ(2U, r
.url_chain().size());
3086 EXPECT_EQ(2, network_delegate
.created_requests());
3087 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3089 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3092 // Tests that the network delegate can synchronously complete OnAuthRequired
3093 // by taking no action. This indicates that the NetworkDelegate does not want to
3094 // handle the challenge, and is passing the buck along to the
3095 // URLRequest::Delegate.
3096 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncNoAction
) {
3097 ASSERT_TRUE(test_server_
.Start());
3100 BlockingNetworkDelegate
network_delegate(
3101 BlockingNetworkDelegate::SYNCHRONOUS
);
3103 TestURLRequestContext
context(true);
3104 context
.set_network_delegate(&network_delegate
);
3107 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3110 GURL
url(test_server_
.GetURL("auth-basic"));
3111 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3114 base::RunLoop().Run();
3116 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3117 EXPECT_EQ(0, r
.status().error());
3118 EXPECT_EQ(200, r
.GetResponseCode());
3119 EXPECT_TRUE(d
.auth_required_called());
3120 EXPECT_EQ(1, network_delegate
.created_requests());
3121 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3123 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3126 TEST_F(URLRequestTestHTTP
,
3127 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders
) {
3128 ASSERT_TRUE(test_server_
.Start());
3131 BlockingNetworkDelegate
network_delegate(
3132 BlockingNetworkDelegate::SYNCHRONOUS
);
3134 TestURLRequestContext
context(true);
3135 context
.set_network_delegate(&network_delegate
);
3138 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3141 GURL
url(test_server_
.GetURL("auth-basic"));
3142 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3146 HttpRequestHeaders headers
;
3147 EXPECT_TRUE(r
.GetFullRequestHeaders(&headers
));
3148 EXPECT_FALSE(headers
.HasHeader("Authorization"));
3151 base::RunLoop().Run();
3153 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3154 EXPECT_EQ(0, r
.status().error());
3155 EXPECT_EQ(200, r
.GetResponseCode());
3156 EXPECT_TRUE(d
.auth_required_called());
3157 EXPECT_EQ(1, network_delegate
.created_requests());
3158 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3160 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3163 // Tests that the network delegate can synchronously complete OnAuthRequired
3164 // by setting credentials.
3165 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncSetAuth
) {
3166 ASSERT_TRUE(test_server_
.Start());
3169 BlockingNetworkDelegate
network_delegate(
3170 BlockingNetworkDelegate::SYNCHRONOUS
);
3171 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3172 network_delegate
.set_auth_retval(
3173 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3175 network_delegate
.set_auth_credentials(AuthCredentials(kUser
, kSecret
));
3177 TestURLRequestContext
context(true);
3178 context
.set_network_delegate(&network_delegate
);
3182 GURL
url(test_server_
.GetURL("auth-basic"));
3183 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3185 base::RunLoop().Run();
3187 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3188 EXPECT_EQ(0, r
.status().error());
3189 EXPECT_EQ(200, r
.GetResponseCode());
3190 EXPECT_FALSE(d
.auth_required_called());
3191 EXPECT_EQ(1, network_delegate
.created_requests());
3192 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3194 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3197 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3198 // headers (for the first or second request) when called at the proper times.
3199 TEST_F(URLRequestTestHTTP
,
3200 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders
) {
3201 ASSERT_TRUE(test_server_
.Start());
3204 BlockingNetworkDelegate
network_delegate(
3205 BlockingNetworkDelegate::SYNCHRONOUS
);
3206 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3207 network_delegate
.set_auth_retval(
3208 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3210 network_delegate
.set_auth_credentials(AuthCredentials(kUser
, kSecret
));
3212 TestURLRequestContext
context(true);
3213 context
.set_network_delegate(&network_delegate
);
3217 GURL
url(test_server_
.GetURL("auth-basic"));
3218 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3220 base::RunLoop().Run();
3222 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3223 EXPECT_EQ(0, r
.status().error());
3224 EXPECT_EQ(200, r
.GetResponseCode());
3225 EXPECT_FALSE(d
.auth_required_called());
3226 EXPECT_EQ(1, network_delegate
.created_requests());
3227 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3230 HttpRequestHeaders headers
;
3231 EXPECT_TRUE(r
.GetFullRequestHeaders(&headers
));
3232 EXPECT_TRUE(headers
.HasHeader("Authorization"));
3235 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3238 // Tests that the network delegate can synchronously complete OnAuthRequired
3239 // by cancelling authentication.
3240 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncCancel
) {
3241 ASSERT_TRUE(test_server_
.Start());
3244 BlockingNetworkDelegate
network_delegate(
3245 BlockingNetworkDelegate::SYNCHRONOUS
);
3246 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3247 network_delegate
.set_auth_retval(
3248 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH
);
3250 TestURLRequestContext
context(true);
3251 context
.set_network_delegate(&network_delegate
);
3255 GURL
url(test_server_
.GetURL("auth-basic"));
3256 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3258 base::RunLoop().Run();
3260 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3261 EXPECT_EQ(OK
, r
.status().error());
3262 EXPECT_EQ(401, r
.GetResponseCode());
3263 EXPECT_FALSE(d
.auth_required_called());
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 asynchronously complete OnAuthRequired
3271 // by taking no action. This indicates that the NetworkDelegate does not want
3272 // to handle the challenge, and is passing the buck along to the
3273 // URLRequest::Delegate.
3274 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncNoAction
) {
3275 ASSERT_TRUE(test_server_
.Start());
3278 BlockingNetworkDelegate
network_delegate(
3279 BlockingNetworkDelegate::AUTO_CALLBACK
);
3280 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3282 TestURLRequestContext
context(true);
3283 context
.set_network_delegate(&network_delegate
);
3286 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3289 GURL
url(test_server_
.GetURL("auth-basic"));
3290 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3292 base::RunLoop().Run();
3294 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3295 EXPECT_EQ(0, r
.status().error());
3296 EXPECT_EQ(200, r
.GetResponseCode());
3297 EXPECT_TRUE(d
.auth_required_called());
3298 EXPECT_EQ(1, network_delegate
.created_requests());
3299 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3301 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3304 // Tests that the network delegate can asynchronously complete OnAuthRequired
3305 // by setting credentials.
3306 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncSetAuth
) {
3307 ASSERT_TRUE(test_server_
.Start());
3310 BlockingNetworkDelegate
network_delegate(
3311 BlockingNetworkDelegate::AUTO_CALLBACK
);
3312 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3313 network_delegate
.set_auth_retval(
3314 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3316 AuthCredentials
auth_credentials(kUser
, kSecret
);
3317 network_delegate
.set_auth_credentials(auth_credentials
);
3319 TestURLRequestContext
context(true);
3320 context
.set_network_delegate(&network_delegate
);
3324 GURL
url(test_server_
.GetURL("auth-basic"));
3325 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3327 base::RunLoop().Run();
3329 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3330 EXPECT_EQ(0, r
.status().error());
3332 EXPECT_EQ(200, r
.GetResponseCode());
3333 EXPECT_FALSE(d
.auth_required_called());
3334 EXPECT_EQ(1, network_delegate
.created_requests());
3335 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3337 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3340 // Tests that the network delegate can asynchronously complete OnAuthRequired
3341 // by cancelling authentication.
3342 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncCancel
) {
3343 ASSERT_TRUE(test_server_
.Start());
3346 BlockingNetworkDelegate
network_delegate(
3347 BlockingNetworkDelegate::AUTO_CALLBACK
);
3348 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3349 network_delegate
.set_auth_retval(
3350 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH
);
3352 TestURLRequestContext
context(true);
3353 context
.set_network_delegate(&network_delegate
);
3357 GURL
url(test_server_
.GetURL("auth-basic"));
3358 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &context
);
3360 base::RunLoop().Run();
3362 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
3363 EXPECT_EQ(OK
, r
.status().error());
3364 EXPECT_EQ(401, r
.GetResponseCode());
3365 EXPECT_FALSE(d
.auth_required_called());
3366 EXPECT_EQ(1, network_delegate
.created_requests());
3367 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3369 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3372 // Tests that we can handle when a network request was canceled while we were
3373 // waiting for the network delegate.
3374 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3375 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting1
) {
3376 ASSERT_TRUE(test_server_
.Start());
3379 BlockingNetworkDelegate
network_delegate(
3380 BlockingNetworkDelegate::USER_CALLBACK
);
3381 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3383 TestURLRequestContext
context(true);
3384 context
.set_network_delegate(&network_delegate
);
3389 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context
);
3392 base::RunLoop().Run();
3393 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
3394 network_delegate
.stage_blocked_for_callback());
3395 EXPECT_EQ(0, network_delegate
.completed_requests());
3396 // Cancel before callback.
3398 // Ensure that network delegate is notified.
3399 EXPECT_EQ(1, network_delegate
.completed_requests());
3400 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
3401 EXPECT_EQ(ERR_ABORTED
, r
.status().error());
3402 EXPECT_EQ(1, network_delegate
.created_requests());
3403 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3405 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3408 // Tests that we can handle when a network request was canceled while we were
3409 // waiting for the network delegate.
3410 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3411 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting2
) {
3412 ASSERT_TRUE(test_server_
.Start());
3415 BlockingNetworkDelegate
network_delegate(
3416 BlockingNetworkDelegate::USER_CALLBACK
);
3417 network_delegate
.set_block_on(
3418 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
);
3420 TestURLRequestContext
context(true);
3421 context
.set_network_delegate(&network_delegate
);
3426 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context
);
3429 base::RunLoop().Run();
3430 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
3431 network_delegate
.stage_blocked_for_callback());
3432 EXPECT_EQ(0, network_delegate
.completed_requests());
3433 // Cancel before callback.
3435 // Ensure that network delegate is notified.
3436 EXPECT_EQ(1, network_delegate
.completed_requests());
3437 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
3438 EXPECT_EQ(ERR_ABORTED
, r
.status().error());
3439 EXPECT_EQ(1, network_delegate
.created_requests());
3440 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3442 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3445 // Tests that we can handle when a network request was canceled while we were
3446 // waiting for the network delegate.
3447 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3448 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting3
) {
3449 ASSERT_TRUE(test_server_
.Start());
3452 BlockingNetworkDelegate
network_delegate(
3453 BlockingNetworkDelegate::USER_CALLBACK
);
3454 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
3456 TestURLRequestContext
context(true);
3457 context
.set_network_delegate(&network_delegate
);
3462 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context
);
3465 base::RunLoop().Run();
3466 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
3467 network_delegate
.stage_blocked_for_callback());
3468 EXPECT_EQ(0, network_delegate
.completed_requests());
3469 // Cancel before callback.
3471 // Ensure that network delegate is notified.
3472 EXPECT_EQ(1, network_delegate
.completed_requests());
3473 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
3474 EXPECT_EQ(ERR_ABORTED
, r
.status().error());
3475 EXPECT_EQ(1, network_delegate
.created_requests());
3476 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3478 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3481 // Tests that we can handle when a network request was canceled while we were
3482 // waiting for the network delegate.
3483 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3484 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting4
) {
3485 ASSERT_TRUE(test_server_
.Start());
3488 BlockingNetworkDelegate
network_delegate(
3489 BlockingNetworkDelegate::USER_CALLBACK
);
3490 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3492 TestURLRequestContext
context(true);
3493 context
.set_network_delegate(&network_delegate
);
3498 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
, &context
);
3501 base::RunLoop().Run();
3502 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED
,
3503 network_delegate
.stage_blocked_for_callback());
3504 EXPECT_EQ(0, network_delegate
.completed_requests());
3505 // Cancel before callback.
3507 // Ensure that network delegate is notified.
3508 EXPECT_EQ(1, network_delegate
.completed_requests());
3509 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
3510 EXPECT_EQ(ERR_ABORTED
, r
.status().error());
3511 EXPECT_EQ(1, network_delegate
.created_requests());
3512 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3514 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3517 // In this unit test, we're using the HTTPTestServer as a proxy server and
3518 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3519 // The HTTPTestServer will return a 401 response, which we should balk at.
3520 TEST_F(URLRequestTestHTTP
, UnexpectedServerAuthTest
) {
3521 ASSERT_TRUE(test_server_
.Start());
3523 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
3524 TestURLRequestContextWithProxy
context(
3525 test_server_
.host_port_pair().ToString(), &network_delegate
);
3530 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY
, &d
, &context
);
3533 EXPECT_TRUE(r
.is_pending());
3535 base::RunLoop().Run();
3537 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
3538 // The proxy server is not set before failure.
3539 EXPECT_TRUE(r
.proxy_server().IsEmpty());
3540 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
.status().error());
3544 TEST_F(URLRequestTestHTTP
, GetTest_NoCache
) {
3545 ASSERT_TRUE(test_server_
.Start());
3549 URLRequest
r(test_server_
.GetURL(std::string()),
3555 EXPECT_TRUE(r
.is_pending());
3557 base::RunLoop().Run();
3559 EXPECT_EQ(1, d
.response_started_count());
3560 EXPECT_FALSE(d
.received_data_before_response());
3561 EXPECT_NE(0, d
.bytes_received());
3562 EXPECT_EQ(test_server_
.host_port_pair().host(),
3563 r
.GetSocketAddress().host());
3564 EXPECT_EQ(test_server_
.host_port_pair().port(),
3565 r
.GetSocketAddress().port());
3567 // TODO(eroman): Add back the NetLog tests...
3571 // This test has the server send a large number of cookies to the client.
3572 // To ensure that no number of cookies causes a crash, a galloping binary
3573 // search is used to estimate that maximum number of cookies that are accepted
3574 // by the browser. Beyond the maximum number, the request will fail with
3575 // ERR_RESPONSE_HEADERS_TOO_BIG.
3577 // http://crbug.com/177916
3578 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3580 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3581 #endif // defined(OS_WIN)
3582 TEST_F(URLRequestTestHTTP
, MAYBE_GetTest_ManyCookies
) {
3583 ASSERT_TRUE(test_server_
.Start());
3585 int lower_bound
= 0;
3586 int upper_bound
= 1;
3588 // Double the number of cookies until the response header limits are
3590 while (DoManyCookiesRequest(upper_bound
)) {
3591 lower_bound
= upper_bound
;
3593 ASSERT_LT(upper_bound
, 1000000);
3596 int tolerance
= upper_bound
* 0.005;
3600 // Perform a binary search to find the highest possible number of cookies,
3601 // within the desired tolerance.
3602 while (upper_bound
- lower_bound
>= tolerance
) {
3603 int num_cookies
= (lower_bound
+ upper_bound
) / 2;
3605 if (DoManyCookiesRequest(num_cookies
))
3606 lower_bound
= num_cookies
;
3608 upper_bound
= num_cookies
;
3610 // Success: the test did not crash.
3613 TEST_F(URLRequestTestHTTP
, GetTest
) {
3614 ASSERT_TRUE(test_server_
.Start());
3618 URLRequest
r(test_server_
.GetURL(std::string()),
3624 EXPECT_TRUE(r
.is_pending());
3626 base::RunLoop().Run();
3628 EXPECT_EQ(1, d
.response_started_count());
3629 EXPECT_FALSE(d
.received_data_before_response());
3630 EXPECT_NE(0, d
.bytes_received());
3631 EXPECT_EQ(test_server_
.host_port_pair().host(),
3632 r
.GetSocketAddress().host());
3633 EXPECT_EQ(test_server_
.host_port_pair().port(),
3634 r
.GetSocketAddress().port());
3638 TEST_F(URLRequestTestHTTP
, GetTest_GetFullRequestHeaders
) {
3639 ASSERT_TRUE(test_server_
.Start());
3643 GURL
test_url(test_server_
.GetURL(std::string()));
3644 URLRequest
r(test_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
3646 HttpRequestHeaders headers
;
3647 EXPECT_FALSE(r
.GetFullRequestHeaders(&headers
));
3650 EXPECT_TRUE(r
.is_pending());
3652 base::RunLoop().Run();
3654 EXPECT_EQ(1, d
.response_started_count());
3655 EXPECT_FALSE(d
.received_data_before_response());
3656 EXPECT_NE(0, d
.bytes_received());
3657 EXPECT_EQ(test_server_
.host_port_pair().host(),
3658 r
.GetSocketAddress().host());
3659 EXPECT_EQ(test_server_
.host_port_pair().port(),
3660 r
.GetSocketAddress().port());
3662 EXPECT_TRUE(d
.have_full_request_headers());
3663 CheckFullRequestHeaders(d
.full_request_headers(), test_url
);
3667 TEST_F(URLRequestTestHTTP
, GetTestLoadTiming
) {
3668 ASSERT_TRUE(test_server_
.Start());
3672 URLRequest
r(test_server_
.GetURL(std::string()),
3678 EXPECT_TRUE(r
.is_pending());
3680 base::RunLoop().Run();
3682 LoadTimingInfo load_timing_info
;
3683 r
.GetLoadTimingInfo(&load_timing_info
);
3684 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
3686 EXPECT_EQ(1, d
.response_started_count());
3687 EXPECT_FALSE(d
.received_data_before_response());
3688 EXPECT_NE(0, d
.bytes_received());
3689 EXPECT_EQ(test_server_
.host_port_pair().host(),
3690 r
.GetSocketAddress().host());
3691 EXPECT_EQ(test_server_
.host_port_pair().port(),
3692 r
.GetSocketAddress().port());
3696 TEST_F(URLRequestTestHTTP
, GetZippedTest
) {
3697 ASSERT_TRUE(test_server_
.Start());
3699 // Parameter that specifies the Content-Length field in the response:
3700 // C - Compressed length.
3701 // U - Uncompressed length.
3702 // L - Large length (larger than both C & U).
3703 // M - Medium length (between C & U).
3704 // S - Small length (smaller than both C & U).
3705 const char test_parameters
[] = "CULMS";
3706 const int num_tests
= arraysize(test_parameters
)- 1; // Skip NULL.
3707 // C & U should be OK.
3708 // L & M are larger than the data sent, and show an error.
3709 // S has too little data, but we seem to accept it.
3710 const bool test_expect_success
[num_tests
] =
3711 { true, true, false, false, true };
3713 for (int i
= 0; i
< num_tests
; i
++) {
3716 std::string test_file
=
3717 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3718 test_parameters
[i
]);
3720 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
3721 TestURLRequestContext
context(true);
3722 context
.set_network_delegate(&network_delegate
);
3726 test_server_
.GetURL(test_file
), DEFAULT_PRIORITY
, &d
, &context
);
3728 EXPECT_TRUE(r
.is_pending());
3730 base::RunLoop().Run();
3732 EXPECT_EQ(1, d
.response_started_count());
3733 EXPECT_FALSE(d
.received_data_before_response());
3734 VLOG(1) << " Received " << d
.bytes_received() << " bytes"
3735 << " status = " << r
.status().status()
3736 << " error = " << r
.status().error();
3737 if (test_expect_success
[i
]) {
3738 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status())
3739 << " Parameter = \"" << test_file
<< "\"";
3741 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
3742 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH
, r
.status().error())
3743 << " Parameter = \"" << test_file
<< "\"";
3749 TEST_F(URLRequestTestHTTP
, HTTPSToHTTPRedirectNoRefererTest
) {
3750 ASSERT_TRUE(test_server_
.Start());
3752 SpawnedTestServer
https_test_server(
3753 SpawnedTestServer::TYPE_HTTPS
, SpawnedTestServer::kLocalhost
,
3754 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3755 ASSERT_TRUE(https_test_server
.Start());
3757 // An https server is sent a request with an https referer,
3758 // and responds with a redirect to an http url. The http
3759 // server should not be sent the referer.
3760 GURL http_destination
= test_server_
.GetURL(std::string());
3763 https_test_server
.GetURL("server-redirect?" + http_destination
.spec()),
3767 req
.SetReferrer("https://www.referrer.com/");
3769 base::RunLoop().Run();
3771 EXPECT_EQ(1, d
.response_started_count());
3772 EXPECT_EQ(1, d
.received_redirect_count());
3773 EXPECT_EQ(http_destination
, req
.url());
3774 EXPECT_EQ(std::string(), req
.referrer());
3777 TEST_F(URLRequestTestHTTP
, RedirectLoadTiming
) {
3778 ASSERT_TRUE(test_server_
.Start());
3780 GURL destination_url
= test_server_
.GetURL(std::string());
3782 test_server_
.GetURL("server-redirect?" + destination_url
.spec());
3784 URLRequest
req(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
3786 base::RunLoop().Run();
3788 EXPECT_EQ(1, d
.response_started_count());
3789 EXPECT_EQ(1, d
.received_redirect_count());
3790 EXPECT_EQ(destination_url
, req
.url());
3791 EXPECT_EQ(original_url
, req
.original_url());
3792 ASSERT_EQ(2U, req
.url_chain().size());
3793 EXPECT_EQ(original_url
, req
.url_chain()[0]);
3794 EXPECT_EQ(destination_url
, req
.url_chain()[1]);
3796 LoadTimingInfo load_timing_info_before_redirect
;
3797 EXPECT_TRUE(default_network_delegate_
.GetLoadTimingInfoBeforeRedirect(
3798 &load_timing_info_before_redirect
));
3799 TestLoadTimingNotReused(load_timing_info_before_redirect
,
3800 CONNECT_TIMING_HAS_DNS_TIMES
);
3802 LoadTimingInfo load_timing_info
;
3803 req
.GetLoadTimingInfo(&load_timing_info
);
3804 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
3806 // Check that a new socket was used on redirect, since the server does not
3807 // supposed keep-alive sockets, and that the times before the redirect are
3808 // before the ones recorded for the second request.
3809 EXPECT_NE(load_timing_info_before_redirect
.socket_log_id
,
3810 load_timing_info
.socket_log_id
);
3811 EXPECT_LE(load_timing_info_before_redirect
.receive_headers_end
,
3812 load_timing_info
.connect_timing
.connect_start
);
3815 TEST_F(URLRequestTestHTTP
, MultipleRedirectTest
) {
3816 ASSERT_TRUE(test_server_
.Start());
3818 GURL destination_url
= test_server_
.GetURL(std::string());
3819 GURL middle_redirect_url
=
3820 test_server_
.GetURL("server-redirect?" + destination_url
.spec());
3821 GURL original_url
= test_server_
.GetURL(
3822 "server-redirect?" + middle_redirect_url
.spec());
3824 URLRequest
req(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
3826 base::RunLoop().Run();
3828 EXPECT_EQ(1, d
.response_started_count());
3829 EXPECT_EQ(2, d
.received_redirect_count());
3830 EXPECT_EQ(destination_url
, req
.url());
3831 EXPECT_EQ(original_url
, req
.original_url());
3832 ASSERT_EQ(3U, req
.url_chain().size());
3833 EXPECT_EQ(original_url
, req
.url_chain()[0]);
3834 EXPECT_EQ(middle_redirect_url
, req
.url_chain()[1]);
3835 EXPECT_EQ(destination_url
, req
.url_chain()[2]);
3838 // First and second pieces of information logged by delegates to URLRequests.
3839 const char kFirstDelegateInfo
[] = "Wonderful delegate";
3840 const char kSecondDelegateInfo
[] = "Exciting delegate";
3842 // Logs delegate information to a URLRequest. The first string is logged
3843 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3844 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3845 // another asynchronous call is used to clear the delegate information
3846 // before calling a callback. The object then deletes itself.
3847 class AsyncDelegateLogger
: public base::RefCounted
<AsyncDelegateLogger
> {
3849 typedef base::Callback
<void()> Callback
;
3851 // Each time delegate information is added to the URLRequest, the resulting
3852 // load state is checked. The expected load state after each request is
3853 // passed in as an argument.
3854 static void Run(URLRequest
* url_request
,
3855 LoadState expected_first_load_state
,
3856 LoadState expected_second_load_state
,
3857 LoadState expected_third_load_state
,
3858 const Callback
& callback
) {
3859 AsyncDelegateLogger
* logger
= new AsyncDelegateLogger(
3861 expected_first_load_state
,
3862 expected_second_load_state
,
3863 expected_third_load_state
,
3868 // Checks that the log entries, starting with log_position, contain the
3869 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3870 // recorded. Returns the index of entry after the expected number of
3871 // events this logged, or entries.size() if there aren't enough entries.
3872 static size_t CheckDelegateInfo(
3873 const CapturingNetLog::CapturedEntryList
& entries
, size_t log_position
) {
3874 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3875 if (log_position
+ 3 >= entries
.size()) {
3876 ADD_FAILURE() << "Not enough log entries";
3877 return entries
.size();
3879 std::string delegate_info
;
3880 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3881 EXPECT_EQ(NetLog::PHASE_BEGIN
, entries
[log_position
].phase
);
3882 EXPECT_TRUE(entries
[log_position
].GetStringValue("delegate_info",
3884 EXPECT_EQ(kFirstDelegateInfo
, delegate_info
);
3887 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3888 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
3891 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3892 EXPECT_EQ(NetLog::PHASE_BEGIN
, entries
[log_position
].phase
);
3893 EXPECT_TRUE(entries
[log_position
].GetStringValue("delegate_info",
3895 EXPECT_EQ(kSecondDelegateInfo
, delegate_info
);
3898 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3899 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
3901 return log_position
+ 1;
3904 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3905 // Returns the position of the end message.
3906 static size_t ExpectBeforeNetworkEvents(
3907 const CapturingNetLog::CapturedEntryList
& entries
,
3908 size_t log_position
) {
3910 ExpectLogContainsSomewhereAfter(entries
,
3912 NetLog::TYPE_URL_REQUEST_DELEGATE
,
3913 NetLog::PHASE_BEGIN
);
3914 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
,
3915 entries
[log_position
+ 1].type
);
3916 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
+ 1].phase
);
3917 return log_position
+ 1;
3921 friend class base::RefCounted
<AsyncDelegateLogger
>;
3923 AsyncDelegateLogger(URLRequest
* url_request
,
3924 LoadState expected_first_load_state
,
3925 LoadState expected_second_load_state
,
3926 LoadState expected_third_load_state
,
3927 const Callback
& callback
)
3928 : url_request_(url_request
),
3929 expected_first_load_state_(expected_first_load_state
),
3930 expected_second_load_state_(expected_second_load_state
),
3931 expected_third_load_state_(expected_third_load_state
),
3932 callback_(callback
) {
3935 ~AsyncDelegateLogger() {}
3938 url_request_
->LogBlockedBy(kFirstDelegateInfo
);
3939 LoadStateWithParam load_state
= url_request_
->GetLoadState();
3940 EXPECT_EQ(expected_first_load_state_
, load_state
.state
);
3941 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo
), load_state
.param
);
3942 base::MessageLoop::current()->PostTask(
3944 base::Bind(&AsyncDelegateLogger::LogSecondDelegate
, this));
3947 void LogSecondDelegate() {
3948 url_request_
->LogAndReportBlockedBy(kSecondDelegateInfo
);
3949 LoadStateWithParam load_state
= url_request_
->GetLoadState();
3950 EXPECT_EQ(expected_second_load_state_
, load_state
.state
);
3951 if (expected_second_load_state_
== LOAD_STATE_WAITING_FOR_DELEGATE
) {
3952 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo
), load_state
.param
);
3954 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo
), load_state
.param
);
3956 base::MessageLoop::current()->PostTask(
3958 base::Bind(&AsyncDelegateLogger::LogComplete
, this));
3961 void LogComplete() {
3962 url_request_
->LogUnblocked();
3963 LoadStateWithParam load_state
= url_request_
->GetLoadState();
3964 EXPECT_EQ(expected_third_load_state_
, load_state
.state
);
3965 if (expected_second_load_state_
== LOAD_STATE_WAITING_FOR_DELEGATE
)
3966 EXPECT_EQ(base::string16(), load_state
.param
);
3970 URLRequest
* url_request_
;
3971 const int expected_first_load_state_
;
3972 const int expected_second_load_state_
;
3973 const int expected_third_load_state_
;
3974 const Callback callback_
;
3976 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger
);
3979 // NetworkDelegate that logs delegate information before a request is started,
3980 // before headers are sent, when headers are read, and when auth information
3981 // is requested. Uses AsyncDelegateLogger.
3982 class AsyncLoggingNetworkDelegate
: public TestNetworkDelegate
{
3984 AsyncLoggingNetworkDelegate() {}
3985 virtual ~AsyncLoggingNetworkDelegate() {}
3987 // NetworkDelegate implementation.
3988 virtual int OnBeforeURLRequest(URLRequest
* request
,
3989 const CompletionCallback
& callback
,
3990 GURL
* new_url
) OVERRIDE
{
3991 TestNetworkDelegate::OnBeforeURLRequest(request
, callback
, new_url
);
3992 return RunCallbackAsynchronously(request
, callback
);
3995 virtual int OnBeforeSendHeaders(URLRequest
* request
,
3996 const CompletionCallback
& callback
,
3997 HttpRequestHeaders
* headers
) OVERRIDE
{
3998 TestNetworkDelegate::OnBeforeSendHeaders(request
, callback
, headers
);
3999 return RunCallbackAsynchronously(request
, callback
);
4002 virtual int OnHeadersReceived(
4003 URLRequest
* request
,
4004 const CompletionCallback
& callback
,
4005 const HttpResponseHeaders
* original_response_headers
,
4006 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
4007 GURL
* allowed_unsafe_redirect_url
) OVERRIDE
{
4008 TestNetworkDelegate::OnHeadersReceived(request
,
4010 original_response_headers
,
4011 override_response_headers
,
4012 allowed_unsafe_redirect_url
);
4013 return RunCallbackAsynchronously(request
, callback
);
4016 virtual NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
4017 URLRequest
* request
,
4018 const AuthChallengeInfo
& auth_info
,
4019 const AuthCallback
& callback
,
4020 AuthCredentials
* credentials
) OVERRIDE
{
4021 AsyncDelegateLogger::Run(
4023 LOAD_STATE_WAITING_FOR_DELEGATE
,
4024 LOAD_STATE_WAITING_FOR_DELEGATE
,
4025 LOAD_STATE_WAITING_FOR_DELEGATE
,
4026 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume
,
4027 callback
, credentials
));
4028 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
4032 static int RunCallbackAsynchronously(
4033 URLRequest
* request
,
4034 const CompletionCallback
& callback
) {
4035 AsyncDelegateLogger::Run(
4037 LOAD_STATE_WAITING_FOR_DELEGATE
,
4038 LOAD_STATE_WAITING_FOR_DELEGATE
,
4039 LOAD_STATE_WAITING_FOR_DELEGATE
,
4040 base::Bind(callback
, OK
));
4041 return ERR_IO_PENDING
;
4044 static void SetAuthAndResume(const AuthCallback
& callback
,
4045 AuthCredentials
* credentials
) {
4046 *credentials
= AuthCredentials(kUser
, kSecret
);
4047 callback
.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
4050 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate
);
4053 // URLRequest::Delegate that logs delegate information when the headers
4054 // are received, when each read completes, and during redirects. Uses
4055 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4057 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4058 // advancing to the next step in most cases, as well as cancellation.
4059 class AsyncLoggingUrlRequestDelegate
: public TestDelegate
{
4063 CANCEL_ON_RECEIVED_REDIRECT
,
4064 CANCEL_ON_RESPONSE_STARTED
,
4065 CANCEL_ON_READ_COMPLETED
4068 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage
)
4069 : cancel_stage_(cancel_stage
) {
4070 if (cancel_stage
== CANCEL_ON_RECEIVED_REDIRECT
)
4071 set_cancel_in_received_redirect(true);
4072 else if (cancel_stage
== CANCEL_ON_RESPONSE_STARTED
)
4073 set_cancel_in_response_started(true);
4074 else if (cancel_stage
== CANCEL_ON_READ_COMPLETED
)
4075 set_cancel_in_received_data(true);
4077 virtual ~AsyncLoggingUrlRequestDelegate() {}
4079 // URLRequest::Delegate implementation:
4080 void virtual OnReceivedRedirect(URLRequest
* request
,
4081 const GURL
& new_url
,
4082 bool* defer_redirect
) OVERRIDE
{
4083 *defer_redirect
= true;
4084 AsyncDelegateLogger::Run(
4086 LOAD_STATE_WAITING_FOR_DELEGATE
,
4087 LOAD_STATE_WAITING_FOR_DELEGATE
,
4088 LOAD_STATE_WAITING_FOR_DELEGATE
,
4090 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete
,
4091 base::Unretained(this), request
, new_url
));
4094 virtual void OnResponseStarted(URLRequest
* request
) OVERRIDE
{
4095 AsyncDelegateLogger::Run(
4097 LOAD_STATE_WAITING_FOR_DELEGATE
,
4098 LOAD_STATE_WAITING_FOR_DELEGATE
,
4099 LOAD_STATE_WAITING_FOR_DELEGATE
,
4101 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete
,
4102 base::Unretained(this), request
));
4105 virtual void OnReadCompleted(URLRequest
* request
,
4106 int bytes_read
) OVERRIDE
{
4107 AsyncDelegateLogger::Run(
4113 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete
,
4114 base::Unretained(this), request
, bytes_read
));
4118 void OnReceivedRedirectLoggingComplete(URLRequest
* request
,
4119 const GURL
& new_url
) {
4120 bool defer_redirect
= false;
4121 TestDelegate::OnReceivedRedirect(request
, new_url
, &defer_redirect
);
4122 // FollowDeferredRedirect should not be called after cancellation.
4123 if (cancel_stage_
== CANCEL_ON_RECEIVED_REDIRECT
)
4125 if (!defer_redirect
)
4126 request
->FollowDeferredRedirect();
4129 void OnResponseStartedLoggingComplete(URLRequest
* request
) {
4130 // The parent class continues the request.
4131 TestDelegate::OnResponseStarted(request
);
4134 void AfterReadCompletedLoggingComplete(URLRequest
* request
, int bytes_read
) {
4135 // The parent class continues the request.
4136 TestDelegate::OnReadCompleted(request
, bytes_read
);
4139 const CancelStage cancel_stage_
;
4141 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate
);
4144 // Tests handling of delegate info before a request starts.
4145 TEST_F(URLRequestTestHTTP
, DelegateInfoBeforeStart
) {
4146 ASSERT_TRUE(test_server_
.Start());
4148 TestDelegate request_delegate
;
4149 TestURLRequestContext
context(true);
4150 context
.set_network_delegate(NULL
);
4151 context
.set_net_log(&net_log_
);
4155 URLRequest
r(test_server_
.GetURL("empty.html"),
4159 LoadStateWithParam load_state
= r
.GetLoadState();
4160 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4161 EXPECT_EQ(base::string16(), load_state
.param
);
4163 AsyncDelegateLogger::Run(
4165 LOAD_STATE_WAITING_FOR_DELEGATE
,
4166 LOAD_STATE_WAITING_FOR_DELEGATE
,
4168 base::Bind(&URLRequest::Start
, base::Unretained(&r
)));
4170 base::RunLoop().Run();
4172 EXPECT_EQ(200, r
.GetResponseCode());
4173 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
4176 CapturingNetLog::CapturedEntryList entries
;
4177 net_log_
.GetEntries(&entries
);
4178 size_t log_position
= ExpectLogContainsSomewhereAfter(
4181 NetLog::TYPE_DELEGATE_INFO
,
4182 NetLog::PHASE_BEGIN
);
4184 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
, log_position
);
4186 // Nothing else should add any delegate info to the request.
4187 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4188 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4191 // Tests handling of delegate info from a network delegate.
4192 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfo
) {
4193 ASSERT_TRUE(test_server_
.Start());
4195 TestDelegate request_delegate
;
4196 AsyncLoggingNetworkDelegate network_delegate
;
4197 TestURLRequestContext
context(true);
4198 context
.set_network_delegate(&network_delegate
);
4199 context
.set_net_log(&net_log_
);
4203 URLRequest
r(test_server_
.GetURL("simple.html"),
4207 LoadStateWithParam load_state
= r
.GetLoadState();
4208 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4209 EXPECT_EQ(base::string16(), load_state
.param
);
4212 base::RunLoop().Run();
4214 EXPECT_EQ(200, r
.GetResponseCode());
4215 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
4216 EXPECT_EQ(1, network_delegate
.created_requests());
4217 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4219 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4221 size_t log_position
= 0;
4222 CapturingNetLog::CapturedEntryList entries
;
4223 net_log_
.GetEntries(&entries
);
4224 for (size_t i
= 0; i
< 3; ++i
) {
4225 log_position
= ExpectLogContainsSomewhereAfter(
4228 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4229 NetLog::PHASE_BEGIN
);
4231 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4234 ASSERT_LT(log_position
, entries
.size());
4235 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4236 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4239 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4240 entries
, log_position
+ 1);
4244 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4245 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4248 // Tests handling of delegate info from a network delegate in the case of an
4250 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfoRedirect
) {
4251 ASSERT_TRUE(test_server_
.Start());
4253 TestDelegate request_delegate
;
4254 AsyncLoggingNetworkDelegate network_delegate
;
4255 TestURLRequestContext
context(true);
4256 context
.set_network_delegate(&network_delegate
);
4257 context
.set_net_log(&net_log_
);
4261 URLRequest
r(test_server_
.GetURL("server-redirect?simple.html"),
4265 LoadStateWithParam load_state
= r
.GetLoadState();
4266 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4267 EXPECT_EQ(base::string16(), load_state
.param
);
4270 base::RunLoop().Run();
4272 EXPECT_EQ(200, r
.GetResponseCode());
4273 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
4274 EXPECT_EQ(2, network_delegate
.created_requests());
4275 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4277 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4279 size_t log_position
= 0;
4280 CapturingNetLog::CapturedEntryList entries
;
4281 net_log_
.GetEntries(&entries
);
4282 // The NetworkDelegate logged information in OnBeforeURLRequest,
4283 // OnBeforeSendHeaders, and OnHeadersReceived.
4284 for (size_t i
= 0; i
< 3; ++i
) {
4285 log_position
= ExpectLogContainsSomewhereAfter(
4288 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4289 NetLog::PHASE_BEGIN
);
4291 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4294 ASSERT_LT(log_position
, entries
.size());
4295 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4296 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4299 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4300 entries
, log_position
+ 1);
4304 // The URLRequest::Delegate then gets informed about the redirect.
4305 log_position
= ExpectLogContainsSomewhereAfter(
4308 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4309 NetLog::PHASE_BEGIN
);
4311 // The NetworkDelegate logged information in the same three events as before.
4312 for (size_t i
= 0; i
< 3; ++i
) {
4313 log_position
= ExpectLogContainsSomewhereAfter(
4316 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4317 NetLog::PHASE_BEGIN
);
4319 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4322 ASSERT_LT(log_position
, entries
.size());
4323 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4324 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4327 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4328 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4331 // Tests handling of delegate info from a network delegate in the case of HTTP
4333 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfoAuth
) {
4334 ASSERT_TRUE(test_server_
.Start());
4336 TestDelegate request_delegate
;
4337 AsyncLoggingNetworkDelegate network_delegate
;
4338 TestURLRequestContext
context(true);
4339 context
.set_network_delegate(&network_delegate
);
4340 context
.set_net_log(&net_log_
);
4344 URLRequest
r(test_server_
.GetURL("auth-basic"),
4348 LoadStateWithParam load_state
= r
.GetLoadState();
4349 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4350 EXPECT_EQ(base::string16(), load_state
.param
);
4353 base::RunLoop().Run();
4355 EXPECT_EQ(200, r
.GetResponseCode());
4356 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
4357 EXPECT_EQ(1, network_delegate
.created_requests());
4358 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4360 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4362 size_t log_position
= 0;
4363 CapturingNetLog::CapturedEntryList entries
;
4364 net_log_
.GetEntries(&entries
);
4365 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4366 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4367 // OnBeforeURLRequest and OnBeforeSendHeaders.
4368 for (size_t i
= 0; i
< 6; ++i
) {
4369 log_position
= ExpectLogContainsSomewhereAfter(
4372 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4373 NetLog::PHASE_BEGIN
);
4375 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4378 ASSERT_LT(log_position
, entries
.size());
4379 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4380 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4383 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4384 entries
, log_position
+ 1);
4388 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4389 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4392 // Tests handling of delegate info from a URLRequest::Delegate.
4393 TEST_F(URLRequestTestHTTP
, URLRequestDelegateInfo
) {
4394 ASSERT_TRUE(test_server_
.Start());
4396 AsyncLoggingUrlRequestDelegate
request_delegate(
4397 AsyncLoggingUrlRequestDelegate::NO_CANCEL
);
4398 TestURLRequestContext
context(true);
4399 context
.set_network_delegate(NULL
);
4400 context
.set_net_log(&net_log_
);
4404 // A chunked response with delays between chunks is used to make sure that
4405 // attempts by the URLRequest delegate to log information while reading the
4406 // body are ignored. Since they are ignored, this test is robust against
4407 // the possibility of multiple reads being combined in the unlikely event
4409 URLRequest
r(test_server_
.GetURL("chunked?waitBetweenChunks=20"),
4413 LoadStateWithParam load_state
= r
.GetLoadState();
4415 base::RunLoop().Run();
4417 EXPECT_EQ(200, r
.GetResponseCode());
4418 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
4421 CapturingNetLog::CapturedEntryList entries
;
4422 net_log_
.GetEntries(&entries
);
4424 size_t log_position
= 0;
4426 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4427 entries
, log_position
);
4429 // The delegate info should only have been logged on header complete. Other
4430 // times it should silently be ignored.
4432 ExpectLogContainsSomewhereAfter(entries
,
4434 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4435 NetLog::PHASE_BEGIN
);
4437 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4440 ASSERT_LT(log_position
, entries
.size());
4441 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4442 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4444 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4445 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4446 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4447 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4450 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4451 // an HTTP redirect.
4452 TEST_F(URLRequestTestHTTP
, URLRequestDelegateInfoOnRedirect
) {
4453 ASSERT_TRUE(test_server_
.Start());
4455 AsyncLoggingUrlRequestDelegate
request_delegate(
4456 AsyncLoggingUrlRequestDelegate::NO_CANCEL
);
4457 TestURLRequestContext
context(true);
4458 context
.set_network_delegate(NULL
);
4459 context
.set_net_log(&net_log_
);
4463 URLRequest
r(test_server_
.GetURL("server-redirect?simple.html"),
4467 LoadStateWithParam load_state
= r
.GetLoadState();
4469 base::RunLoop().Run();
4471 EXPECT_EQ(200, r
.GetResponseCode());
4472 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
4475 CapturingNetLog::CapturedEntryList entries
;
4476 net_log_
.GetEntries(&entries
);
4478 // Delegate info should only have been logged in OnReceivedRedirect and
4479 // OnResponseStarted.
4480 size_t log_position
= 0;
4481 for (int i
= 0; i
< 2; ++i
) {
4483 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4484 entries
, log_position
) + 1;
4487 log_position
= ExpectLogContainsSomewhereAfter(
4490 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4491 NetLog::PHASE_BEGIN
);
4493 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4496 ASSERT_LT(log_position
, entries
.size());
4497 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4498 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4501 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4502 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4503 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4504 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4507 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4508 // an HTTP redirect, with cancellation at various points.
4509 TEST_F(URLRequestTestHTTP
, URLRequestDelegateOnRedirectCancelled
) {
4510 ASSERT_TRUE(test_server_
.Start());
4512 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages
[] = {
4513 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT
,
4514 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED
,
4515 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED
,
4518 for (size_t test_case
= 0; test_case
< arraysize(kCancelStages
);
4520 AsyncLoggingUrlRequestDelegate
request_delegate(kCancelStages
[test_case
]);
4521 TestURLRequestContext
context(true);
4522 CapturingNetLog net_log
;
4523 context
.set_network_delegate(NULL
);
4524 context
.set_net_log(&net_log
);
4528 URLRequest
r(test_server_
.GetURL("server-redirect?simple.html"),
4532 LoadStateWithParam load_state
= r
.GetLoadState();
4534 base::RunLoop().Run();
4535 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
4538 CapturingNetLog::CapturedEntryList entries
;
4539 net_log
.GetEntries(&entries
);
4541 // Delegate info is always logged in both OnReceivedRedirect and
4542 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4543 // OnResponseStarted delegate call is after cancellation, but logging is
4544 // still currently supported in that call.
4545 size_t log_position
= 0;
4546 for (int i
= 0; i
< 2; ++i
) {
4548 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4549 entries
, log_position
) + 1;
4552 log_position
= ExpectLogContainsSomewhereAfter(
4555 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4556 NetLog::PHASE_BEGIN
);
4558 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4561 ASSERT_LT(log_position
, entries
.size());
4562 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4563 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4566 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4567 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4568 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4569 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4575 const char kExtraHeader
[] = "Allow-Snafu";
4576 const char kExtraValue
[] = "fubar";
4578 class RedirectWithAdditionalHeadersDelegate
: public TestDelegate
{
4579 virtual void OnReceivedRedirect(net::URLRequest
* request
,
4580 const GURL
& new_url
,
4581 bool* defer_redirect
) OVERRIDE
{
4582 TestDelegate::OnReceivedRedirect(request
, new_url
, defer_redirect
);
4583 request
->SetExtraRequestHeaderByName(kExtraHeader
, kExtraValue
, false);
4589 TEST_F(URLRequestTestHTTP
, RedirectWithAdditionalHeadersTest
) {
4590 ASSERT_TRUE(test_server_
.Start());
4592 GURL destination_url
= test_server_
.GetURL(
4593 "echoheader?" + std::string(kExtraHeader
));
4594 GURL original_url
= test_server_
.GetURL(
4595 "server-redirect?" + destination_url
.spec());
4596 RedirectWithAdditionalHeadersDelegate d
;
4597 URLRequest
req(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
4599 base::RunLoop().Run();
4602 const HttpRequestHeaders
& headers
= req
.extra_request_headers();
4603 EXPECT_TRUE(headers
.GetHeader(kExtraHeader
, &value
));
4604 EXPECT_EQ(kExtraValue
, value
);
4605 EXPECT_FALSE(req
.is_pending());
4606 EXPECT_FALSE(req
.is_redirecting());
4607 EXPECT_EQ(kExtraValue
, d
.data_received());
4612 const char kExtraHeaderToRemove
[] = "To-Be-Removed";
4614 class RedirectWithHeaderRemovalDelegate
: public TestDelegate
{
4615 virtual void OnReceivedRedirect(net::URLRequest
* request
,
4616 const GURL
& new_url
,
4617 bool* defer_redirect
) OVERRIDE
{
4618 TestDelegate::OnReceivedRedirect(request
, new_url
, defer_redirect
);
4619 request
->RemoveRequestHeaderByName(kExtraHeaderToRemove
);
4625 TEST_F(URLRequestTestHTTP
, RedirectWithHeaderRemovalTest
) {
4626 ASSERT_TRUE(test_server_
.Start());
4628 GURL destination_url
= test_server_
.GetURL(
4629 "echoheader?" + std::string(kExtraHeaderToRemove
));
4630 GURL original_url
= test_server_
.GetURL(
4631 "server-redirect?" + destination_url
.spec());
4632 RedirectWithHeaderRemovalDelegate d
;
4633 URLRequest
req(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
4634 req
.SetExtraRequestHeaderByName(kExtraHeaderToRemove
, "dummy", false);
4636 base::RunLoop().Run();
4639 const HttpRequestHeaders
& headers
= req
.extra_request_headers();
4640 EXPECT_FALSE(headers
.GetHeader(kExtraHeaderToRemove
, &value
));
4641 EXPECT_FALSE(req
.is_pending());
4642 EXPECT_FALSE(req
.is_redirecting());
4643 EXPECT_EQ("None", d
.data_received());
4646 TEST_F(URLRequestTestHTTP
, CancelTest
) {
4649 URLRequest
r(GURL("http://www.google.com/"),
4655 EXPECT_TRUE(r
.is_pending());
4659 base::RunLoop().Run();
4661 // We expect to receive OnResponseStarted even though the request has been
4663 EXPECT_EQ(1, d
.response_started_count());
4664 EXPECT_EQ(0, d
.bytes_received());
4665 EXPECT_FALSE(d
.received_data_before_response());
4669 TEST_F(URLRequestTestHTTP
, CancelTest2
) {
4670 ASSERT_TRUE(test_server_
.Start());
4674 URLRequest
r(test_server_
.GetURL(std::string()),
4679 d
.set_cancel_in_response_started(true);
4682 EXPECT_TRUE(r
.is_pending());
4684 base::RunLoop().Run();
4686 EXPECT_EQ(1, d
.response_started_count());
4687 EXPECT_EQ(0, d
.bytes_received());
4688 EXPECT_FALSE(d
.received_data_before_response());
4689 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
4693 TEST_F(URLRequestTestHTTP
, CancelTest3
) {
4694 ASSERT_TRUE(test_server_
.Start());
4698 URLRequest
r(test_server_
.GetURL(std::string()),
4703 d
.set_cancel_in_received_data(true);
4706 EXPECT_TRUE(r
.is_pending());
4708 base::RunLoop().Run();
4710 EXPECT_EQ(1, d
.response_started_count());
4711 // There is no guarantee about how much data was received
4712 // before the cancel was issued. It could have been 0 bytes,
4713 // or it could have been all the bytes.
4714 // EXPECT_EQ(0, d.bytes_received());
4715 EXPECT_FALSE(d
.received_data_before_response());
4716 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
4720 TEST_F(URLRequestTestHTTP
, CancelTest4
) {
4721 ASSERT_TRUE(test_server_
.Start());
4725 URLRequest
r(test_server_
.GetURL(std::string()),
4731 EXPECT_TRUE(r
.is_pending());
4733 // The request will be implicitly canceled when it is destroyed. The
4734 // test delegate must not post a quit message when this happens because
4735 // this test doesn't actually have a message loop. The quit message would
4736 // get put on this thread's message queue and the next test would exit
4737 // early, causing problems.
4738 d
.set_quit_on_complete(false);
4740 // expect things to just cleanup properly.
4742 // we won't actually get a received reponse here because we've never run the
4744 EXPECT_FALSE(d
.received_data_before_response());
4745 EXPECT_EQ(0, d
.bytes_received());
4748 TEST_F(URLRequestTestHTTP
, CancelTest5
) {
4749 ASSERT_TRUE(test_server_
.Start());
4754 URLRequest
r(test_server_
.GetURL("cachetime"),
4759 base::RunLoop().Run();
4760 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
4763 // cancel read from cache (see bug 990242)
4766 URLRequest
r(test_server_
.GetURL("cachetime"),
4772 base::RunLoop().Run();
4774 EXPECT_EQ(URLRequestStatus::CANCELED
, r
.status().status());
4775 EXPECT_EQ(1, d
.response_started_count());
4776 EXPECT_EQ(0, d
.bytes_received());
4777 EXPECT_FALSE(d
.received_data_before_response());
4781 TEST_F(URLRequestTestHTTP
, PostTest
) {
4782 ASSERT_TRUE(test_server_
.Start());
4783 HTTPUploadDataOperationTest("POST");
4786 TEST_F(URLRequestTestHTTP
, PutTest
) {
4787 ASSERT_TRUE(test_server_
.Start());
4788 HTTPUploadDataOperationTest("PUT");
4791 TEST_F(URLRequestTestHTTP
, PostEmptyTest
) {
4792 ASSERT_TRUE(test_server_
.Start());
4797 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, &default_context_
);
4798 r
.set_method("POST");
4801 EXPECT_TRUE(r
.is_pending());
4803 base::RunLoop().Run();
4805 ASSERT_EQ(1, d
.response_started_count())
4806 << "request failed: " << r
.status().status()
4807 << ", error: " << r
.status().error();
4809 EXPECT_FALSE(d
.received_data_before_response());
4810 EXPECT_TRUE(d
.data_received().empty());
4814 TEST_F(URLRequestTestHTTP
, PostFileTest
) {
4815 ASSERT_TRUE(test_server_
.Start());
4820 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, &default_context_
);
4821 r
.set_method("POST");
4824 PathService::Get(base::DIR_EXE
, &dir
);
4825 base::SetCurrentDirectory(dir
);
4827 ScopedVector
<UploadElementReader
> element_readers
;
4829 base::FilePath path
;
4830 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
4831 path
= path
.Append(FILE_PATH_LITERAL("net"));
4832 path
= path
.Append(FILE_PATH_LITERAL("data"));
4833 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
4834 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
4835 element_readers
.push_back(
4836 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4841 r
.set_upload(make_scoped_ptr(
4842 new UploadDataStream(element_readers
.Pass(), 0)));
4845 EXPECT_TRUE(r
.is_pending());
4847 base::RunLoop().Run();
4850 ASSERT_EQ(true, base::GetFileSize(path
, &size
));
4851 scoped_ptr
<char[]> buf(new char[size
]);
4853 ASSERT_EQ(size
, base::ReadFile(path
, buf
.get(), size
));
4855 ASSERT_EQ(1, d
.response_started_count())
4856 << "request failed: " << r
.status().status()
4857 << ", error: " << r
.status().error();
4859 EXPECT_FALSE(d
.received_data_before_response());
4861 EXPECT_EQ(size
, d
.bytes_received());
4862 EXPECT_EQ(std::string(&buf
[0], size
), d
.data_received());
4866 TEST_F(URLRequestTestHTTP
, PostUnreadableFileTest
) {
4867 ASSERT_TRUE(test_server_
.Start());
4871 URLRequest
r(test_server_
.GetURL("echo"), DEFAULT_PRIORITY
,
4872 &d
, &default_context_
);
4873 r
.set_method("POST");
4875 ScopedVector
<UploadElementReader
> element_readers
;
4877 element_readers
.push_back(new UploadFileElementReader(
4878 base::MessageLoopProxy::current().get(),
4879 base::FilePath(FILE_PATH_LITERAL(
4880 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4884 r
.set_upload(make_scoped_ptr(
4885 new UploadDataStream(element_readers
.Pass(), 0)));
4888 EXPECT_TRUE(r
.is_pending());
4890 base::RunLoop().Run();
4892 EXPECT_TRUE(d
.request_failed());
4893 EXPECT_FALSE(d
.received_data_before_response());
4894 EXPECT_EQ(0, d
.bytes_received());
4895 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
4896 EXPECT_EQ(ERR_FILE_NOT_FOUND
, r
.status().error());
4900 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataBeforeStart
) {
4901 ASSERT_TRUE(test_server_
.Start());
4906 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, &default_context_
);
4907 r
.EnableChunkedUpload();
4908 r
.set_method("POST");
4909 AddChunksToUpload(&r
);
4911 EXPECT_TRUE(r
.is_pending());
4913 base::RunLoop().Run();
4915 VerifyReceivedDataMatchesChunks(&r
, &d
);
4919 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataJustAfterStart
) {
4920 ASSERT_TRUE(test_server_
.Start());
4925 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, &default_context_
);
4926 r
.EnableChunkedUpload();
4927 r
.set_method("POST");
4929 EXPECT_TRUE(r
.is_pending());
4930 AddChunksToUpload(&r
);
4931 base::RunLoop().Run();
4933 VerifyReceivedDataMatchesChunks(&r
, &d
);
4937 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataAfterStart
) {
4938 ASSERT_TRUE(test_server_
.Start());
4943 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, &default_context_
);
4944 r
.EnableChunkedUpload();
4945 r
.set_method("POST");
4947 EXPECT_TRUE(r
.is_pending());
4949 base::RunLoop().RunUntilIdle();
4950 AddChunksToUpload(&r
);
4951 base::RunLoop().Run();
4953 VerifyReceivedDataMatchesChunks(&r
, &d
);
4957 TEST_F(URLRequestTestHTTP
, ResponseHeadersTest
) {
4958 ASSERT_TRUE(test_server_
.Start());
4961 URLRequest
req(test_server_
.GetURL("files/with-headers.html"),
4966 base::RunLoop().Run();
4968 const HttpResponseHeaders
* headers
= req
.response_headers();
4970 // Simple sanity check that response_info() accesses the same data.
4971 EXPECT_EQ(headers
, req
.response_info().headers
.get());
4974 EXPECT_TRUE(headers
->GetNormalizedHeader("cache-control", &header
));
4975 EXPECT_EQ("private", header
);
4978 EXPECT_TRUE(headers
->GetNormalizedHeader("content-type", &header
));
4979 EXPECT_EQ("text/html; charset=ISO-8859-1", header
);
4981 // The response has two "X-Multiple-Entries" headers.
4982 // This verfies our output has them concatenated together.
4984 EXPECT_TRUE(headers
->GetNormalizedHeader("x-multiple-entries", &header
));
4985 EXPECT_EQ("a, b", header
);
4988 TEST_F(URLRequestTestHTTP
, ProcessSTS
) {
4989 SpawnedTestServer::SSLOptions ssl_options
;
4990 SpawnedTestServer
https_test_server(
4991 SpawnedTestServer::TYPE_HTTPS
,
4993 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4994 ASSERT_TRUE(https_test_server
.Start());
4997 URLRequest
request(https_test_server
.GetURL("files/hsts-headers.html"),
5002 base::RunLoop().Run();
5004 TransportSecurityState
* security_state
=
5005 default_context_
.transport_security_state();
5006 TransportSecurityState::DomainState domain_state
;
5007 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5008 SpawnedTestServer::kLocalhost
, &domain_state
));
5009 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5010 domain_state
.sts
.upgrade_mode
);
5011 EXPECT_TRUE(domain_state
.sts
.include_subdomains
);
5012 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5013 #if defined(OS_ANDROID)
5014 // Android's CertVerifyProc does not (yet) handle pins.
5016 EXPECT_FALSE(domain_state
.HasPublicKeyPins());
5020 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5021 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5022 // DomainState present because header rejected).
5023 #if defined(OS_ANDROID)
5024 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5026 #define MAYBE_ProcessPKP ProcessPKP
5029 // Tests that enabling HPKP on a domain does not affect the HSTS
5030 // validity/expiration.
5031 TEST_F(URLRequestTestHTTP
, MAYBE_ProcessPKP
) {
5032 SpawnedTestServer::SSLOptions ssl_options
;
5033 SpawnedTestServer
https_test_server(
5034 SpawnedTestServer::TYPE_HTTPS
,
5036 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5037 ASSERT_TRUE(https_test_server
.Start());
5040 URLRequest
request(https_test_server
.GetURL("files/hpkp-headers.html"),
5045 base::RunLoop().Run();
5047 TransportSecurityState
* security_state
=
5048 default_context_
.transport_security_state();
5049 TransportSecurityState::DomainState domain_state
;
5050 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5051 SpawnedTestServer::kLocalhost
, &domain_state
));
5052 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT
,
5053 domain_state
.sts
.upgrade_mode
);
5054 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5055 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5056 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5057 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5060 TEST_F(URLRequestTestHTTP
, ProcessSTSOnce
) {
5061 SpawnedTestServer::SSLOptions ssl_options
;
5062 SpawnedTestServer
https_test_server(
5063 SpawnedTestServer::TYPE_HTTPS
,
5065 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5066 ASSERT_TRUE(https_test_server
.Start());
5070 https_test_server
.GetURL("files/hsts-multiple-headers.html"),
5075 base::RunLoop().Run();
5077 // We should have set parameters from the first header, not the second.
5078 TransportSecurityState
* security_state
=
5079 default_context_
.transport_security_state();
5080 TransportSecurityState::DomainState domain_state
;
5081 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5082 SpawnedTestServer::kLocalhost
, &domain_state
));
5083 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5084 domain_state
.sts
.upgrade_mode
);
5085 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5086 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5089 TEST_F(URLRequestTestHTTP
, ProcessSTSAndPKP
) {
5090 SpawnedTestServer::SSLOptions ssl_options
;
5091 SpawnedTestServer
https_test_server(
5092 SpawnedTestServer::TYPE_HTTPS
,
5094 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5095 ASSERT_TRUE(https_test_server
.Start());
5099 https_test_server
.GetURL("files/hsts-and-hpkp-headers.html"),
5104 base::RunLoop().Run();
5106 // We should have set parameters from the first header, not the second.
5107 TransportSecurityState
* security_state
=
5108 default_context_
.transport_security_state();
5109 TransportSecurityState::DomainState domain_state
;
5110 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5111 SpawnedTestServer::kLocalhost
, &domain_state
));
5112 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5113 domain_state
.sts
.upgrade_mode
);
5114 #if defined(OS_ANDROID)
5115 // Android's CertVerifyProc does not (yet) handle pins.
5117 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5119 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5121 // Even though there is an HSTS header asserting includeSubdomains, it is
5122 // the *second* such header, and we MUST process only the first.
5123 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5124 // includeSubdomains does not occur in the test HPKP header.
5125 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5128 // Tests that when multiple HPKP headers are present, asserting different
5129 // policies, that only the first such policy is processed.
5130 TEST_F(URLRequestTestHTTP
, ProcessSTSAndPKP2
) {
5131 SpawnedTestServer::SSLOptions ssl_options
;
5132 SpawnedTestServer
https_test_server(
5133 SpawnedTestServer::TYPE_HTTPS
,
5135 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5136 ASSERT_TRUE(https_test_server
.Start());
5140 https_test_server
.GetURL("files/hsts-and-hpkp-headers2.html"),
5145 base::RunLoop().Run();
5147 TransportSecurityState
* security_state
=
5148 default_context_
.transport_security_state();
5149 TransportSecurityState::DomainState domain_state
;
5150 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5151 SpawnedTestServer::kLocalhost
, &domain_state
));
5152 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5153 domain_state
.sts
.upgrade_mode
);
5154 #if defined(OS_ANDROID)
5155 // Android's CertVerifyProc does not (yet) handle pins.
5157 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5159 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5161 EXPECT_TRUE(domain_state
.sts
.include_subdomains
);
5162 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5165 TEST_F(URLRequestTestHTTP
, ContentTypeNormalizationTest
) {
5166 ASSERT_TRUE(test_server_
.Start());
5169 URLRequest
req(test_server_
.GetURL("files/content-type-normalization.html"),
5174 base::RunLoop().Run();
5176 std::string mime_type
;
5177 req
.GetMimeType(&mime_type
);
5178 EXPECT_EQ("text/html", mime_type
);
5180 std::string charset
;
5181 req
.GetCharset(&charset
);
5182 EXPECT_EQ("utf-8", charset
);
5186 TEST_F(URLRequestTestHTTP
, ProtocolHandlerAndFactoryRestrictDataRedirects
) {
5187 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5188 GURL
data_url("data:,foo");
5189 DataProtocolHandler data_protocol_handler
;
5190 EXPECT_FALSE(data_protocol_handler
.IsSafeRedirectTarget(data_url
));
5192 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5193 EXPECT_FALSE(job_factory_
.IsSafeRedirectTarget(data_url
));
5196 #if !defined(DISABLE_FILE_SUPPORT)
5197 TEST_F(URLRequestTestHTTP
, ProtocolHandlerAndFactoryRestrictFileRedirects
) {
5198 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5199 GURL
file_url("file:///foo.txt");
5200 FileProtocolHandler
file_protocol_handler(base::MessageLoopProxy::current());
5201 EXPECT_FALSE(file_protocol_handler
.IsSafeRedirectTarget(file_url
));
5203 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5204 EXPECT_FALSE(job_factory_
.IsSafeRedirectTarget(file_url
));
5207 TEST_F(URLRequestTestHTTP
, RestrictFileRedirects
) {
5208 ASSERT_TRUE(test_server_
.Start());
5211 URLRequest
req(test_server_
.GetURL("files/redirect-to-file.html"),
5216 base::RunLoop().Run();
5218 EXPECT_EQ(URLRequestStatus::FAILED
, req
.status().status());
5219 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, req
.status().error());
5221 #endif // !defined(DISABLE_FILE_SUPPORT)
5223 TEST_F(URLRequestTestHTTP
, RestrictDataRedirects
) {
5224 ASSERT_TRUE(test_server_
.Start());
5227 URLRequest
req(test_server_
.GetURL("files/redirect-to-data.html"),
5232 base::MessageLoop::current()->Run();
5234 EXPECT_EQ(URLRequestStatus::FAILED
, req
.status().status());
5235 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, req
.status().error());
5238 TEST_F(URLRequestTestHTTP
, RedirectToInvalidURL
) {
5239 ASSERT_TRUE(test_server_
.Start());
5242 URLRequest
req(test_server_
.GetURL("files/redirect-to-invalid-url.html"),
5247 base::RunLoop().Run();
5249 EXPECT_EQ(URLRequestStatus::FAILED
, req
.status().status());
5250 EXPECT_EQ(ERR_INVALID_URL
, req
.status().error());
5253 // Make sure redirects are cached, despite not reading their bodies.
5254 TEST_F(URLRequestTestHTTP
, CacheRedirect
) {
5255 ASSERT_TRUE(test_server_
.Start());
5257 test_server_
.GetURL("files/redirect302-to-echo-cacheable");
5261 URLRequest
req(redirect_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5263 base::RunLoop().Run();
5264 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5265 EXPECT_EQ(1, d
.received_redirect_count());
5266 EXPECT_EQ(test_server_
.GetURL("echo"), req
.url());
5271 d
.set_quit_on_redirect(true);
5272 URLRequest
req(redirect_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5274 base::RunLoop().Run();
5276 EXPECT_EQ(1, d
.received_redirect_count());
5277 EXPECT_EQ(0, d
.response_started_count());
5278 EXPECT_TRUE(req
.was_cached());
5280 req
.FollowDeferredRedirect();
5281 base::RunLoop().Run();
5282 EXPECT_EQ(1, d
.received_redirect_count());
5283 EXPECT_EQ(1, d
.response_started_count());
5284 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5285 EXPECT_EQ(test_server_
.GetURL("echo"), req
.url());
5289 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5290 // when the headers are read, since the body won't have been read.
5291 TEST_F(URLRequestTestHTTP
, NoCacheOnNetworkDelegateRedirect
) {
5292 ASSERT_TRUE(test_server_
.Start());
5293 // URL that is normally cached.
5294 GURL initial_url
= test_server_
.GetURL("cachetime");
5297 // Set up the TestNetworkDelegate tp force a redirect.
5298 GURL redirect_to_url
= test_server_
.GetURL("echo");
5299 default_network_delegate_
.set_redirect_on_headers_received_url(
5303 URLRequest
req(initial_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5305 base::RunLoop().Run();
5306 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5307 EXPECT_EQ(1, d
.received_redirect_count());
5308 EXPECT_EQ(redirect_to_url
, req
.url());
5313 URLRequest
req(initial_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5315 base::RunLoop().Run();
5317 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5318 EXPECT_FALSE(req
.was_cached());
5319 EXPECT_EQ(0, d
.received_redirect_count());
5320 EXPECT_EQ(initial_url
, req
.url());
5324 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5326 TEST_F(URLRequestTestHTTP
, UnsafeRedirectToWhitelistedUnsafeURL
) {
5327 ASSERT_TRUE(test_server_
.Start());
5329 GURL
unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5330 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5331 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5335 URLRequest
r(test_server_
.GetURL("whatever"),
5341 base::RunLoop().Run();
5343 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
5345 EXPECT_EQ(2U, r
.url_chain().size());
5346 EXPECT_EQ(net::OK
, r
.status().error());
5347 EXPECT_EQ(unsafe_url
, r
.url());
5348 EXPECT_EQ("this-is-considered-an-unsafe-url", d
.data_received());
5352 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5353 // some other URL to the whitelist.
5354 TEST_F(URLRequestTestHTTP
, UnsafeRedirectToDifferentUnsafeURL
) {
5355 ASSERT_TRUE(test_server_
.Start());
5357 GURL
unsafe_url("data:text/html,something");
5358 GURL
different_unsafe_url("data:text/html,something-else");
5359 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5360 default_network_delegate_
.set_allowed_unsafe_redirect_url(
5361 different_unsafe_url
);
5365 URLRequest
r(test_server_
.GetURL("whatever"),
5371 base::RunLoop().Run();
5373 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
5374 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, r
.status().error());
5378 // Redirects from an URL with fragment to an unsafe URL with fragment should
5379 // be allowed, and the reference fragment of the target URL should be preserved.
5380 TEST_F(URLRequestTestHTTP
, UnsafeRedirectWithDifferentReferenceFragment
) {
5381 ASSERT_TRUE(test_server_
.Start());
5383 GURL
original_url(test_server_
.GetURL("original#fragment1"));
5384 GURL
unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5385 GURL
expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5387 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5388 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5392 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5395 base::RunLoop().Run();
5397 EXPECT_EQ(2U, r
.url_chain().size());
5398 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
5399 EXPECT_EQ(net::OK
, r
.status().error());
5400 EXPECT_EQ(original_url
, r
.original_url());
5401 EXPECT_EQ(expected_url
, r
.url());
5405 // When a delegate has specified a safe redirect URL, but it does not match the
5406 // redirect target, then do not prevent the reference fragment from being added.
5407 TEST_F(URLRequestTestHTTP
, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl
) {
5408 ASSERT_TRUE(test_server_
.Start());
5410 GURL
original_url(test_server_
.GetURL("original#expected-fragment"));
5411 GURL
unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5412 GURL
redirect_url(test_server_
.GetURL("target"));
5413 GURL
expected_redirect_url(test_server_
.GetURL("target#expected-fragment"));
5415 default_network_delegate_
.set_redirect_on_headers_received_url(redirect_url
);
5416 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5420 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5423 base::RunLoop().Run();
5425 EXPECT_EQ(2U, r
.url_chain().size());
5426 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
5427 EXPECT_EQ(net::OK
, r
.status().error());
5428 EXPECT_EQ(original_url
, r
.original_url());
5429 EXPECT_EQ(expected_redirect_url
, r
.url());
5433 // When a delegate has specified a safe redirect URL, assume that the redirect
5434 // URL should not be changed. In particular, the reference fragment should not
5436 TEST_F(URLRequestTestHTTP
, RedirectWithReferenceFragment
) {
5437 ASSERT_TRUE(test_server_
.Start());
5439 GURL
original_url(test_server_
.GetURL("original#should-not-be-appended"));
5440 GURL
redirect_url("data:text/html,expect-no-reference-fragment");
5442 default_network_delegate_
.set_redirect_on_headers_received_url(redirect_url
);
5443 default_network_delegate_
.set_allowed_unsafe_redirect_url(redirect_url
);
5447 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5450 base::RunLoop().Run();
5452 EXPECT_EQ(2U, r
.url_chain().size());
5453 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
5454 EXPECT_EQ(net::OK
, r
.status().error());
5455 EXPECT_EQ(original_url
, r
.original_url());
5456 EXPECT_EQ(redirect_url
, r
.url());
5460 // When a URLRequestRedirectJob is created, the redirection must be followed and
5461 // the reference fragment of the target URL must not be modified.
5462 TEST_F(URLRequestTestHTTP
, RedirectJobWithReferenceFragment
) {
5463 ASSERT_TRUE(test_server_
.Start());
5465 GURL
original_url(test_server_
.GetURL("original#should-not-be-appended"));
5466 GURL
redirect_url(test_server_
.GetURL("echo"));
5469 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5471 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
5472 &r
, &default_network_delegate_
, redirect_url
,
5473 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
5474 AddTestInterceptor()->set_main_intercept_job(job
);
5477 base::RunLoop().Run();
5479 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
5480 EXPECT_EQ(net::OK
, r
.status().error());
5481 EXPECT_EQ(original_url
, r
.original_url());
5482 EXPECT_EQ(redirect_url
, r
.url());
5485 TEST_F(URLRequestTestHTTP
, NoUserPassInReferrer
) {
5486 ASSERT_TRUE(test_server_
.Start());
5489 URLRequest
req(test_server_
.GetURL("echoheader?Referer"),
5493 req
.SetReferrer("http://user:pass@foo.com/");
5495 base::RunLoop().Run();
5497 EXPECT_EQ(std::string("http://foo.com/"), d
.data_received());
5500 TEST_F(URLRequestTestHTTP
, NoFragmentInReferrer
) {
5501 ASSERT_TRUE(test_server_
.Start());
5504 URLRequest
req(test_server_
.GetURL("echoheader?Referer"),
5508 req
.SetReferrer("http://foo.com/test#fragment");
5510 base::RunLoop().Run();
5512 EXPECT_EQ(std::string("http://foo.com/test"), d
.data_received());
5515 TEST_F(URLRequestTestHTTP
, EmptyReferrerAfterValidReferrer
) {
5516 ASSERT_TRUE(test_server_
.Start());
5519 URLRequest
req(test_server_
.GetURL("echoheader?Referer"),
5523 req
.SetReferrer("http://foo.com/test#fragment");
5524 req
.SetReferrer("");
5526 base::RunLoop().Run();
5528 EXPECT_EQ(std::string("None"), d
.data_received());
5531 // Defer network start and then resume, checking that the request was a success
5532 // and bytes were received.
5533 TEST_F(URLRequestTestHTTP
, DeferredBeforeNetworkStart
) {
5534 ASSERT_TRUE(test_server_
.Start());
5538 d
.set_quit_on_network_start(true);
5539 GURL
test_url(test_server_
.GetURL("echo"));
5540 URLRequest
req(test_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5543 base::RunLoop().Run();
5545 EXPECT_EQ(1, d
.received_before_network_start_count());
5546 EXPECT_EQ(0, d
.response_started_count());
5548 req
.ResumeNetworkStart();
5549 base::RunLoop().Run();
5551 EXPECT_EQ(1, d
.response_started_count());
5552 EXPECT_NE(0, d
.bytes_received());
5553 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5557 // Check that OnBeforeNetworkStart is only called once even if there is a
5559 TEST_F(URLRequestTestHTTP
, BeforeNetworkStartCalledOnce
) {
5560 ASSERT_TRUE(test_server_
.Start());
5564 d
.set_quit_on_redirect(true);
5565 d
.set_quit_on_network_start(true);
5566 URLRequest
req(test_server_
.GetURL("server-redirect?echo"),
5572 base::RunLoop().Run();
5574 EXPECT_EQ(1, d
.received_before_network_start_count());
5575 EXPECT_EQ(0, d
.response_started_count());
5576 EXPECT_EQ(0, d
.received_redirect_count());
5578 req
.ResumeNetworkStart();
5579 base::RunLoop().Run();
5581 EXPECT_EQ(1, d
.received_redirect_count());
5582 req
.FollowDeferredRedirect();
5583 base::RunLoop().Run();
5585 // Check that the redirect's new network transaction does not get propagated
5586 // to a second OnBeforeNetworkStart() notification.
5587 EXPECT_EQ(1, d
.received_before_network_start_count());
5589 EXPECT_EQ(1, d
.response_started_count());
5590 EXPECT_NE(0, d
.bytes_received());
5591 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5595 // Cancel the request after learning that the request would use the network.
5596 TEST_F(URLRequestTestHTTP
, CancelOnBeforeNetworkStart
) {
5597 ASSERT_TRUE(test_server_
.Start());
5601 d
.set_quit_on_network_start(true);
5602 GURL
test_url(test_server_
.GetURL("echo"));
5603 URLRequest
req(test_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5606 base::RunLoop().Run();
5608 EXPECT_EQ(1, d
.received_before_network_start_count());
5609 EXPECT_EQ(0, d
.response_started_count());
5612 base::RunLoop().Run();
5614 EXPECT_EQ(1, d
.response_started_count());
5615 EXPECT_EQ(0, d
.bytes_received());
5616 EXPECT_EQ(URLRequestStatus::CANCELED
, req
.status().status());
5620 TEST_F(URLRequestTestHTTP
, CancelRedirect
) {
5621 ASSERT_TRUE(test_server_
.Start());
5625 d
.set_cancel_in_received_redirect(true);
5626 URLRequest
req(test_server_
.GetURL("files/redirect-test.html"),
5631 base::RunLoop().Run();
5633 EXPECT_EQ(1, d
.response_started_count());
5634 EXPECT_EQ(0, d
.bytes_received());
5635 EXPECT_FALSE(d
.received_data_before_response());
5636 EXPECT_EQ(URLRequestStatus::CANCELED
, req
.status().status());
5640 TEST_F(URLRequestTestHTTP
, DeferredRedirect
) {
5641 ASSERT_TRUE(test_server_
.Start());
5645 d
.set_quit_on_redirect(true);
5646 GURL
test_url(test_server_
.GetURL("files/redirect-test.html"));
5647 URLRequest
req(test_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5650 base::RunLoop().Run();
5652 EXPECT_EQ(1, d
.received_redirect_count());
5654 req
.FollowDeferredRedirect();
5655 base::RunLoop().Run();
5657 EXPECT_EQ(1, d
.response_started_count());
5658 EXPECT_FALSE(d
.received_data_before_response());
5659 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5661 base::FilePath path
;
5662 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
5663 path
= path
.Append(FILE_PATH_LITERAL("net"));
5664 path
= path
.Append(FILE_PATH_LITERAL("data"));
5665 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
5666 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
5668 std::string contents
;
5669 EXPECT_TRUE(base::ReadFileToString(path
, &contents
));
5670 EXPECT_EQ(contents
, d
.data_received());
5674 TEST_F(URLRequestTestHTTP
, DeferredRedirect_GetFullRequestHeaders
) {
5675 ASSERT_TRUE(test_server_
.Start());
5679 d
.set_quit_on_redirect(true);
5680 GURL
test_url(test_server_
.GetURL("files/redirect-test.html"));
5681 URLRequest
req(test_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
5683 EXPECT_FALSE(d
.have_full_request_headers());
5686 base::RunLoop().Run();
5688 EXPECT_EQ(1, d
.received_redirect_count());
5689 EXPECT_TRUE(d
.have_full_request_headers());
5690 CheckFullRequestHeaders(d
.full_request_headers(), test_url
);
5691 d
.ClearFullRequestHeaders();
5693 req
.FollowDeferredRedirect();
5694 base::RunLoop().Run();
5696 GURL
target_url(test_server_
.GetURL("files/with-headers.html"));
5697 EXPECT_EQ(1, d
.response_started_count());
5698 EXPECT_TRUE(d
.have_full_request_headers());
5699 CheckFullRequestHeaders(d
.full_request_headers(), target_url
);
5700 EXPECT_FALSE(d
.received_data_before_response());
5701 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
.status().status());
5703 base::FilePath path
;
5704 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
5705 path
= path
.Append(FILE_PATH_LITERAL("net"));
5706 path
= path
.Append(FILE_PATH_LITERAL("data"));
5707 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
5708 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
5710 std::string contents
;
5711 EXPECT_TRUE(base::ReadFileToString(path
, &contents
));
5712 EXPECT_EQ(contents
, d
.data_received());
5716 TEST_F(URLRequestTestHTTP
, CancelDeferredRedirect
) {
5717 ASSERT_TRUE(test_server_
.Start());
5721 d
.set_quit_on_redirect(true);
5722 URLRequest
req(test_server_
.GetURL("files/redirect-test.html"),
5727 base::RunLoop().Run();
5729 EXPECT_EQ(1, d
.received_redirect_count());
5732 base::RunLoop().Run();
5734 EXPECT_EQ(1, d
.response_started_count());
5735 EXPECT_EQ(0, d
.bytes_received());
5736 EXPECT_FALSE(d
.received_data_before_response());
5737 EXPECT_EQ(URLRequestStatus::CANCELED
, req
.status().status());
5741 TEST_F(URLRequestTestHTTP
, VaryHeader
) {
5742 ASSERT_TRUE(test_server_
.Start());
5744 // Populate the cache.
5747 URLRequest
req(test_server_
.GetURL("echoheadercache?foo"),
5751 HttpRequestHeaders headers
;
5752 headers
.SetHeader("foo", "1");
5753 req
.SetExtraRequestHeaders(headers
);
5755 base::RunLoop().Run();
5757 LoadTimingInfo load_timing_info
;
5758 req
.GetLoadTimingInfo(&load_timing_info
);
5759 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5762 // Expect a cache hit.
5765 URLRequest
req(test_server_
.GetURL("echoheadercache?foo"),
5769 HttpRequestHeaders headers
;
5770 headers
.SetHeader("foo", "1");
5771 req
.SetExtraRequestHeaders(headers
);
5773 base::RunLoop().Run();
5775 EXPECT_TRUE(req
.was_cached());
5777 LoadTimingInfo load_timing_info
;
5778 req
.GetLoadTimingInfo(&load_timing_info
);
5779 TestLoadTimingCacheHitNoNetwork(load_timing_info
);
5782 // Expect a cache miss.
5785 URLRequest
req(test_server_
.GetURL("echoheadercache?foo"),
5789 HttpRequestHeaders headers
;
5790 headers
.SetHeader("foo", "2");
5791 req
.SetExtraRequestHeaders(headers
);
5793 base::RunLoop().Run();
5795 EXPECT_FALSE(req
.was_cached());
5797 LoadTimingInfo load_timing_info
;
5798 req
.GetLoadTimingInfo(&load_timing_info
);
5799 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5803 TEST_F(URLRequestTestHTTP
, BasicAuth
) {
5804 ASSERT_TRUE(test_server_
.Start());
5806 // populate the cache
5809 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5811 URLRequest
r(test_server_
.GetURL("auth-basic"),
5817 base::RunLoop().Run();
5819 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5822 // repeat request with end-to-end validation. since auth-basic results in a
5823 // cachable page, we expect this test to result in a 304. in which case, the
5824 // response should be fetched from the cache.
5827 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5829 URLRequest
r(test_server_
.GetURL("auth-basic"),
5833 r
.SetLoadFlags(LOAD_VALIDATE_CACHE
);
5836 base::RunLoop().Run();
5838 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5840 // Should be the same cached document.
5841 EXPECT_TRUE(r
.was_cached());
5845 // Check that Set-Cookie headers in 401 responses are respected.
5846 // http://crbug.com/6450
5847 TEST_F(URLRequestTestHTTP
, BasicAuthWithCookies
) {
5848 ASSERT_TRUE(test_server_
.Start());
5850 GURL url_requiring_auth
=
5851 test_server_
.GetURL("auth-basic?set-cookie-if-challenged");
5853 // Request a page that will give a 401 containing a Set-Cookie header.
5854 // Verify that when the transaction is restarted, it includes the new cookie.
5856 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
5857 TestURLRequestContext
context(true);
5858 context
.set_network_delegate(&network_delegate
);
5862 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5864 URLRequest
r(url_requiring_auth
, DEFAULT_PRIORITY
, &d
, &context
);
5867 base::RunLoop().Run();
5869 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5871 // Make sure we sent the cookie in the restarted transaction.
5872 EXPECT_TRUE(d
.data_received().find("Cookie: got_challenged=true")
5873 != std::string::npos
);
5876 // Same test as above, except this time the restart is initiated earlier
5877 // (without user intervention since identity is embedded in the URL).
5879 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
5880 TestURLRequestContext
context(true);
5881 context
.set_network_delegate(&network_delegate
);
5886 GURL::Replacements replacements
;
5887 std::string
username("user2");
5888 std::string
password("secret");
5889 replacements
.SetUsernameStr(username
);
5890 replacements
.SetPasswordStr(password
);
5891 GURL url_with_identity
= url_requiring_auth
.ReplaceComponents(replacements
);
5893 URLRequest
r(url_with_identity
, DEFAULT_PRIORITY
, &d
, &context
);
5896 base::RunLoop().Run();
5898 EXPECT_TRUE(d
.data_received().find("user2/secret") != std::string::npos
);
5900 // Make sure we sent the cookie in the restarted transaction.
5901 EXPECT_TRUE(d
.data_received().find("Cookie: got_challenged=true")
5902 != std::string::npos
);
5906 // Tests that load timing works as expected with auth and the cache.
5907 TEST_F(URLRequestTestHTTP
, BasicAuthLoadTiming
) {
5908 ASSERT_TRUE(test_server_
.Start());
5910 // populate the cache
5913 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5915 URLRequest
r(test_server_
.GetURL("auth-basic"),
5921 base::RunLoop().Run();
5923 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5925 LoadTimingInfo load_timing_info_before_auth
;
5926 EXPECT_TRUE(default_network_delegate_
.GetLoadTimingInfoBeforeAuth(
5927 &load_timing_info_before_auth
));
5928 TestLoadTimingNotReused(load_timing_info_before_auth
,
5929 CONNECT_TIMING_HAS_DNS_TIMES
);
5931 LoadTimingInfo load_timing_info
;
5932 r
.GetLoadTimingInfo(&load_timing_info
);
5933 // The test server does not support keep alive sockets, so the second
5934 // request with auth should use a new socket.
5935 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5936 EXPECT_NE(load_timing_info_before_auth
.socket_log_id
,
5937 load_timing_info
.socket_log_id
);
5938 EXPECT_LE(load_timing_info_before_auth
.receive_headers_end
,
5939 load_timing_info
.connect_timing
.connect_start
);
5942 // Repeat request with end-to-end validation. Since auth-basic results in a
5943 // cachable page, we expect this test to result in a 304. In which case, the
5944 // response should be fetched from the cache.
5947 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5949 URLRequest
r(test_server_
.GetURL("auth-basic"),
5953 r
.SetLoadFlags(LOAD_VALIDATE_CACHE
);
5956 base::RunLoop().Run();
5958 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5960 // Should be the same cached document.
5961 EXPECT_TRUE(r
.was_cached());
5963 // Since there was a request that went over the wire, the load timing
5964 // information should include connection times.
5965 LoadTimingInfo load_timing_info
;
5966 r
.GetLoadTimingInfo(&load_timing_info
);
5967 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5971 // In this test, we do a POST which the server will 302 redirect.
5972 // The subsequent transaction should use GET, and should not send the
5973 // Content-Type header.
5974 // http://code.google.com/p/chromium/issues/detail?id=843
5975 TEST_F(URLRequestTestHTTP
, Post302RedirectGet
) {
5976 ASSERT_TRUE(test_server_
.Start());
5978 const char kData
[] = "hello world";
5981 URLRequest
req(test_server_
.GetURL("files/redirect-to-echoall"),
5985 req
.set_method("POST");
5986 req
.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
5988 // Set headers (some of which are specific to the POST).
5989 HttpRequestHeaders headers
;
5990 headers
.AddHeadersFromString(
5991 "Content-Type: multipart/form-data; "
5992 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5993 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5994 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5995 "Accept-Language: en-US,en\r\n"
5996 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5997 "Content-Length: 11\r\n"
5998 "Origin: http://localhost:1337/");
5999 req
.SetExtraRequestHeaders(headers
);
6001 base::RunLoop().Run();
6003 std::string mime_type
;
6004 req
.GetMimeType(&mime_type
);
6005 EXPECT_EQ("text/html", mime_type
);
6007 const std::string
& data
= d
.data_received();
6009 // Check that the post-specific headers were stripped:
6010 EXPECT_FALSE(ContainsString(data
, "Content-Length:"));
6011 EXPECT_FALSE(ContainsString(data
, "Content-Type:"));
6012 EXPECT_FALSE(ContainsString(data
, "Origin:"));
6014 // These extra request headers should not have been stripped.
6015 EXPECT_TRUE(ContainsString(data
, "Accept:"));
6016 EXPECT_TRUE(ContainsString(data
, "Accept-Language:"));
6017 EXPECT_TRUE(ContainsString(data
, "Accept-Charset:"));
6020 // The following tests check that we handle mutating the request method for
6021 // HTTP redirects as expected.
6022 // See http://crbug.com/56373 and http://crbug.com/102130.
6024 TEST_F(URLRequestTestHTTP
, Redirect301Tests
) {
6025 ASSERT_TRUE(test_server_
.Start());
6027 const GURL url
= test_server_
.GetURL("files/redirect301-to-echo");
6029 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6030 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6031 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6034 TEST_F(URLRequestTestHTTP
, Redirect302Tests
) {
6035 ASSERT_TRUE(test_server_
.Start());
6037 const GURL url
= test_server_
.GetURL("files/redirect302-to-echo");
6039 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6040 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6041 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6044 TEST_F(URLRequestTestHTTP
, Redirect303Tests
) {
6045 ASSERT_TRUE(test_server_
.Start());
6047 const GURL url
= test_server_
.GetURL("files/redirect303-to-echo");
6049 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6050 HTTPRedirectMethodTest(url
, "PUT", "GET", true);
6051 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6054 TEST_F(URLRequestTestHTTP
, Redirect307Tests
) {
6055 ASSERT_TRUE(test_server_
.Start());
6057 const GURL url
= test_server_
.GetURL("files/redirect307-to-echo");
6059 HTTPRedirectMethodTest(url
, "POST", "POST", true);
6060 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6061 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6064 TEST_F(URLRequestTestHTTP
, Redirect308Tests
) {
6065 ASSERT_TRUE(test_server_
.Start());
6067 const GURL url
= test_server_
.GetURL("files/redirect308-to-echo");
6069 HTTPRedirectMethodTest(url
, "POST", "POST", true);
6070 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6071 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6074 // Make sure that 308 responses without bodies are not treated as redirects.
6075 // Certain legacy apis that pre-date the response code expect this behavior
6076 // (Like Google Drive).
6077 TEST_F(URLRequestTestHTTP
, NoRedirectOn308WithoutLocationHeader
) {
6078 ASSERT_TRUE(test_server_
.Start());
6081 const GURL url
= test_server_
.GetURL("files/308-without-location-header");
6083 URLRequest
request(url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
6086 base::RunLoop().Run();
6087 EXPECT_EQ(URLRequestStatus::SUCCESS
, request
.status().status());
6088 EXPECT_EQ(OK
, request
.status().error());
6089 EXPECT_EQ(0, d
.received_redirect_count());
6090 EXPECT_EQ(308, request
.response_headers()->response_code());
6091 EXPECT_EQ("This is not a redirect.", d
.data_received());
6094 TEST_F(URLRequestTestHTTP
, Redirect302PreserveReferenceFragment
) {
6095 ASSERT_TRUE(test_server_
.Start());
6097 GURL
original_url(test_server_
.GetURL("files/redirect302-to-echo#fragment"));
6098 GURL
expected_url(test_server_
.GetURL("echo#fragment"));
6102 URLRequest
r(original_url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
6105 base::RunLoop().Run();
6107 EXPECT_EQ(2U, r
.url_chain().size());
6108 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
.status().status());
6109 EXPECT_EQ(net::OK
, r
.status().error());
6110 EXPECT_EQ(original_url
, r
.original_url());
6111 EXPECT_EQ(expected_url
, r
.url());
6115 TEST_F(URLRequestTestHTTP
, InterceptPost302RedirectGet
) {
6116 ASSERT_TRUE(test_server_
.Start());
6118 const char kData
[] = "hello world";
6121 URLRequest
req(test_server_
.GetURL("empty.html"),
6125 req
.set_method("POST");
6126 req
.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
6127 HttpRequestHeaders headers
;
6128 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
6129 base::UintToString(arraysize(kData
) - 1));
6130 req
.SetExtraRequestHeaders(headers
);
6132 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
6133 &req
, &default_network_delegate_
, test_server_
.GetURL("echo"),
6134 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
6135 AddTestInterceptor()->set_main_intercept_job(job
);
6138 base::RunLoop().Run();
6139 EXPECT_EQ("GET", req
.method());
6142 TEST_F(URLRequestTestHTTP
, InterceptPost307RedirectPost
) {
6143 ASSERT_TRUE(test_server_
.Start());
6145 const char kData
[] = "hello world";
6148 URLRequest
req(test_server_
.GetURL("empty.html"),
6152 req
.set_method("POST");
6153 req
.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
6154 HttpRequestHeaders headers
;
6155 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
6156 base::UintToString(arraysize(kData
) - 1));
6157 req
.SetExtraRequestHeaders(headers
);
6159 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
6160 &req
, &default_network_delegate_
, test_server_
.GetURL("echo"),
6161 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT
,
6162 "Very Good Reason");
6163 AddTestInterceptor()->set_main_intercept_job(job
);
6166 base::RunLoop().Run();
6167 EXPECT_EQ("POST", req
.method());
6168 EXPECT_EQ(kData
, d
.data_received());
6171 // Check that default A-L header is sent.
6172 TEST_F(URLRequestTestHTTP
, DefaultAcceptLanguage
) {
6173 ASSERT_TRUE(test_server_
.Start());
6175 StaticHttpUserAgentSettings
settings("en", std::string());
6176 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6177 TestURLRequestContext
context(true);
6178 context
.set_network_delegate(&network_delegate
);
6179 context
.set_http_user_agent_settings(&settings
);
6183 URLRequest
req(test_server_
.GetURL("echoheader?Accept-Language"),
6188 base::RunLoop().Run();
6189 EXPECT_EQ("en", d
.data_received());
6192 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6193 TEST_F(URLRequestTestHTTP
, EmptyAcceptLanguage
) {
6194 ASSERT_TRUE(test_server_
.Start());
6196 std::string empty_string
; // Avoid most vexing parse on line below.
6197 StaticHttpUserAgentSettings
settings(empty_string
, empty_string
);
6198 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6199 TestURLRequestContext
context(true);
6200 context
.set_network_delegate(&network_delegate
);
6202 // We override the language after initialization because empty entries
6203 // get overridden by Init().
6204 context
.set_http_user_agent_settings(&settings
);
6207 URLRequest
req(test_server_
.GetURL("echoheader?Accept-Language"),
6212 base::RunLoop().Run();
6213 EXPECT_EQ("None", d
.data_received());
6216 // Check that if request overrides the A-L header, the default is not appended.
6217 // See http://crbug.com/20894
6218 TEST_F(URLRequestTestHTTP
, OverrideAcceptLanguage
) {
6219 ASSERT_TRUE(test_server_
.Start());
6222 URLRequest
req(test_server_
.GetURL("echoheader?Accept-Language"),
6226 HttpRequestHeaders headers
;
6227 headers
.SetHeader(HttpRequestHeaders::kAcceptLanguage
, "ru");
6228 req
.SetExtraRequestHeaders(headers
);
6230 base::RunLoop().Run();
6231 EXPECT_EQ(std::string("ru"), d
.data_received());
6234 // Check that default A-E header is sent.
6235 TEST_F(URLRequestTestHTTP
, DefaultAcceptEncoding
) {
6236 ASSERT_TRUE(test_server_
.Start());
6239 URLRequest
req(test_server_
.GetURL("echoheader?Accept-Encoding"),
6243 HttpRequestHeaders headers
;
6244 req
.SetExtraRequestHeaders(headers
);
6246 base::RunLoop().Run();
6247 EXPECT_TRUE(ContainsString(d
.data_received(), "gzip"));
6250 // Check that if request overrides the A-E header, the default is not appended.
6251 // See http://crbug.com/47381
6252 TEST_F(URLRequestTestHTTP
, OverrideAcceptEncoding
) {
6253 ASSERT_TRUE(test_server_
.Start());
6256 URLRequest
req(test_server_
.GetURL("echoheader?Accept-Encoding"),
6260 HttpRequestHeaders headers
;
6261 headers
.SetHeader(HttpRequestHeaders::kAcceptEncoding
, "identity");
6262 req
.SetExtraRequestHeaders(headers
);
6264 base::RunLoop().Run();
6265 EXPECT_FALSE(ContainsString(d
.data_received(), "gzip"));
6266 EXPECT_TRUE(ContainsString(d
.data_received(), "identity"));
6269 // Check that setting the A-C header sends the proper header.
6270 TEST_F(URLRequestTestHTTP
, SetAcceptCharset
) {
6271 ASSERT_TRUE(test_server_
.Start());
6274 URLRequest
req(test_server_
.GetURL("echoheader?Accept-Charset"),
6278 HttpRequestHeaders headers
;
6279 headers
.SetHeader(HttpRequestHeaders::kAcceptCharset
, "koi-8r");
6280 req
.SetExtraRequestHeaders(headers
);
6282 base::RunLoop().Run();
6283 EXPECT_EQ(std::string("koi-8r"), d
.data_received());
6286 // Check that default User-Agent header is sent.
6287 TEST_F(URLRequestTestHTTP
, DefaultUserAgent
) {
6288 ASSERT_TRUE(test_server_
.Start());
6291 URLRequest
req(test_server_
.GetURL("echoheader?User-Agent"),
6296 base::RunLoop().Run();
6297 EXPECT_EQ(req
.context()->http_user_agent_settings()->GetUserAgent(),
6301 // Check that if request overrides the User-Agent header,
6302 // the default is not appended.
6303 TEST_F(URLRequestTestHTTP
, OverrideUserAgent
) {
6304 ASSERT_TRUE(test_server_
.Start());
6307 URLRequest
req(test_server_
.GetURL("echoheader?User-Agent"),
6311 HttpRequestHeaders headers
;
6312 headers
.SetHeader(HttpRequestHeaders::kUserAgent
, "Lynx (textmode)");
6313 req
.SetExtraRequestHeaders(headers
);
6315 base::RunLoop().Run();
6316 EXPECT_EQ(std::string("Lynx (textmode)"), d
.data_received());
6319 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6320 // User-Agent header to be sent but does not send the Accept-Language and
6321 // Accept-Charset headers.
6322 TEST_F(URLRequestTestHTTP
, EmptyHttpUserAgentSettings
) {
6323 ASSERT_TRUE(test_server_
.Start());
6325 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6326 TestURLRequestContext
context(true);
6327 context
.set_network_delegate(&network_delegate
);
6329 // We override the HttpUserAgentSettings after initialization because empty
6330 // entries get overridden by Init().
6331 context
.set_http_user_agent_settings(NULL
);
6334 const char* request
;
6335 const char* expected_response
;
6336 } tests
[] = { { "echoheader?Accept-Language", "None" },
6337 { "echoheader?Accept-Charset", "None" },
6338 { "echoheader?User-Agent", "" } };
6340 for (size_t i
= 0; i
< ARRAYSIZE_UNSAFE(tests
); i
++) {
6343 test_server_
.GetURL(tests
[i
].request
), DEFAULT_PRIORITY
, &d
, &context
);
6345 base::RunLoop().Run();
6346 EXPECT_EQ(tests
[i
].expected_response
, d
.data_received())
6347 << " Request = \"" << tests
[i
].request
<< "\"";
6351 // Make sure that URLRequest passes on its priority updates to
6352 // newly-created jobs after the first one.
6353 TEST_F(URLRequestTestHTTP
, SetSubsequentJobPriority
) {
6354 ASSERT_TRUE(test_server_
.Start());
6357 URLRequest
req(test_server_
.GetURL("empty.html"),
6361 EXPECT_EQ(DEFAULT_PRIORITY
, req
.priority());
6363 scoped_refptr
<URLRequestRedirectJob
> redirect_job
=
6364 new URLRequestRedirectJob(
6365 &req
, &default_network_delegate_
, test_server_
.GetURL("echo"),
6366 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
6367 AddTestInterceptor()->set_main_intercept_job(redirect_job
.get());
6369 req
.SetPriority(LOW
);
6371 EXPECT_TRUE(req
.is_pending());
6373 scoped_refptr
<URLRequestTestJob
> job
=
6374 new URLRequestTestJob(&req
, &default_network_delegate_
);
6375 AddTestInterceptor()->set_main_intercept_job(job
.get());
6377 // Should trigger |job| to be started.
6378 base::RunLoop().Run();
6379 EXPECT_EQ(LOW
, job
->priority());
6382 // Check that creating a network request while entering/exiting suspend mode
6383 // fails as it should. This is the only case where an HttpTransactionFactory
6384 // does not return an HttpTransaction.
6385 TEST_F(URLRequestTestHTTP
, NetworkSuspendTest
) {
6386 // Create a new HttpNetworkLayer that thinks it's suspended.
6387 HttpNetworkSession::Params params
;
6388 params
.host_resolver
= default_context_
.host_resolver();
6389 params
.cert_verifier
= default_context_
.cert_verifier();
6390 params
.transport_security_state
= default_context_
.transport_security_state();
6391 params
.proxy_service
= default_context_
.proxy_service();
6392 params
.ssl_config_service
= default_context_
.ssl_config_service();
6393 params
.http_auth_handler_factory
=
6394 default_context_
.http_auth_handler_factory();
6395 params
.network_delegate
= &default_network_delegate_
;
6396 params
.http_server_properties
= default_context_
.http_server_properties();
6397 scoped_ptr
<HttpNetworkLayer
> network_layer(
6398 new HttpNetworkLayer(new HttpNetworkSession(params
)));
6399 network_layer
->OnSuspend();
6401 HttpCache
http_cache(network_layer
.release(), default_context_
.net_log(),
6402 HttpCache::DefaultBackend::InMemory(0));
6404 TestURLRequestContext
context(true);
6405 context
.set_http_transaction_factory(&http_cache
);
6409 URLRequest
req(GURL("http://127.0.0.1/"),
6414 base::RunLoop().Run();
6416 EXPECT_TRUE(d
.request_failed());
6417 EXPECT_EQ(URLRequestStatus::FAILED
, req
.status().status());
6418 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED
, req
.status().error());
6421 // Check that creating a network request while entering/exiting suspend mode
6422 // fails as it should in the case there is no cache. This is the only case
6423 // where an HttpTransactionFactory does not return an HttpTransaction.
6424 TEST_F(URLRequestTestHTTP
, NetworkSuspendTestNoCache
) {
6425 // Create a new HttpNetworkLayer that thinks it's suspended.
6426 HttpNetworkSession::Params params
;
6427 params
.host_resolver
= default_context_
.host_resolver();
6428 params
.cert_verifier
= default_context_
.cert_verifier();
6429 params
.transport_security_state
= default_context_
.transport_security_state();
6430 params
.proxy_service
= default_context_
.proxy_service();
6431 params
.ssl_config_service
= default_context_
.ssl_config_service();
6432 params
.http_auth_handler_factory
=
6433 default_context_
.http_auth_handler_factory();
6434 params
.network_delegate
= &default_network_delegate_
;
6435 params
.http_server_properties
= default_context_
.http_server_properties();
6436 HttpNetworkLayer
network_layer(new HttpNetworkSession(params
));
6437 network_layer
.OnSuspend();
6439 TestURLRequestContext
context(true);
6440 context
.set_http_transaction_factory(&network_layer
);
6444 URLRequest
req(GURL("http://127.0.0.1/"),
6449 base::RunLoop().Run();
6451 EXPECT_TRUE(d
.request_failed());
6452 EXPECT_EQ(URLRequestStatus::FAILED
, req
.status().status());
6453 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED
, req
.status().error());
6456 class HTTPSRequestTest
: public testing::Test
{
6458 HTTPSRequestTest() : default_context_(true) {
6459 default_context_
.set_network_delegate(&default_network_delegate_
);
6460 default_context_
.Init();
6462 virtual ~HTTPSRequestTest() {}
6465 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
6466 TestURLRequestContext default_context_
;
6469 TEST_F(HTTPSRequestTest
, HTTPSGetTest
) {
6470 SpawnedTestServer
test_server(
6471 SpawnedTestServer::TYPE_HTTPS
,
6472 SpawnedTestServer::kLocalhost
,
6473 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6474 ASSERT_TRUE(test_server
.Start());
6478 URLRequest
r(test_server
.GetURL(std::string()),
6483 EXPECT_TRUE(r
.is_pending());
6485 base::RunLoop().Run();
6487 EXPECT_EQ(1, d
.response_started_count());
6488 EXPECT_FALSE(d
.received_data_before_response());
6489 EXPECT_NE(0, d
.bytes_received());
6490 CheckSSLInfo(r
.ssl_info());
6491 EXPECT_EQ(test_server
.host_port_pair().host(),
6492 r
.GetSocketAddress().host());
6493 EXPECT_EQ(test_server
.host_port_pair().port(),
6494 r
.GetSocketAddress().port());
6498 TEST_F(HTTPSRequestTest
, HTTPSMismatchedTest
) {
6499 SpawnedTestServer::SSLOptions
ssl_options(
6500 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
6501 SpawnedTestServer
test_server(
6502 SpawnedTestServer::TYPE_HTTPS
,
6504 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6505 ASSERT_TRUE(test_server
.Start());
6507 bool err_allowed
= true;
6508 for (int i
= 0; i
< 2 ; i
++, err_allowed
= !err_allowed
) {
6511 d
.set_allow_certificate_errors(err_allowed
);
6512 URLRequest
r(test_server
.GetURL(std::string()),
6518 EXPECT_TRUE(r
.is_pending());
6520 base::RunLoop().Run();
6522 EXPECT_EQ(1, d
.response_started_count());
6523 EXPECT_FALSE(d
.received_data_before_response());
6524 EXPECT_TRUE(d
.have_certificate_errors());
6526 EXPECT_NE(0, d
.bytes_received());
6527 CheckSSLInfo(r
.ssl_info());
6529 EXPECT_EQ(0, d
.bytes_received());
6535 TEST_F(HTTPSRequestTest
, HTTPSExpiredTest
) {
6536 SpawnedTestServer::SSLOptions
ssl_options(
6537 SpawnedTestServer::SSLOptions::CERT_EXPIRED
);
6538 SpawnedTestServer
test_server(
6539 SpawnedTestServer::TYPE_HTTPS
,
6541 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6542 ASSERT_TRUE(test_server
.Start());
6544 // Iterate from false to true, just so that we do the opposite of the
6545 // previous test in order to increase test coverage.
6546 bool err_allowed
= false;
6547 for (int i
= 0; i
< 2 ; i
++, err_allowed
= !err_allowed
) {
6550 d
.set_allow_certificate_errors(err_allowed
);
6551 URLRequest
r(test_server
.GetURL(std::string()),
6557 EXPECT_TRUE(r
.is_pending());
6559 base::RunLoop().Run();
6561 EXPECT_EQ(1, d
.response_started_count());
6562 EXPECT_FALSE(d
.received_data_before_response());
6563 EXPECT_TRUE(d
.have_certificate_errors());
6565 EXPECT_NE(0, d
.bytes_received());
6566 CheckSSLInfo(r
.ssl_info());
6568 EXPECT_EQ(0, d
.bytes_received());
6574 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
6576 TEST_F(HTTPSRequestTest
, TLSv1Fallback
) {
6577 // The OpenSSL library in use may not support TLS 1.1.
6578 #if !defined(USE_OPENSSL)
6579 EXPECT_GT(kDefaultSSLVersionMax
, SSL_PROTOCOL_VERSION_TLS1
);
6581 if (kDefaultSSLVersionMax
<= SSL_PROTOCOL_VERSION_TLS1
)
6584 SpawnedTestServer::SSLOptions
ssl_options(
6585 SpawnedTestServer::SSLOptions::CERT_OK
);
6586 ssl_options
.tls_intolerant
=
6587 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
6588 SpawnedTestServer
test_server(
6589 SpawnedTestServer::TYPE_HTTPS
,
6591 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6592 ASSERT_TRUE(test_server
.Start());
6595 TestURLRequestContext
context(true);
6597 d
.set_allow_certificate_errors(true);
6599 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context
);
6602 base::RunLoop().Run();
6604 EXPECT_EQ(1, d
.response_started_count());
6605 EXPECT_NE(0, d
.bytes_received());
6606 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1
),
6607 SSLConnectionStatusToVersion(r
.ssl_info().connection_status
));
6608 EXPECT_TRUE(r
.ssl_info().connection_status
& SSL_CONNECTION_VERSION_FALLBACK
);
6611 // Tests that we don't fallback with servers that implement TLS_FALLBACK_SCSV.
6612 #if defined(USE_OPENSSL)
6613 TEST_F(HTTPSRequestTest
, DISABLED_FallbackSCSV
) {
6615 TEST_F(HTTPSRequestTest
, FallbackSCSV
) {
6617 SpawnedTestServer::SSLOptions
ssl_options(
6618 SpawnedTestServer::SSLOptions::CERT_OK
);
6619 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
6620 // a version fallback.
6621 ssl_options
.tls_intolerant
=
6622 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
6623 // Have the server process TLS_FALLBACK_SCSV so that version fallback
6624 // connections are rejected.
6625 ssl_options
.fallback_scsv_enabled
= true;
6627 SpawnedTestServer
test_server(
6628 SpawnedTestServer::TYPE_HTTPS
,
6630 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6631 ASSERT_TRUE(test_server
.Start());
6634 TestURLRequestContext
context(true);
6636 d
.set_allow_certificate_errors(true);
6638 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context
);
6641 base::RunLoop().Run();
6643 EXPECT_EQ(1, d
.response_started_count());
6644 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
6645 // intolerance. If the fallback SCSV is processed when the original error
6646 // that caused the fallback should be returned, which should be
6647 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
6648 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
, r
.status().error());
6651 // This tests that a load of www.google.com with a certificate error sets
6652 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
6653 // the interstitial to be fatal.
6654 TEST_F(HTTPSRequestTest
, HTTPSPreloadedHSTSTest
) {
6655 SpawnedTestServer::SSLOptions
ssl_options(
6656 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
6657 SpawnedTestServer
test_server(
6658 SpawnedTestServer::TYPE_HTTPS
,
6660 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6661 ASSERT_TRUE(test_server
.Start());
6663 // We require that the URL be www.google.com in order to pick up the
6664 // preloaded HSTS entries in the TransportSecurityState. This means that we
6665 // have to use a MockHostResolver in order to direct www.google.com to the
6666 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6668 MockHostResolver host_resolver
;
6669 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6670 TestURLRequestContext
context(true);
6671 context
.set_network_delegate(&network_delegate
);
6672 context
.set_host_resolver(&host_resolver
);
6673 TransportSecurityState transport_security_state
;
6674 context
.set_transport_security_state(&transport_security_state
);
6678 URLRequest
r(GURL(base::StringPrintf("https://www.google.com:%d",
6679 test_server
.host_port_pair().port())),
6685 EXPECT_TRUE(r
.is_pending());
6687 base::RunLoop().Run();
6689 EXPECT_EQ(1, d
.response_started_count());
6690 EXPECT_FALSE(d
.received_data_before_response());
6691 EXPECT_TRUE(d
.have_certificate_errors());
6692 EXPECT_TRUE(d
.certificate_errors_are_fatal());
6695 // This tests that cached HTTPS page loads do not cause any updates to the
6696 // TransportSecurityState.
6697 TEST_F(HTTPSRequestTest
, HTTPSErrorsNoClobberTSSTest
) {
6698 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6699 // matter. It just has to be any error.
6700 SpawnedTestServer::SSLOptions
ssl_options(
6701 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
6702 SpawnedTestServer
test_server(
6703 SpawnedTestServer::TYPE_HTTPS
,
6705 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6706 ASSERT_TRUE(test_server
.Start());
6708 // We require that the URL be www.google.com in order to pick up the static
6709 // and dynamic STS and PKP entries in the TransportSecurityState. This means
6710 // that we have to use a MockHostResolver in order to direct www.google.com to
6711 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6713 MockHostResolver host_resolver
;
6714 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6715 TestURLRequestContext
context(true);
6716 context
.set_network_delegate(&network_delegate
);
6717 context
.set_host_resolver(&host_resolver
);
6718 TransportSecurityState transport_security_state
;
6720 TransportSecurityState::DomainState static_domain_state
;
6721 EXPECT_TRUE(transport_security_state
.GetStaticDomainState(
6722 "www.google.com", true, &static_domain_state
));
6723 context
.set_transport_security_state(&transport_security_state
);
6726 TransportSecurityState::DomainState dynamic_domain_state
;
6727 EXPECT_FALSE(transport_security_state
.GetDynamicDomainState(
6728 "www.google.com", &dynamic_domain_state
));
6731 URLRequest
r(GURL(base::StringPrintf("https://www.google.com:%d",
6732 test_server
.host_port_pair().port())),
6738 EXPECT_TRUE(r
.is_pending());
6740 base::RunLoop().Run();
6742 EXPECT_EQ(1, d
.response_started_count());
6743 EXPECT_FALSE(d
.received_data_before_response());
6744 EXPECT_TRUE(d
.have_certificate_errors());
6745 EXPECT_TRUE(d
.certificate_errors_are_fatal());
6747 // Get a fresh copy of the states, and check that they haven't changed.
6748 TransportSecurityState::DomainState new_static_domain_state
;
6749 EXPECT_TRUE(transport_security_state
.GetStaticDomainState(
6750 "www.google.com", true, &new_static_domain_state
));
6751 TransportSecurityState::DomainState new_dynamic_domain_state
;
6752 EXPECT_FALSE(transport_security_state
.GetDynamicDomainState(
6753 "www.google.com", &new_dynamic_domain_state
));
6755 EXPECT_EQ(new_static_domain_state
.sts
.upgrade_mode
,
6756 static_domain_state
.sts
.upgrade_mode
);
6757 EXPECT_EQ(new_static_domain_state
.sts
.include_subdomains
,
6758 static_domain_state
.sts
.include_subdomains
);
6759 EXPECT_EQ(new_static_domain_state
.pkp
.include_subdomains
,
6760 static_domain_state
.pkp
.include_subdomains
);
6761 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state
.pkp
.spki_hashes
,
6762 static_domain_state
.pkp
.spki_hashes
));
6763 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state
.pkp
.bad_spki_hashes
,
6764 static_domain_state
.pkp
.bad_spki_hashes
));
6767 // Make sure HSTS preserves a POST request's method and body.
6768 TEST_F(HTTPSRequestTest
, HSTSPreservesPosts
) {
6769 static const char kData
[] = "hello world";
6771 SpawnedTestServer::SSLOptions
ssl_options(
6772 SpawnedTestServer::SSLOptions::CERT_OK
);
6773 SpawnedTestServer
test_server(
6774 SpawnedTestServer::TYPE_HTTPS
,
6776 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6777 ASSERT_TRUE(test_server
.Start());
6780 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6781 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
6782 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6784 MockHostResolver host_resolver
;
6786 // Force https for www.somewhere.com.
6787 TransportSecurityState transport_security_state
;
6788 base::Time expiry
= base::Time::Now() + base::TimeDelta::FromDays(1000);
6789 bool include_subdomains
= false;
6790 transport_security_state
.AddHSTS("www.somewhere.com", expiry
,
6791 include_subdomains
);
6793 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6795 TestURLRequestContext
context(true);
6796 context
.set_host_resolver(&host_resolver
);
6797 context
.set_transport_security_state(&transport_security_state
);
6798 context
.set_network_delegate(&network_delegate
);
6802 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6803 // cause a certificate error. Ignore the error.
6804 d
.set_allow_certificate_errors(true);
6806 URLRequest
req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6807 test_server
.host_port_pair().port())),
6811 req
.set_method("POST");
6812 req
.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
6815 base::RunLoop().Run();
6817 EXPECT_EQ("https", req
.url().scheme());
6818 EXPECT_EQ("POST", req
.method());
6819 EXPECT_EQ(kData
, d
.data_received());
6821 LoadTimingInfo load_timing_info
;
6822 network_delegate
.GetLoadTimingInfoBeforeRedirect(&load_timing_info
);
6823 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6824 TestLoadTimingCacheHitNoNetwork(load_timing_info
);
6827 TEST_F(HTTPSRequestTest
, SSLv3Fallback
) {
6828 SpawnedTestServer::SSLOptions
ssl_options(
6829 SpawnedTestServer::SSLOptions::CERT_OK
);
6830 ssl_options
.tls_intolerant
=
6831 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
6832 SpawnedTestServer
test_server(
6833 SpawnedTestServer::TYPE_HTTPS
,
6835 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6836 ASSERT_TRUE(test_server
.Start());
6839 TestURLRequestContext
context(true);
6841 d
.set_allow_certificate_errors(true);
6843 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context
);
6846 base::RunLoop().Run();
6848 EXPECT_EQ(1, d
.response_started_count());
6849 EXPECT_NE(0, d
.bytes_received());
6850 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3
),
6851 SSLConnectionStatusToVersion(r
.ssl_info().connection_status
));
6852 EXPECT_TRUE(r
.ssl_info().connection_status
& SSL_CONNECTION_VERSION_FALLBACK
);
6857 class SSLClientAuthTestDelegate
: public TestDelegate
{
6859 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6861 virtual void OnCertificateRequested(
6862 URLRequest
* request
,
6863 SSLCertRequestInfo
* cert_request_info
) OVERRIDE
{
6864 on_certificate_requested_count_
++;
6865 base::MessageLoop::current()->Quit();
6867 int on_certificate_requested_count() {
6868 return on_certificate_requested_count_
;
6871 int on_certificate_requested_count_
;
6876 // TODO(davidben): Test the rest of the code. Specifically,
6877 // - Filtering which certificates to select.
6878 // - Sending a certificate back.
6879 // - Getting a certificate request in an SSL renegotiation sending the
6881 TEST_F(HTTPSRequestTest
, ClientAuthTest
) {
6882 SpawnedTestServer::SSLOptions ssl_options
;
6883 ssl_options
.request_client_certificate
= true;
6884 SpawnedTestServer
test_server(
6885 SpawnedTestServer::TYPE_HTTPS
,
6887 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6888 ASSERT_TRUE(test_server
.Start());
6890 SSLClientAuthTestDelegate d
;
6892 URLRequest
r(test_server
.GetURL(std::string()),
6898 EXPECT_TRUE(r
.is_pending());
6900 base::RunLoop().Run();
6902 EXPECT_EQ(1, d
.on_certificate_requested_count());
6903 EXPECT_FALSE(d
.received_data_before_response());
6904 EXPECT_EQ(0, d
.bytes_received());
6906 // Send no certificate.
6907 // TODO(davidben): Get temporary client cert import (with keys) working on
6908 // all platforms so we can test sending a cert as well.
6909 r
.ContinueWithCertificate(NULL
);
6911 base::RunLoop().Run();
6913 EXPECT_EQ(1, d
.response_started_count());
6914 EXPECT_FALSE(d
.received_data_before_response());
6915 EXPECT_NE(0, d
.bytes_received());
6919 TEST_F(HTTPSRequestTest
, ResumeTest
) {
6920 // Test that we attempt a session resume when making two connections to the
6922 SpawnedTestServer::SSLOptions ssl_options
;
6923 ssl_options
.record_resume
= true;
6924 SpawnedTestServer
test_server(
6925 SpawnedTestServer::TYPE_HTTPS
,
6927 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6928 ASSERT_TRUE(test_server
.Start());
6930 SSLClientSocket::ClearSessionCache();
6934 URLRequest
r(test_server
.GetURL("ssl-session-cache"),
6940 EXPECT_TRUE(r
.is_pending());
6942 base::RunLoop().Run();
6944 EXPECT_EQ(1, d
.response_started_count());
6947 reinterpret_cast<HttpCache
*>(default_context_
.http_transaction_factory())->
6948 CloseAllConnections();
6952 URLRequest
r(test_server
.GetURL("ssl-session-cache"),
6958 EXPECT_TRUE(r
.is_pending());
6960 base::RunLoop().Run();
6962 // The response will look like;
6967 // With a newline at the end which makes the split think that there are
6970 EXPECT_EQ(1, d
.response_started_count());
6971 std::vector
<std::string
> lines
;
6972 base::SplitString(d
.data_received(), '\n', &lines
);
6973 ASSERT_EQ(4u, lines
.size()) << d
.data_received();
6975 std::string session_id
;
6977 for (size_t i
= 0; i
< 2; i
++) {
6978 std::vector
<std::string
> parts
;
6979 base::SplitString(lines
[i
], '\t', &parts
);
6980 ASSERT_EQ(2u, parts
.size());
6982 EXPECT_EQ("insert", parts
[0]);
6983 session_id
= parts
[1];
6985 EXPECT_EQ("lookup", parts
[0]);
6986 EXPECT_EQ(session_id
, parts
[1]);
6992 TEST_F(HTTPSRequestTest
, SSLSessionCacheShardTest
) {
6993 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6995 SpawnedTestServer::SSLOptions ssl_options
;
6996 ssl_options
.record_resume
= true;
6997 SpawnedTestServer
test_server(
6998 SpawnedTestServer::TYPE_HTTPS
,
7000 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7001 ASSERT_TRUE(test_server
.Start());
7003 SSLClientSocket::ClearSessionCache();
7007 URLRequest
r(test_server
.GetURL("ssl-session-cache"),
7013 EXPECT_TRUE(r
.is_pending());
7015 base::RunLoop().Run();
7017 EXPECT_EQ(1, d
.response_started_count());
7020 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7021 HttpNetworkSession::Params params
;
7022 params
.host_resolver
= default_context_
.host_resolver();
7023 params
.cert_verifier
= default_context_
.cert_verifier();
7024 params
.transport_security_state
= default_context_
.transport_security_state();
7025 params
.proxy_service
= default_context_
.proxy_service();
7026 params
.ssl_config_service
= default_context_
.ssl_config_service();
7027 params
.http_auth_handler_factory
=
7028 default_context_
.http_auth_handler_factory();
7029 params
.network_delegate
= &default_network_delegate_
;
7030 params
.http_server_properties
= default_context_
.http_server_properties();
7031 params
.ssl_session_cache_shard
= "alternate";
7033 scoped_ptr
<net::HttpCache
> cache(new net::HttpCache(
7034 new net::HttpNetworkSession(params
),
7035 net::HttpCache::DefaultBackend::InMemory(0)));
7037 default_context_
.set_http_transaction_factory(cache
.get());
7041 URLRequest
r(test_server
.GetURL("ssl-session-cache"),
7047 EXPECT_TRUE(r
.is_pending());
7049 base::RunLoop().Run();
7051 // The response will look like;
7055 // With a newline at the end which makes the split think that there are
7058 EXPECT_EQ(1, d
.response_started_count());
7059 std::vector
<std::string
> lines
;
7060 base::SplitString(d
.data_received(), '\n', &lines
);
7061 ASSERT_EQ(3u, lines
.size());
7063 std::string session_id
;
7064 for (size_t i
= 0; i
< 2; i
++) {
7065 std::vector
<std::string
> parts
;
7066 base::SplitString(lines
[i
], '\t', &parts
);
7067 ASSERT_EQ(2u, parts
.size());
7068 EXPECT_EQ("insert", parts
[0]);
7070 session_id
= parts
[1];
7072 EXPECT_NE(session_id
, parts
[1]);
7078 class HTTPSSessionTest
: public testing::Test
{
7080 HTTPSSessionTest() : default_context_(true) {
7081 cert_verifier_
.set_default_result(net::OK
);
7083 default_context_
.set_network_delegate(&default_network_delegate_
);
7084 default_context_
.set_cert_verifier(&cert_verifier_
);
7085 default_context_
.Init();
7087 virtual ~HTTPSSessionTest() {}
7090 MockCertVerifier cert_verifier_
;
7091 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
7092 TestURLRequestContext default_context_
;
7095 // Tests that session resumption is not attempted if an invalid certificate
7097 TEST_F(HTTPSSessionTest
, DontResumeSessionsForInvalidCertificates
) {
7098 SpawnedTestServer::SSLOptions ssl_options
;
7099 ssl_options
.record_resume
= true;
7100 SpawnedTestServer
test_server(
7101 SpawnedTestServer::TYPE_HTTPS
,
7103 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7104 ASSERT_TRUE(test_server
.Start());
7106 SSLClientSocket::ClearSessionCache();
7108 // Simulate the certificate being expired and attempt a connection.
7109 cert_verifier_
.set_default_result(net::ERR_CERT_DATE_INVALID
);
7112 URLRequest
r(test_server
.GetURL("ssl-session-cache"),
7118 EXPECT_TRUE(r
.is_pending());
7120 base::RunLoop().Run();
7122 EXPECT_EQ(1, d
.response_started_count());
7125 reinterpret_cast<HttpCache
*>(default_context_
.http_transaction_factory())->
7126 CloseAllConnections();
7128 // Now change the certificate to be acceptable (so that the response is
7129 // loaded), and ensure that no session id is presented to the peer.
7130 cert_verifier_
.set_default_result(net::OK
);
7133 URLRequest
r(test_server
.GetURL("ssl-session-cache"),
7139 EXPECT_TRUE(r
.is_pending());
7141 base::RunLoop().Run();
7143 // The response will look like;
7147 // With a newline at the end which makes the split think that there are
7150 // If a session was presented (eg: a bug), then the response would look
7156 EXPECT_EQ(1, d
.response_started_count());
7157 std::vector
<std::string
> lines
;
7158 base::SplitString(d
.data_received(), '\n', &lines
);
7159 ASSERT_EQ(3u, lines
.size()) << d
.data_received();
7161 std::string session_id
;
7162 for (size_t i
= 0; i
< 2; i
++) {
7163 std::vector
<std::string
> parts
;
7164 base::SplitString(lines
[i
], '\t', &parts
);
7165 ASSERT_EQ(2u, parts
.size());
7166 EXPECT_EQ("insert", parts
[0]);
7168 session_id
= parts
[1];
7170 EXPECT_NE(session_id
, parts
[1]);
7176 class TestSSLConfigService
: public SSLConfigService
{
7178 TestSSLConfigService(bool ev_enabled
,
7179 bool online_rev_checking
,
7180 bool rev_checking_required_local_anchors
)
7181 : ev_enabled_(ev_enabled
),
7182 online_rev_checking_(online_rev_checking
),
7183 rev_checking_required_local_anchors_(
7184 rev_checking_required_local_anchors
) {}
7186 // SSLConfigService:
7187 virtual void GetSSLConfig(SSLConfig
* config
) OVERRIDE
{
7188 *config
= SSLConfig();
7189 config
->rev_checking_enabled
= online_rev_checking_
;
7190 config
->verify_ev_cert
= ev_enabled_
;
7191 config
->rev_checking_required_local_anchors
=
7192 rev_checking_required_local_anchors_
;
7196 virtual ~TestSSLConfigService() {}
7199 const bool ev_enabled_
;
7200 const bool online_rev_checking_
;
7201 const bool rev_checking_required_local_anchors_
;
7204 // This the fingerprint of the "Testing CA" certificate used by the testserver.
7205 // See net/data/ssl/certificates/ocsp-test-root.pem.
7206 static const SHA1HashValue kOCSPTestCertFingerprint
=
7207 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7208 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7210 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7212 static const SHA256HashValue kOCSPTestCertSPKI
= { {
7213 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7214 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7215 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7216 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7219 // This is the policy OID contained in the certificates that testserver
7221 static const char kOCSPTestCertPolicy
[] = "1.3.6.1.4.1.11129.2.4.1";
7223 class HTTPSOCSPTest
: public HTTPSRequestTest
{
7228 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7229 kOCSPTestCertFingerprint
,
7230 kOCSPTestCertPolicy
)) {
7233 virtual void SetUp() OVERRIDE
{
7234 SetupContext(&context_
);
7237 scoped_refptr
<net::X509Certificate
> root_cert
=
7238 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
7239 CHECK_NE(static_cast<X509Certificate
*>(NULL
), root_cert
);
7240 test_root_
.reset(new ScopedTestRoot(root_cert
.get()));
7242 #if defined(USE_NSS) || defined(OS_IOS)
7243 SetURLRequestContextForNSSHttpIO(&context_
);
7244 EnsureNSSHttpIOInit();
7248 void DoConnection(const SpawnedTestServer::SSLOptions
& ssl_options
,
7249 CertStatus
* out_cert_status
) {
7250 // We always overwrite out_cert_status.
7251 *out_cert_status
= 0;
7252 SpawnedTestServer
test_server(
7253 SpawnedTestServer::TYPE_HTTPS
,
7255 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7256 ASSERT_TRUE(test_server
.Start());
7259 d
.set_allow_certificate_errors(true);
7261 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, &context_
);
7264 base::RunLoop().Run();
7266 EXPECT_EQ(1, d
.response_started_count());
7267 *out_cert_status
= r
.ssl_info().cert_status
;
7270 virtual ~HTTPSOCSPTest() {
7271 #if defined(USE_NSS) || defined(OS_IOS)
7272 ShutdownNSSHttpIO();
7277 // SetupContext configures the URLRequestContext that will be used for making
7278 // connetions to testserver. This can be overridden in test subclasses for
7279 // different behaviour.
7280 virtual void SetupContext(URLRequestContext
* context
) {
7281 context
->set_ssl_config_service(
7282 new TestSSLConfigService(true /* check for EV */,
7283 true /* online revocation checking */,
7284 false /* require rev. checking for local
7288 scoped_ptr
<ScopedTestRoot
> test_root_
;
7289 TestURLRequestContext context_
;
7290 scoped_ptr
<ScopedTestEVPolicy
> ev_test_policy_
;
7293 static CertStatus
ExpectedCertStatusForFailedOnlineRevocationCheck() {
7295 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7296 // have that ability on other platforms.
7297 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION
;
7303 // SystemSupportsHardFailRevocationChecking returns true iff the current
7304 // operating system supports revocation checking and can distinguish between
7305 // situations where a given certificate lacks any revocation information (eg:
7306 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7307 // revocation information cannot be obtained (eg: the CRL was unreachable).
7308 // If it does not, then tests which rely on 'hard fail' behaviour should be
7310 static bool SystemSupportsHardFailRevocationChecking() {
7311 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7318 // SystemUsesChromiumEVMetadata returns true iff the current operating system
7319 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7320 // several tests are effected because our testing EV certificate won't be
7321 // recognised as EV.
7322 static bool SystemUsesChromiumEVMetadata() {
7323 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
7324 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7326 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7327 // On OS X and Android, we use the system to tell us whether a certificate is
7328 // EV or not and the system won't recognise our testing root.
7335 static bool SystemSupportsOCSP() {
7336 #if defined(USE_OPENSSL)
7337 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7339 #elif defined(OS_WIN)
7340 return base::win::GetVersion() >= base::win::VERSION_VISTA
;
7341 #elif defined(OS_ANDROID)
7342 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7349 TEST_F(HTTPSOCSPTest
, Valid
) {
7350 if (!SystemSupportsOCSP()) {
7351 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7355 SpawnedTestServer::SSLOptions
ssl_options(
7356 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7357 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
7359 CertStatus cert_status
;
7360 DoConnection(ssl_options
, &cert_status
);
7362 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7364 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7365 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
7367 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7370 TEST_F(HTTPSOCSPTest
, Revoked
) {
7371 if (!SystemSupportsOCSP()) {
7372 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7376 SpawnedTestServer::SSLOptions
ssl_options(
7377 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7378 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
7380 CertStatus cert_status
;
7381 DoConnection(ssl_options
, &cert_status
);
7383 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
7384 // Doesn't pass on OS X yet for reasons that need to be investigated.
7385 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
7387 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7388 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7391 TEST_F(HTTPSOCSPTest
, Invalid
) {
7392 if (!SystemSupportsOCSP()) {
7393 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7397 SpawnedTestServer::SSLOptions
ssl_options(
7398 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7399 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7401 CertStatus cert_status
;
7402 DoConnection(ssl_options
, &cert_status
);
7404 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7405 cert_status
& CERT_STATUS_ALL_ERRORS
);
7407 // Without a positive OCSP response, we shouldn't show the EV status.
7408 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7409 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7412 class HTTPSHardFailTest
: public HTTPSOCSPTest
{
7414 virtual void SetupContext(URLRequestContext
* context
) OVERRIDE
{
7415 context
->set_ssl_config_service(
7416 new TestSSLConfigService(false /* check for EV */,
7417 false /* online revocation checking */,
7418 true /* require rev. checking for local
7424 TEST_F(HTTPSHardFailTest
, FailsOnOCSPInvalid
) {
7425 if (!SystemSupportsOCSP()) {
7426 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7430 if (!SystemSupportsHardFailRevocationChecking()) {
7431 LOG(WARNING
) << "Skipping test because system doesn't support hard fail "
7432 << "revocation checking";
7436 SpawnedTestServer::SSLOptions
ssl_options(
7437 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7438 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7440 CertStatus cert_status
;
7441 DoConnection(ssl_options
, &cert_status
);
7443 EXPECT_EQ(CERT_STATUS_REVOKED
,
7444 cert_status
& CERT_STATUS_REVOKED
);
7446 // Without a positive OCSP response, we shouldn't show the EV status.
7447 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7450 class HTTPSEVCRLSetTest
: public HTTPSOCSPTest
{
7452 virtual void SetupContext(URLRequestContext
* context
) OVERRIDE
{
7453 context
->set_ssl_config_service(
7454 new TestSSLConfigService(true /* check for EV */,
7455 false /* online revocation checking */,
7456 false /* require rev. checking for local
7461 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndInvalidOCSP
) {
7462 if (!SystemSupportsOCSP()) {
7463 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7467 SpawnedTestServer::SSLOptions
ssl_options(
7468 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7469 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7470 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
7472 CertStatus cert_status
;
7473 DoConnection(ssl_options
, &cert_status
);
7475 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7476 cert_status
& CERT_STATUS_ALL_ERRORS
);
7478 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7479 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7480 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7483 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndRevokedOCSP
) {
7484 if (!SystemSupportsOCSP()) {
7485 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7489 SpawnedTestServer::SSLOptions
ssl_options(
7490 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7491 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
7492 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
7494 CertStatus cert_status
;
7495 DoConnection(ssl_options
, &cert_status
);
7497 // Currently only works for Windows. When using NSS or OS X, it's not
7498 // possible to determine whether the check failed because of actual
7499 // revocation or because there was an OCSP failure.
7501 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
7503 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7506 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7507 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7508 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7511 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndGoodOCSP
) {
7512 if (!SystemSupportsOCSP()) {
7513 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7517 SpawnedTestServer::SSLOptions
ssl_options(
7518 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7519 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
7520 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
7522 CertStatus cert_status
;
7523 DoConnection(ssl_options
, &cert_status
);
7525 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7527 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7528 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
7529 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7530 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7533 TEST_F(HTTPSEVCRLSetTest
, ExpiredCRLSet
) {
7534 if (!SystemSupportsOCSP()) {
7535 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7539 SpawnedTestServer::SSLOptions
ssl_options(
7540 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7541 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7542 SSLConfigService::SetCRLSet(
7543 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
7545 CertStatus cert_status
;
7546 DoConnection(ssl_options
, &cert_status
);
7548 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7549 cert_status
& CERT_STATUS_ALL_ERRORS
);
7551 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7552 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7553 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7556 TEST_F(HTTPSEVCRLSetTest
, FreshCRLSetCovered
) {
7557 if (!SystemSupportsOCSP()) {
7558 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7562 SpawnedTestServer::SSLOptions
ssl_options(
7563 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7564 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7565 SSLConfigService::SetCRLSet(
7566 scoped_refptr
<CRLSet
>(CRLSet::ForTesting(
7567 false, &kOCSPTestCertSPKI
, "")));
7569 CertStatus cert_status
;
7570 DoConnection(ssl_options
, &cert_status
);
7572 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7573 // revocation check for EV.
7574 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7575 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7576 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
7578 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7581 TEST_F(HTTPSEVCRLSetTest
, FreshCRLSetNotCovered
) {
7582 if (!SystemSupportsOCSP()) {
7583 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7587 SpawnedTestServer::SSLOptions
ssl_options(
7588 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7589 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7590 SSLConfigService::SetCRLSet(
7591 scoped_refptr
<CRLSet
>(CRLSet::EmptyCRLSetForTesting()));
7593 CertStatus cert_status
= 0;
7594 DoConnection(ssl_options
, &cert_status
);
7596 // Even with a fresh CRLSet, we should still do online revocation checks when
7597 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7599 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7600 cert_status
& CERT_STATUS_ALL_ERRORS
);
7602 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7603 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7604 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7607 TEST_F(HTTPSEVCRLSetTest
, ExpiredCRLSetAndRevokedNonEVCert
) {
7608 // Test that when EV verification is requested, but online revocation
7609 // checking is disabled, and the leaf certificate is not in fact EV, that
7610 // no revocation checking actually happens.
7611 if (!SystemSupportsOCSP()) {
7612 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7616 // Unmark the certificate's OID as EV, which should disable revocation
7617 // checking (as per the user preference)
7618 ev_test_policy_
.reset();
7620 SpawnedTestServer::SSLOptions
ssl_options(
7621 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7622 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
7623 SSLConfigService::SetCRLSet(
7624 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
7626 CertStatus cert_status
;
7627 DoConnection(ssl_options
, &cert_status
);
7629 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7631 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7632 EXPECT_FALSE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7635 class HTTPSCRLSetTest
: public HTTPSOCSPTest
{
7637 virtual void SetupContext(URLRequestContext
* context
) OVERRIDE
{
7638 context
->set_ssl_config_service(
7639 new TestSSLConfigService(false /* check for EV */,
7640 false /* online revocation checking */,
7641 false /* require rev. checking for local
7646 TEST_F(HTTPSCRLSetTest
, ExpiredCRLSet
) {
7647 SpawnedTestServer::SSLOptions
ssl_options(
7648 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7649 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7650 SSLConfigService::SetCRLSet(
7651 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
7653 CertStatus cert_status
;
7654 DoConnection(ssl_options
, &cert_status
);
7656 // If we're not trying EV verification then, even if the CRLSet has expired,
7657 // we don't fall back to online revocation checks.
7658 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7659 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7660 EXPECT_FALSE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7663 TEST_F(HTTPSCRLSetTest
, CRLSetRevoked
) {
7664 #if defined(USE_OPENSSL)
7665 LOG(WARNING
) << "Skipping test because system doesn't support CRLSets";
7669 SpawnedTestServer::SSLOptions
ssl_options(
7670 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7671 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
7672 ssl_options
.cert_serial
= 10;
7673 SSLConfigService::SetCRLSet(
7674 scoped_refptr
<CRLSet
>(CRLSet::ForTesting(
7675 false, &kOCSPTestCertSPKI
, "\x0a")));
7677 CertStatus cert_status
= 0;
7678 DoConnection(ssl_options
, &cert_status
);
7680 // If the certificate is recorded as revoked in the CRLSet, that should be
7681 // reflected without online revocation checking.
7682 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
7683 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7685 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7687 #endif // !defined(OS_IOS)
7689 #if !defined(DISABLE_FTP_SUPPORT)
7690 class URLRequestTestFTP
: public URLRequestTest
{
7693 : test_server_(SpawnedTestServer::TYPE_FTP
, SpawnedTestServer::kLocalhost
,
7698 SpawnedTestServer test_server_
;
7701 // Make sure an FTP request using an unsafe ports fails.
7702 TEST_F(URLRequestTestFTP
, UnsafePort
) {
7703 ASSERT_TRUE(test_server_
.Start());
7705 URLRequestJobFactoryImpl job_factory
;
7706 FtpNetworkLayer
ftp_transaction_factory(default_context_
.host_resolver());
7708 GURL
url("ftp://127.0.0.1:7");
7709 job_factory
.SetProtocolHandler(
7711 new FtpProtocolHandler(&ftp_transaction_factory
));
7712 default_context_
.set_job_factory(&job_factory
);
7716 URLRequest
r(url
, DEFAULT_PRIORITY
, &d
, &default_context_
);
7718 EXPECT_TRUE(r
.is_pending());
7720 base::RunLoop().Run();
7722 EXPECT_FALSE(r
.is_pending());
7723 EXPECT_EQ(URLRequestStatus::FAILED
, r
.status().status());
7724 EXPECT_EQ(ERR_UNSAFE_PORT
, r
.status().error());
7728 // Flaky, see http://crbug.com/25045.
7729 TEST_F(URLRequestTestFTP
, DISABLED_FTPDirectoryListing
) {
7730 ASSERT_TRUE(test_server_
.Start());
7735 test_server_
.GetURL("/"), DEFAULT_PRIORITY
, &d
, &default_context_
);
7737 EXPECT_TRUE(r
.is_pending());
7739 base::RunLoop().Run();
7741 EXPECT_FALSE(r
.is_pending());
7742 EXPECT_EQ(1, d
.response_started_count());
7743 EXPECT_FALSE(d
.received_data_before_response());
7744 EXPECT_LT(0, d
.bytes_received());
7745 EXPECT_EQ(test_server_
.host_port_pair().host(),
7746 r
.GetSocketAddress().host());
7747 EXPECT_EQ(test_server_
.host_port_pair().port(),
7748 r
.GetSocketAddress().port());
7752 // Flaky, see http://crbug.com/25045.
7753 TEST_F(URLRequestTestFTP
, DISABLED_FTPGetTestAnonymous
) {
7754 ASSERT_TRUE(test_server_
.Start());
7756 base::FilePath app_path
;
7757 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7758 app_path
= app_path
.AppendASCII("LICENSE");
7761 URLRequest
r(test_server_
.GetURL("/LICENSE"),
7766 EXPECT_TRUE(r
.is_pending());
7768 base::RunLoop().Run();
7770 int64 file_size
= 0;
7771 base::GetFileSize(app_path
, &file_size
);
7773 EXPECT_FALSE(r
.is_pending());
7774 EXPECT_EQ(1, d
.response_started_count());
7775 EXPECT_FALSE(d
.received_data_before_response());
7776 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
7777 EXPECT_EQ(test_server_
.host_port_pair().host(),
7778 r
.GetSocketAddress().host());
7779 EXPECT_EQ(test_server_
.host_port_pair().port(),
7780 r
.GetSocketAddress().port());
7784 // Flaky, see http://crbug.com/25045.
7785 TEST_F(URLRequestTestFTP
, DISABLED_FTPGetTest
) {
7786 ASSERT_TRUE(test_server_
.Start());
7788 base::FilePath app_path
;
7789 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7790 app_path
= app_path
.AppendASCII("LICENSE");
7794 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7799 EXPECT_TRUE(r
.is_pending());
7801 base::RunLoop().Run();
7803 int64 file_size
= 0;
7804 base::GetFileSize(app_path
, &file_size
);
7806 EXPECT_FALSE(r
.is_pending());
7807 EXPECT_EQ(test_server_
.host_port_pair().host(),
7808 r
.GetSocketAddress().host());
7809 EXPECT_EQ(test_server_
.host_port_pair().port(),
7810 r
.GetSocketAddress().port());
7811 EXPECT_EQ(1, d
.response_started_count());
7812 EXPECT_FALSE(d
.received_data_before_response());
7813 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
7815 LoadTimingInfo load_timing_info
;
7816 r
.GetLoadTimingInfo(&load_timing_info
);
7817 TestLoadTimingNoHttpResponse(load_timing_info
);
7821 // Flaky, see http://crbug.com/25045.
7822 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongPassword
) {
7823 ASSERT_TRUE(test_server_
.Start());
7825 base::FilePath app_path
;
7826 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7827 app_path
= app_path
.AppendASCII("LICENSE");
7830 URLRequest
r(test_server_
.GetURLWithUserAndPassword(
7831 "/LICENSE", "chrome", "wrong_password"),
7836 EXPECT_TRUE(r
.is_pending());
7838 base::RunLoop().Run();
7840 int64 file_size
= 0;
7841 base::GetFileSize(app_path
, &file_size
);
7843 EXPECT_FALSE(r
.is_pending());
7844 EXPECT_EQ(1, d
.response_started_count());
7845 EXPECT_FALSE(d
.received_data_before_response());
7846 EXPECT_EQ(d
.bytes_received(), 0);
7850 // Flaky, see http://crbug.com/25045.
7851 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongPasswordRestart
) {
7852 ASSERT_TRUE(test_server_
.Start());
7854 base::FilePath app_path
;
7855 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7856 app_path
= app_path
.AppendASCII("LICENSE");
7858 // Set correct login credentials. The delegate will be asked for them when
7859 // the initial login with wrong credentials will fail.
7860 d
.set_credentials(AuthCredentials(kChrome
, kChrome
));
7862 URLRequest
r(test_server_
.GetURLWithUserAndPassword(
7863 "/LICENSE", "chrome", "wrong_password"),
7868 EXPECT_TRUE(r
.is_pending());
7870 base::RunLoop().Run();
7872 int64 file_size
= 0;
7873 base::GetFileSize(app_path
, &file_size
);
7875 EXPECT_FALSE(r
.is_pending());
7876 EXPECT_EQ(1, d
.response_started_count());
7877 EXPECT_FALSE(d
.received_data_before_response());
7878 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
7882 // Flaky, see http://crbug.com/25045.
7883 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongUser
) {
7884 ASSERT_TRUE(test_server_
.Start());
7886 base::FilePath app_path
;
7887 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7888 app_path
= app_path
.AppendASCII("LICENSE");
7891 URLRequest
r(test_server_
.GetURLWithUserAndPassword(
7892 "/LICENSE", "wrong_user", "chrome"),
7897 EXPECT_TRUE(r
.is_pending());
7899 base::RunLoop().Run();
7901 int64 file_size
= 0;
7902 base::GetFileSize(app_path
, &file_size
);
7904 EXPECT_FALSE(r
.is_pending());
7905 EXPECT_EQ(1, d
.response_started_count());
7906 EXPECT_FALSE(d
.received_data_before_response());
7907 EXPECT_EQ(d
.bytes_received(), 0);
7911 // Flaky, see http://crbug.com/25045.
7912 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongUserRestart
) {
7913 ASSERT_TRUE(test_server_
.Start());
7915 base::FilePath app_path
;
7916 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7917 app_path
= app_path
.AppendASCII("LICENSE");
7919 // Set correct login credentials. The delegate will be asked for them when
7920 // the initial login with wrong credentials will fail.
7921 d
.set_credentials(AuthCredentials(kChrome
, kChrome
));
7923 URLRequest
r(test_server_
.GetURLWithUserAndPassword(
7924 "/LICENSE", "wrong_user", "chrome"),
7929 EXPECT_TRUE(r
.is_pending());
7931 base::RunLoop().Run();
7933 int64 file_size
= 0;
7934 base::GetFileSize(app_path
, &file_size
);
7936 EXPECT_FALSE(r
.is_pending());
7937 EXPECT_EQ(1, d
.response_started_count());
7938 EXPECT_FALSE(d
.received_data_before_response());
7939 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
7943 // Flaky, see http://crbug.com/25045.
7944 TEST_F(URLRequestTestFTP
, DISABLED_FTPCacheURLCredentials
) {
7945 ASSERT_TRUE(test_server_
.Start());
7947 base::FilePath app_path
;
7948 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7949 app_path
= app_path
.AppendASCII("LICENSE");
7951 scoped_ptr
<TestDelegate
> d(new TestDelegate
);
7953 // Pass correct login identity in the URL.
7955 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7960 EXPECT_TRUE(r
.is_pending());
7962 base::RunLoop().Run();
7964 int64 file_size
= 0;
7965 base::GetFileSize(app_path
, &file_size
);
7967 EXPECT_FALSE(r
.is_pending());
7968 EXPECT_EQ(1, d
->response_started_count());
7969 EXPECT_FALSE(d
->received_data_before_response());
7970 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
7973 d
.reset(new TestDelegate
);
7975 // This request should use cached identity from previous request.
7976 URLRequest
r(test_server_
.GetURL("/LICENSE"),
7981 EXPECT_TRUE(r
.is_pending());
7983 base::RunLoop().Run();
7985 int64 file_size
= 0;
7986 base::GetFileSize(app_path
, &file_size
);
7988 EXPECT_FALSE(r
.is_pending());
7989 EXPECT_EQ(1, d
->response_started_count());
7990 EXPECT_FALSE(d
->received_data_before_response());
7991 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
7995 // Flaky, see http://crbug.com/25045.
7996 TEST_F(URLRequestTestFTP
, DISABLED_FTPCacheLoginBoxCredentials
) {
7997 ASSERT_TRUE(test_server_
.Start());
7999 base::FilePath app_path
;
8000 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8001 app_path
= app_path
.AppendASCII("LICENSE");
8003 scoped_ptr
<TestDelegate
> d(new TestDelegate
);
8004 // Set correct login credentials. The delegate will be asked for them when
8005 // the initial login with wrong credentials will fail.
8006 d
->set_credentials(AuthCredentials(kChrome
, kChrome
));
8008 URLRequest
r(test_server_
.GetURLWithUserAndPassword(
8009 "/LICENSE", "chrome", "wrong_password"),
8014 EXPECT_TRUE(r
.is_pending());
8016 base::RunLoop().Run();
8018 int64 file_size
= 0;
8019 base::GetFileSize(app_path
, &file_size
);
8021 EXPECT_FALSE(r
.is_pending());
8022 EXPECT_EQ(1, d
->response_started_count());
8023 EXPECT_FALSE(d
->received_data_before_response());
8024 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
8027 // Use a new delegate without explicit credentials. The cached ones should be
8029 d
.reset(new TestDelegate
);
8031 // Don't pass wrong credentials in the URL, they would override valid cached
8033 URLRequest
r(test_server_
.GetURL("/LICENSE"),
8038 EXPECT_TRUE(r
.is_pending());
8040 base::RunLoop().Run();
8042 int64 file_size
= 0;
8043 base::GetFileSize(app_path
, &file_size
);
8045 EXPECT_FALSE(r
.is_pending());
8046 EXPECT_EQ(1, d
->response_started_count());
8047 EXPECT_FALSE(d
->received_data_before_response());
8048 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
8051 #endif // !defined(DISABLE_FTP_SUPPORT)