isolate_driver: Enable ninja parsing code all the time.
[chromium-blink-merge.git] / net / url_request / url_request_unittest.cc
blob7a526a3d567bd43ce2a4476b5abe3517d82aec29
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"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shlobj.h>
10 #endif
12 #include <algorithm>
13 #include <string>
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/filename_util.h"
34 #include "net/base/load_flags.h"
35 #include "net/base/load_timing_info.h"
36 #include "net/base/load_timing_info_test_util.h"
37 #include "net/base/net_errors.h"
38 #include "net/base/net_log.h"
39 #include "net/base/net_log_unittest.h"
40 #include "net/base/net_module.h"
41 #include "net/base/net_util.h"
42 #include "net/base/request_priority.h"
43 #include "net/base/test_data_directory.h"
44 #include "net/base/upload_bytes_element_reader.h"
45 #include "net/base/upload_data_stream.h"
46 #include "net/base/upload_file_element_reader.h"
47 #include "net/cert/ev_root_ca_metadata.h"
48 #include "net/cert/mock_cert_verifier.h"
49 #include "net/cert/test_root_certs.h"
50 #include "net/cookies/cookie_monster.h"
51 #include "net/cookies/cookie_store_test_helpers.h"
52 #include "net/disk_cache/disk_cache.h"
53 #include "net/dns/mock_host_resolver.h"
54 #include "net/ftp/ftp_network_layer.h"
55 #include "net/http/http_byte_range.h"
56 #include "net/http/http_cache.h"
57 #include "net/http/http_network_layer.h"
58 #include "net/http/http_network_session.h"
59 #include "net/http/http_request_headers.h"
60 #include "net/http/http_response_headers.h"
61 #include "net/http/http_util.h"
62 #include "net/ocsp/nss_ocsp.h"
63 #include "net/proxy/proxy_service.h"
64 #include "net/socket/ssl_client_socket.h"
65 #include "net/ssl/ssl_connection_status_flags.h"
66 #include "net/test/cert_test_util.h"
67 #include "net/test/spawned_test_server/spawned_test_server.h"
68 #include "net/url_request/data_protocol_handler.h"
69 #include "net/url_request/static_http_user_agent_settings.h"
70 #include "net/url_request/url_request.h"
71 #include "net/url_request/url_request_http_job.h"
72 #include "net/url_request/url_request_job_factory_impl.h"
73 #include "net/url_request/url_request_redirect_job.h"
74 #include "net/url_request/url_request_test_job.h"
75 #include "net/url_request/url_request_test_util.h"
76 #include "testing/gtest/include/gtest/gtest.h"
77 #include "testing/platform_test.h"
79 #if !defined(DISABLE_FILE_SUPPORT)
80 #include "net/url_request/file_protocol_handler.h"
81 #include "net/url_request/url_request_file_dir_job.h"
82 #endif
84 #if !defined(DISABLE_FTP_SUPPORT)
85 #include "net/url_request/ftp_protocol_handler.h"
86 #endif
88 #if defined(OS_WIN)
89 #include "base/win/scoped_com_initializer.h"
90 #include "base/win/scoped_comptr.h"
91 #include "base/win/windows_version.h"
92 #endif
94 using base::ASCIIToUTF16;
95 using base::Time;
97 namespace net {
99 namespace {
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
106 // no proxy.
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) {
176 return "header";
179 void FillBuffer(char* buffer, size_t len) {
180 static bool called = false;
181 if (!called) {
182 called = true;
183 int seed = static_cast<int>(Time::Now().ToInternalValue());
184 srand(seed);
187 for (size_t i = 0; i < len; i++) {
188 buffer[i] = static_cast<char>(rand());
189 if (!buffer[i])
190 buffer[i] = 'g';
194 #if !defined(OS_IOS)
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(),
236 haystack.end(),
237 needle,
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())
275 return false;
277 for (size_t i = 0; i < size; ++i) {
278 if (!a[i].Equals(b[i]))
279 return false;
282 return true;
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,
290 // or
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 {
297 public:
298 // Stages in which the delegate can block.
299 enum Stage {
300 NOT_BLOCKED = 0,
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.
309 enum BlockMode {
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);
327 // Setters.
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);
332 retval_ = 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) {
347 redirect_url_ = 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_;
360 private:
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(
375 URLRequest* request,
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(
382 URLRequest* request,
383 const AuthChallengeInfo& auth_info,
384 const AuthCallback& callback,
385 AuthCredentials* credentials) OVERRIDE;
387 // Resets the callbacks and |stage_blocked_for_callback_|.
388 void Reset();
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
406 // callback.
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_| !=
412 // USER_CALLBACK).
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),
426 retval_(OK),
427 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
428 block_on_(0),
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_;
439 Reset();
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_;
448 Reset();
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(
467 URLRequest* request,
468 const CompletionCallback& callback,
469 GURL* new_url) {
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(
482 URLRequest* request,
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(
491 URLRequest* request,
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,
497 callback,
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(
506 URLRequest* request,
507 const AuthChallengeInfo& auth_info,
508 const AuthCallback& callback,
509 AuthCredentials* credentials) {
510 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
511 credentials);
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_) {
522 case SYNCHRONOUS:
523 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
524 *target_auth_credentials_ = auth_credentials_;
525 return auth_retval_;
527 case AUTO_CALLBACK:
528 base::MessageLoop::current()->PostTask(
529 FROM_HERE,
530 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
531 weak_factory_.GetWeakPtr(), auth_retval_, callback));
532 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
534 case USER_CALLBACK:
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;
541 NOTREACHED();
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;
548 callback_.Reset();
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) {
559 return OK;
562 switch (block_mode_) {
563 case SYNCHRONOUS:
564 EXPECT_NE(OK, retval_);
565 return retval_;
567 case AUTO_CALLBACK:
568 base::MessageLoop::current()->PostTask(
569 FROM_HERE,
570 base::Bind(&BlockingNetworkDelegate::RunCallback,
571 weak_factory_.GetWeakPtr(), retval_, callback));
572 return ERR_IO_PENDING;
574 case USER_CALLBACK:
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;
581 NOTREACHED();
582 return 0;
585 class TestURLRequestContextWithProxy : public TestURLRequestContext {
586 public:
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);
593 Init();
595 virtual ~TestURLRequestContextWithProxy() {}
598 } // namespace
600 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
601 class URLRequestTest : public PlatformTest {
602 public:
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()));
610 #endif
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_;
627 protected:
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) {
635 TestDelegate d;
637 URLRequest r(GURL("about:blank"), DEFAULT_PRIORITY, &d, &default_context_);
639 r.Start();
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) {
656 TestDelegate d;
658 // Use our nice little Chrome logo.
659 URLRequest r(
660 GURL(
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="),
680 DEFAULT_PRIORITY,
682 &default_context_);
684 r.Start();
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 TEST_F(URLRequestTest, FileTest) {
701 base::FilePath app_path;
702 PathService::Get(base::FILE_EXE, &app_path);
703 GURL app_url = FilePathToFileURL(app_path);
705 TestDelegate d;
707 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
709 r.Start();
710 EXPECT_TRUE(r.is_pending());
712 base::RunLoop().Run();
714 int64 file_size = -1;
715 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
717 EXPECT_TRUE(!r.is_pending());
718 EXPECT_EQ(1, d.response_started_count());
719 EXPECT_FALSE(d.received_data_before_response());
720 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
721 EXPECT_EQ("", r.GetSocketAddress().host());
722 EXPECT_EQ(0, r.GetSocketAddress().port());
724 HttpRequestHeaders headers;
725 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
729 TEST_F(URLRequestTest, FileTestCancel) {
730 base::FilePath app_path;
731 PathService::Get(base::FILE_EXE, &app_path);
732 GURL app_url = FilePathToFileURL(app_path);
734 TestDelegate d;
736 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
738 r.Start();
739 EXPECT_TRUE(r.is_pending());
740 r.Cancel();
742 // Async cancellation should be safe even when URLRequest has been already
743 // destroyed.
744 base::RunLoop().RunUntilIdle();
747 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
748 const size_t buffer_size = 4000;
749 scoped_ptr<char[]> buffer(new char[buffer_size]);
750 FillBuffer(buffer.get(), buffer_size);
752 base::FilePath temp_path;
753 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
754 GURL temp_url = FilePathToFileURL(temp_path);
755 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
757 int64 file_size;
758 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
760 const size_t first_byte_position = 500;
761 const size_t last_byte_position = buffer_size - first_byte_position;
762 const size_t content_length = last_byte_position - first_byte_position + 1;
763 std::string partial_buffer_string(buffer.get() + first_byte_position,
764 buffer.get() + last_byte_position + 1);
766 TestDelegate d;
768 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
770 HttpRequestHeaders headers;
771 headers.SetHeader(
772 HttpRequestHeaders::kRange,
773 net::HttpByteRange::Bounded(
774 first_byte_position, last_byte_position).GetHeaderValue());
775 r.SetExtraRequestHeaders(headers);
776 r.Start();
777 EXPECT_TRUE(r.is_pending());
779 base::RunLoop().Run();
780 EXPECT_TRUE(!r.is_pending());
781 EXPECT_EQ(1, d.response_started_count());
782 EXPECT_FALSE(d.received_data_before_response());
783 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
784 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
785 EXPECT_TRUE(partial_buffer_string == d.data_received());
788 EXPECT_TRUE(base::DeleteFile(temp_path, false));
791 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
792 const size_t buffer_size = 4000;
793 scoped_ptr<char[]> buffer(new char[buffer_size]);
794 FillBuffer(buffer.get(), buffer_size);
796 base::FilePath temp_path;
797 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
798 GURL temp_url = FilePathToFileURL(temp_path);
799 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
801 int64 file_size;
802 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
804 const size_t first_byte_position = 500;
805 const size_t last_byte_position = buffer_size - 1;
806 const size_t content_length = last_byte_position - first_byte_position + 1;
807 std::string partial_buffer_string(buffer.get() + first_byte_position,
808 buffer.get() + last_byte_position + 1);
810 TestDelegate d;
812 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
814 HttpRequestHeaders headers;
815 headers.SetHeader(HttpRequestHeaders::kRange,
816 net::HttpByteRange::RightUnbounded(
817 first_byte_position).GetHeaderValue());
818 r.SetExtraRequestHeaders(headers);
819 r.Start();
820 EXPECT_TRUE(r.is_pending());
822 base::RunLoop().Run();
823 EXPECT_TRUE(!r.is_pending());
824 EXPECT_EQ(1, d.response_started_count());
825 EXPECT_FALSE(d.received_data_before_response());
826 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
827 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
828 EXPECT_TRUE(partial_buffer_string == d.data_received());
831 EXPECT_TRUE(base::DeleteFile(temp_path, false));
834 TEST_F(URLRequestTest, FileTestMultipleRanges) {
835 const size_t buffer_size = 400000;
836 scoped_ptr<char[]> buffer(new char[buffer_size]);
837 FillBuffer(buffer.get(), buffer_size);
839 base::FilePath temp_path;
840 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
841 GURL temp_url = FilePathToFileURL(temp_path);
842 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
844 int64 file_size;
845 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
847 TestDelegate d;
849 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
851 HttpRequestHeaders headers;
852 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
853 r.SetExtraRequestHeaders(headers);
854 r.Start();
855 EXPECT_TRUE(r.is_pending());
857 base::RunLoop().Run();
858 EXPECT_TRUE(d.request_failed());
861 EXPECT_TRUE(base::DeleteFile(temp_path, false));
864 TEST_F(URLRequestTest, AllowFileURLs) {
865 base::ScopedTempDir temp_dir;
866 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
867 base::FilePath test_file;
868 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
869 std::string test_data("monkey");
870 base::WriteFile(test_file, test_data.data(), test_data.size());
871 GURL test_file_url = net::FilePathToFileURL(test_file);
874 TestDelegate d;
875 TestNetworkDelegate network_delegate;
876 network_delegate.set_can_access_files(true);
877 default_context_.set_network_delegate(&network_delegate);
878 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
879 r.Start();
880 base::RunLoop().Run();
881 EXPECT_FALSE(d.request_failed());
882 EXPECT_EQ(test_data, d.data_received());
886 TestDelegate d;
887 TestNetworkDelegate network_delegate;
888 network_delegate.set_can_access_files(false);
889 default_context_.set_network_delegate(&network_delegate);
890 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
891 r.Start();
892 base::RunLoop().Run();
893 EXPECT_TRUE(d.request_failed());
894 EXPECT_EQ("", d.data_received());
898 TEST_F(URLRequestTest, InvalidUrlTest) {
899 TestDelegate d;
901 URLRequest r(GURL("invalid url"), DEFAULT_PRIORITY, &d, &default_context_);
903 r.Start();
904 EXPECT_TRUE(r.is_pending());
906 base::RunLoop().Run();
907 EXPECT_TRUE(d.request_failed());
911 #if defined(OS_WIN)
912 TEST_F(URLRequestTest, ResolveShortcutTest) {
913 base::FilePath app_path;
914 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
915 app_path = app_path.AppendASCII("net");
916 app_path = app_path.AppendASCII("data");
917 app_path = app_path.AppendASCII("url_request_unittest");
918 app_path = app_path.AppendASCII("with-headers.html");
920 std::wstring lnk_path = app_path.value() + L".lnk";
922 base::win::ScopedCOMInitializer com_initializer;
924 // Temporarily create a shortcut for test
926 base::win::ScopedComPtr<IShellLink> shell;
927 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
928 CLSCTX_INPROC_SERVER)));
929 base::win::ScopedComPtr<IPersistFile> persist;
930 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
931 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
932 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
933 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
936 TestDelegate d;
938 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)),
939 DEFAULT_PRIORITY,
941 &default_context_);
943 r.Start();
944 EXPECT_TRUE(r.is_pending());
946 base::RunLoop().Run();
948 WIN32_FILE_ATTRIBUTE_DATA data;
949 GetFileAttributesEx(app_path.value().c_str(),
950 GetFileExInfoStandard, &data);
951 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
952 FILE_SHARE_READ, NULL, OPEN_EXISTING,
953 FILE_ATTRIBUTE_NORMAL, NULL);
954 EXPECT_NE(INVALID_HANDLE_VALUE, file);
955 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
956 DWORD read_size;
957 BOOL result;
958 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
959 &read_size, NULL);
960 std::string content(buffer.get(), read_size);
961 CloseHandle(file);
963 EXPECT_TRUE(!r.is_pending());
964 EXPECT_EQ(1, d.received_redirect_count());
965 EXPECT_EQ(content, d.data_received());
968 // Clean the shortcut
969 DeleteFile(lnk_path.c_str());
971 #endif // defined(OS_WIN)
973 TEST_F(URLRequestTest, FileDirCancelTest) {
974 // Put in mock resource provider.
975 NetModule::SetResourceProvider(TestNetResourceProvider);
977 TestDelegate d;
979 base::FilePath file_path;
980 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
981 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
982 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
984 URLRequest req(
985 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, &default_context_);
986 req.Start();
987 EXPECT_TRUE(req.is_pending());
989 d.set_cancel_in_received_data_pending(true);
991 base::RunLoop().Run();
994 // Take out mock resource provider.
995 NetModule::SetResourceProvider(NULL);
998 TEST_F(URLRequestTest, FileDirOutputSanity) {
999 // Verify the general sanity of the the output of the file:
1000 // directory lister by checking for the output of a known existing
1001 // file.
1002 const char sentinel_name[] = "filedir-sentinel";
1004 base::FilePath path;
1005 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1006 path = path.Append(FILE_PATH_LITERAL("net"));
1007 path = path.Append(FILE_PATH_LITERAL("data"));
1008 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1010 TestDelegate d;
1011 URLRequest req(
1012 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
1013 req.Start();
1014 base::RunLoop().Run();
1016 // Generate entry for the sentinel file.
1017 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
1018 base::File::Info info;
1019 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
1020 EXPECT_GT(info.size, 0);
1021 std::string sentinel_output = GetDirectoryListingEntry(
1022 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1023 std::string(sentinel_name),
1024 false /* is_dir */,
1025 info.size,
1026 info.last_modified);
1028 ASSERT_LT(0, d.bytes_received());
1029 ASSERT_FALSE(d.request_failed());
1030 ASSERT_TRUE(req.status().is_success());
1031 // Check for the entry generated for the "sentinel" file.
1032 const std::string& data = d.data_received();
1033 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1036 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1037 // There is an implicit redirect when loading a file path that matches a
1038 // directory and does not end with a slash. Ensure that following such
1039 // redirects does not crash. See http://crbug.com/18686.
1041 base::FilePath path;
1042 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1043 path = path.Append(FILE_PATH_LITERAL("net"));
1044 path = path.Append(FILE_PATH_LITERAL("data"));
1045 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1047 TestDelegate d;
1048 URLRequest req(
1049 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
1050 req.Start();
1051 base::RunLoop().Run();
1053 ASSERT_EQ(1, d.received_redirect_count());
1054 ASSERT_LT(0, d.bytes_received());
1055 ASSERT_FALSE(d.request_failed());
1056 ASSERT_TRUE(req.status().is_success());
1059 #if defined(OS_WIN)
1060 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1061 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1062 TestDelegate d;
1063 URLRequest req(GURL("file:///"), DEFAULT_PRIORITY, &d, &default_context_);
1064 req.Start();
1065 base::RunLoop().Run();
1067 ASSERT_EQ(1, d.received_redirect_count());
1068 ASSERT_FALSE(req.status().is_success());
1070 #endif
1072 // Custom URLRequestJobs for use with interceptor tests
1073 class RestartTestJob : public URLRequestTestJob {
1074 public:
1075 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1076 : URLRequestTestJob(request, network_delegate, true) {}
1077 protected:
1078 virtual void StartAsync() OVERRIDE {
1079 this->NotifyRestartRequired();
1081 private:
1082 virtual ~RestartTestJob() {}
1085 class CancelTestJob : public URLRequestTestJob {
1086 public:
1087 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1088 : URLRequestTestJob(request, network_delegate, true) {}
1089 protected:
1090 virtual void StartAsync() OVERRIDE {
1091 request_->Cancel();
1093 private:
1094 virtual ~CancelTestJob() {}
1097 class CancelThenRestartTestJob : public URLRequestTestJob {
1098 public:
1099 explicit CancelThenRestartTestJob(URLRequest* request,
1100 NetworkDelegate* network_delegate)
1101 : URLRequestTestJob(request, network_delegate, true) {
1103 protected:
1104 virtual void StartAsync() OVERRIDE {
1105 request_->Cancel();
1106 this->NotifyRestartRequired();
1108 private:
1109 virtual ~CancelThenRestartTestJob() {}
1112 // An Interceptor for use with interceptor tests
1113 class TestInterceptor : URLRequest::Interceptor {
1114 public:
1115 TestInterceptor()
1116 : intercept_main_request_(false), restart_main_request_(false),
1117 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1118 simulate_main_network_error_(false),
1119 intercept_redirect_(false), cancel_redirect_request_(false),
1120 intercept_final_response_(false), cancel_final_request_(false),
1121 did_intercept_main_(false), did_restart_main_(false),
1122 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1123 did_simulate_error_main_(false),
1124 did_intercept_redirect_(false), did_cancel_redirect_(false),
1125 did_intercept_final_(false), did_cancel_final_(false) {
1126 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1129 virtual ~TestInterceptor() {
1130 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1133 virtual URLRequestJob* MaybeIntercept(
1134 URLRequest* request,
1135 NetworkDelegate* network_delegate) OVERRIDE {
1136 if (restart_main_request_) {
1137 restart_main_request_ = false;
1138 did_restart_main_ = true;
1139 return new RestartTestJob(request, network_delegate);
1141 if (cancel_main_request_) {
1142 cancel_main_request_ = false;
1143 did_cancel_main_ = true;
1144 return new CancelTestJob(request, network_delegate);
1146 if (cancel_then_restart_main_request_) {
1147 cancel_then_restart_main_request_ = false;
1148 did_cancel_then_restart_main_ = true;
1149 return new CancelThenRestartTestJob(request, network_delegate);
1151 if (simulate_main_network_error_) {
1152 simulate_main_network_error_ = false;
1153 did_simulate_error_main_ = true;
1154 // will error since the requeted url is not one of its canned urls
1155 return new URLRequestTestJob(request, network_delegate, true);
1157 if (!intercept_main_request_)
1158 return NULL;
1159 intercept_main_request_ = false;
1160 did_intercept_main_ = true;
1161 URLRequestTestJob* job = new URLRequestTestJob(request,
1162 network_delegate,
1163 main_headers_,
1164 main_data_,
1165 true);
1166 job->set_load_timing_info(main_request_load_timing_info_);
1167 return job;
1170 virtual URLRequestJob* MaybeInterceptRedirect(
1171 URLRequest* request,
1172 NetworkDelegate* network_delegate,
1173 const GURL& location) OVERRIDE {
1174 if (cancel_redirect_request_) {
1175 cancel_redirect_request_ = false;
1176 did_cancel_redirect_ = true;
1177 return new CancelTestJob(request, network_delegate);
1179 if (!intercept_redirect_)
1180 return NULL;
1181 intercept_redirect_ = false;
1182 did_intercept_redirect_ = true;
1183 return new URLRequestTestJob(request,
1184 network_delegate,
1185 redirect_headers_,
1186 redirect_data_,
1187 true);
1190 virtual URLRequestJob* MaybeInterceptResponse(
1191 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
1192 if (cancel_final_request_) {
1193 cancel_final_request_ = false;
1194 did_cancel_final_ = true;
1195 return new CancelTestJob(request, network_delegate);
1197 if (!intercept_final_response_)
1198 return NULL;
1199 intercept_final_response_ = false;
1200 did_intercept_final_ = true;
1201 return new URLRequestTestJob(request,
1202 network_delegate,
1203 final_headers_,
1204 final_data_,
1205 true);
1208 // Whether to intercept the main request, and if so the response to return and
1209 // the LoadTimingInfo to use.
1210 bool intercept_main_request_;
1211 std::string main_headers_;
1212 std::string main_data_;
1213 LoadTimingInfo main_request_load_timing_info_;
1215 // Other actions we take at MaybeIntercept time
1216 bool restart_main_request_;
1217 bool cancel_main_request_;
1218 bool cancel_then_restart_main_request_;
1219 bool simulate_main_network_error_;
1221 // Whether to intercept redirects, and if so the response to return.
1222 bool intercept_redirect_;
1223 std::string redirect_headers_;
1224 std::string redirect_data_;
1226 // Other actions we can take at MaybeInterceptRedirect time
1227 bool cancel_redirect_request_;
1229 // Whether to intercept final response, and if so the response to return.
1230 bool intercept_final_response_;
1231 std::string final_headers_;
1232 std::string final_data_;
1234 // Other actions we can take at MaybeInterceptResponse time
1235 bool cancel_final_request_;
1237 // If we did something or not
1238 bool did_intercept_main_;
1239 bool did_restart_main_;
1240 bool did_cancel_main_;
1241 bool did_cancel_then_restart_main_;
1242 bool did_simulate_error_main_;
1243 bool did_intercept_redirect_;
1244 bool did_cancel_redirect_;
1245 bool did_intercept_final_;
1246 bool did_cancel_final_;
1248 // Static getters for canned response header and data strings
1250 static std::string ok_data() {
1251 return URLRequestTestJob::test_data_1();
1254 static std::string ok_headers() {
1255 return URLRequestTestJob::test_headers();
1258 static std::string redirect_data() {
1259 return std::string();
1262 static std::string redirect_headers() {
1263 return URLRequestTestJob::test_redirect_headers();
1266 static std::string error_data() {
1267 return std::string("ohhh nooooo mr. bill!");
1270 static std::string error_headers() {
1271 return URLRequestTestJob::test_error_headers();
1275 TEST_F(URLRequestTest, Intercept) {
1276 TestInterceptor interceptor;
1278 // intercept the main request and respond with a simple response
1279 interceptor.intercept_main_request_ = true;
1280 interceptor.main_headers_ = TestInterceptor::ok_headers();
1281 interceptor.main_data_ = TestInterceptor::ok_data();
1283 TestDelegate d;
1284 URLRequest req(GURL("http://test_intercept/foo"),
1285 DEFAULT_PRIORITY,
1287 &default_context_);
1288 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1289 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1290 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1291 req.SetUserData(NULL, user_data0);
1292 req.SetUserData(&user_data1, user_data1);
1293 req.SetUserData(&user_data2, user_data2);
1294 req.set_method("GET");
1295 req.Start();
1296 base::RunLoop().Run();
1298 // Make sure we can retrieve our specific user data
1299 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1300 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1301 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1303 // Check the interceptor got called as expected
1304 EXPECT_TRUE(interceptor.did_intercept_main_);
1306 // Check we got one good response
1307 EXPECT_TRUE(req.status().is_success());
1308 EXPECT_EQ(200, req.response_headers()->response_code());
1309 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1310 EXPECT_EQ(1, d.response_started_count());
1311 EXPECT_EQ(0, d.received_redirect_count());
1314 TEST_F(URLRequestTest, InterceptRedirect) {
1315 TestInterceptor interceptor;
1317 // intercept the main request and respond with a redirect
1318 interceptor.intercept_main_request_ = true;
1319 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1320 interceptor.main_data_ = TestInterceptor::redirect_data();
1322 // intercept that redirect and respond a final OK response
1323 interceptor.intercept_redirect_ = true;
1324 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1325 interceptor.redirect_data_ = TestInterceptor::ok_data();
1327 TestDelegate d;
1328 URLRequest req(GURL("http://test_intercept/foo"),
1329 DEFAULT_PRIORITY,
1331 &default_context_);
1332 req.set_method("GET");
1333 req.Start();
1334 base::RunLoop().Run();
1336 // Check the interceptor got called as expected
1337 EXPECT_TRUE(interceptor.did_intercept_main_);
1338 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1340 // Check we got one good response
1341 EXPECT_TRUE(req.status().is_success());
1342 if (req.status().is_success()) {
1343 EXPECT_EQ(200, req.response_headers()->response_code());
1345 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1346 EXPECT_EQ(1, d.response_started_count());
1347 EXPECT_EQ(0, d.received_redirect_count());
1350 TEST_F(URLRequestTest, InterceptServerError) {
1351 TestInterceptor interceptor;
1353 // intercept the main request to generate a server error response
1354 interceptor.intercept_main_request_ = true;
1355 interceptor.main_headers_ = TestInterceptor::error_headers();
1356 interceptor.main_data_ = TestInterceptor::error_data();
1358 // intercept that error and respond with an OK response
1359 interceptor.intercept_final_response_ = true;
1360 interceptor.final_headers_ = TestInterceptor::ok_headers();
1361 interceptor.final_data_ = TestInterceptor::ok_data();
1363 TestDelegate d;
1364 URLRequest req(GURL("http://test_intercept/foo"),
1365 DEFAULT_PRIORITY,
1367 &default_context_);
1368 req.set_method("GET");
1369 req.Start();
1370 base::RunLoop().Run();
1372 // Check the interceptor got called as expected
1373 EXPECT_TRUE(interceptor.did_intercept_main_);
1374 EXPECT_TRUE(interceptor.did_intercept_final_);
1376 // Check we got one good response
1377 EXPECT_TRUE(req.status().is_success());
1378 EXPECT_EQ(200, req.response_headers()->response_code());
1379 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1380 EXPECT_EQ(1, d.response_started_count());
1381 EXPECT_EQ(0, d.received_redirect_count());
1384 TEST_F(URLRequestTest, InterceptNetworkError) {
1385 TestInterceptor interceptor;
1387 // intercept the main request to simulate a network error
1388 interceptor.simulate_main_network_error_ = true;
1390 // intercept that error and respond with an OK response
1391 interceptor.intercept_final_response_ = true;
1392 interceptor.final_headers_ = TestInterceptor::ok_headers();
1393 interceptor.final_data_ = TestInterceptor::ok_data();
1395 TestDelegate d;
1396 URLRequest req(GURL("http://test_intercept/foo"),
1397 DEFAULT_PRIORITY,
1399 &default_context_);
1400 req.set_method("GET");
1401 req.Start();
1402 base::RunLoop().Run();
1404 // Check the interceptor got called as expected
1405 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1406 EXPECT_TRUE(interceptor.did_intercept_final_);
1408 // Check we received one good response
1409 EXPECT_TRUE(req.status().is_success());
1410 EXPECT_EQ(200, req.response_headers()->response_code());
1411 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1412 EXPECT_EQ(1, d.response_started_count());
1413 EXPECT_EQ(0, d.received_redirect_count());
1416 TEST_F(URLRequestTest, InterceptRestartRequired) {
1417 TestInterceptor interceptor;
1419 // restart the main request
1420 interceptor.restart_main_request_ = true;
1422 // then intercept the new main request and respond with an OK response
1423 interceptor.intercept_main_request_ = true;
1424 interceptor.main_headers_ = TestInterceptor::ok_headers();
1425 interceptor.main_data_ = TestInterceptor::ok_data();
1427 TestDelegate d;
1428 URLRequest req(GURL("http://test_intercept/foo"),
1429 DEFAULT_PRIORITY,
1431 &default_context_);
1432 req.set_method("GET");
1433 req.Start();
1434 base::RunLoop().Run();
1436 // Check the interceptor got called as expected
1437 EXPECT_TRUE(interceptor.did_restart_main_);
1438 EXPECT_TRUE(interceptor.did_intercept_main_);
1440 // Check we received one good response
1441 EXPECT_TRUE(req.status().is_success());
1442 if (req.status().is_success()) {
1443 EXPECT_EQ(200, req.response_headers()->response_code());
1445 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1446 EXPECT_EQ(1, d.response_started_count());
1447 EXPECT_EQ(0, d.received_redirect_count());
1450 TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1451 TestInterceptor interceptor;
1453 // intercept the main request and cancel from within the restarted job
1454 interceptor.cancel_main_request_ = true;
1456 // setup to intercept final response and override it with an OK response
1457 interceptor.intercept_final_response_ = true;
1458 interceptor.final_headers_ = TestInterceptor::ok_headers();
1459 interceptor.final_data_ = TestInterceptor::ok_data();
1461 TestDelegate d;
1462 URLRequest req(GURL("http://test_intercept/foo"),
1463 DEFAULT_PRIORITY,
1465 &default_context_);
1466 req.set_method("GET");
1467 req.Start();
1468 base::RunLoop().Run();
1470 // Check the interceptor got called as expected
1471 EXPECT_TRUE(interceptor.did_cancel_main_);
1472 EXPECT_FALSE(interceptor.did_intercept_final_);
1474 // Check we see a canceled request
1475 EXPECT_FALSE(req.status().is_success());
1476 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1479 TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1480 TestInterceptor interceptor;
1482 // intercept the main request and respond with a redirect
1483 interceptor.intercept_main_request_ = true;
1484 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1485 interceptor.main_data_ = TestInterceptor::redirect_data();
1487 // intercept the redirect and cancel from within that job
1488 interceptor.cancel_redirect_request_ = true;
1490 // setup to intercept final response and override it with an OK response
1491 interceptor.intercept_final_response_ = true;
1492 interceptor.final_headers_ = TestInterceptor::ok_headers();
1493 interceptor.final_data_ = TestInterceptor::ok_data();
1495 TestDelegate d;
1496 URLRequest req(GURL("http://test_intercept/foo"),
1497 DEFAULT_PRIORITY,
1499 &default_context_);
1500 req.set_method("GET");
1501 req.Start();
1502 base::RunLoop().Run();
1504 // Check the interceptor got called as expected
1505 EXPECT_TRUE(interceptor.did_intercept_main_);
1506 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1507 EXPECT_FALSE(interceptor.did_intercept_final_);
1509 // Check we see a canceled request
1510 EXPECT_FALSE(req.status().is_success());
1511 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1514 TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1515 TestInterceptor interceptor;
1517 // intercept the main request to simulate a network error
1518 interceptor.simulate_main_network_error_ = true;
1520 // setup to intercept final response and cancel from within that job
1521 interceptor.cancel_final_request_ = true;
1523 TestDelegate d;
1524 URLRequest req(GURL("http://test_intercept/foo"),
1525 DEFAULT_PRIORITY,
1527 &default_context_);
1528 req.set_method("GET");
1529 req.Start();
1530 base::RunLoop().Run();
1532 // Check the interceptor got called as expected
1533 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1534 EXPECT_TRUE(interceptor.did_cancel_final_);
1536 // Check we see a canceled request
1537 EXPECT_FALSE(req.status().is_success());
1538 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1541 TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1542 TestInterceptor interceptor;
1544 // intercept the main request and cancel then restart from within that job
1545 interceptor.cancel_then_restart_main_request_ = true;
1547 // setup to intercept final response and override it with an OK response
1548 interceptor.intercept_final_response_ = true;
1549 interceptor.final_headers_ = TestInterceptor::ok_headers();
1550 interceptor.final_data_ = TestInterceptor::ok_data();
1552 TestDelegate d;
1553 URLRequest req(GURL("http://test_intercept/foo"),
1554 DEFAULT_PRIORITY,
1556 &default_context_);
1557 req.set_method("GET");
1558 req.Start();
1559 base::RunLoop().Run();
1561 // Check the interceptor got called as expected
1562 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1563 EXPECT_FALSE(interceptor.did_intercept_final_);
1565 // Check we see a canceled request
1566 EXPECT_FALSE(req.status().is_success());
1567 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1570 LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1571 URLRequestContext* context) {
1572 TestInterceptor interceptor;
1573 interceptor.intercept_main_request_ = true;
1574 interceptor.main_request_load_timing_info_ = job_load_timing;
1575 TestDelegate d;
1576 URLRequest req(
1577 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, context);
1578 req.Start();
1579 base::RunLoop().Run();
1581 LoadTimingInfo resulting_load_timing;
1582 req.GetLoadTimingInfo(&resulting_load_timing);
1584 // None of these should be modified by the URLRequest.
1585 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1586 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1587 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1588 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1589 EXPECT_EQ(job_load_timing.receive_headers_end,
1590 resulting_load_timing.receive_headers_end);
1592 return resulting_load_timing;
1595 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1596 // reused. |connect_time_flags| is used to indicate if there should be dns
1597 // or SSL times, and |used_proxy| is used for proxy times.
1598 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1599 int connect_time_flags,
1600 bool used_proxy) {
1601 LoadTimingInfo load_timing;
1602 load_timing.socket_log_id = 1;
1604 if (used_proxy) {
1605 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1606 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1609 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1610 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1611 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1612 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1614 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1615 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1616 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1617 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1619 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1621 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1622 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1623 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1624 return load_timing;
1627 // Same as above, but in the case of a reused socket.
1628 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1629 bool used_proxy) {
1630 LoadTimingInfo load_timing;
1631 load_timing.socket_log_id = 1;
1632 load_timing.socket_reused = true;
1634 if (used_proxy) {
1635 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1636 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1639 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1640 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1641 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1642 return load_timing;
1645 // Basic test that the intercept + load timing tests work.
1646 TEST_F(URLRequestTest, InterceptLoadTiming) {
1647 base::TimeTicks now = base::TimeTicks::Now();
1648 LoadTimingInfo job_load_timing =
1649 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1651 LoadTimingInfo load_timing_result =
1652 RunLoadTimingTest(job_load_timing, &default_context_);
1654 // Nothing should have been changed by the URLRequest.
1655 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1656 load_timing_result.proxy_resolve_start);
1657 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1658 load_timing_result.proxy_resolve_end);
1659 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1660 load_timing_result.connect_timing.dns_start);
1661 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1662 load_timing_result.connect_timing.dns_end);
1663 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1664 load_timing_result.connect_timing.connect_start);
1665 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1666 load_timing_result.connect_timing.connect_end);
1667 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1668 load_timing_result.connect_timing.ssl_start);
1669 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1670 load_timing_result.connect_timing.ssl_end);
1672 // Redundant sanity check.
1673 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1676 // Another basic test, with proxy and SSL times, but no DNS times.
1677 TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1678 base::TimeTicks now = base::TimeTicks::Now();
1679 LoadTimingInfo job_load_timing =
1680 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1682 LoadTimingInfo load_timing_result =
1683 RunLoadTimingTest(job_load_timing, &default_context_);
1685 // Nothing should have been changed by the URLRequest.
1686 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1687 load_timing_result.proxy_resolve_start);
1688 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1689 load_timing_result.proxy_resolve_end);
1690 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1691 load_timing_result.connect_timing.dns_start);
1692 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1693 load_timing_result.connect_timing.dns_end);
1694 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1695 load_timing_result.connect_timing.connect_start);
1696 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1697 load_timing_result.connect_timing.connect_end);
1698 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1699 load_timing_result.connect_timing.ssl_start);
1700 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1701 load_timing_result.connect_timing.ssl_end);
1703 // Redundant sanity check.
1704 TestLoadTimingNotReusedWithProxy(load_timing_result,
1705 CONNECT_TIMING_HAS_SSL_TIMES);
1708 // Make sure that URLRequest correctly adjusts proxy times when they're before
1709 // |request_start|, due to already having a connected socket. This happens in
1710 // the case of reusing a SPDY session or HTTP pipeline. The connected socket is
1711 // not considered reused in this test (May be a preconnect).
1713 // To mix things up from the test above, assumes DNS times but no SSL times.
1714 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1715 base::TimeTicks now = base::TimeTicks::Now();
1716 LoadTimingInfo job_load_timing =
1717 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1718 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1719 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1720 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1721 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1722 job_load_timing.connect_timing.connect_start =
1723 now - base::TimeDelta::FromDays(2);
1724 job_load_timing.connect_timing.connect_end =
1725 now - base::TimeDelta::FromDays(1);
1727 LoadTimingInfo load_timing_result =
1728 RunLoadTimingTest(job_load_timing, &default_context_);
1730 // Proxy times, connect times, and DNS times should all be replaced with
1731 // request_start.
1732 EXPECT_EQ(load_timing_result.request_start,
1733 load_timing_result.proxy_resolve_start);
1734 EXPECT_EQ(load_timing_result.request_start,
1735 load_timing_result.proxy_resolve_end);
1736 EXPECT_EQ(load_timing_result.request_start,
1737 load_timing_result.connect_timing.dns_start);
1738 EXPECT_EQ(load_timing_result.request_start,
1739 load_timing_result.connect_timing.dns_end);
1740 EXPECT_EQ(load_timing_result.request_start,
1741 load_timing_result.connect_timing.connect_start);
1742 EXPECT_EQ(load_timing_result.request_start,
1743 load_timing_result.connect_timing.connect_end);
1745 // Other times should have been left null.
1746 TestLoadTimingNotReusedWithProxy(load_timing_result,
1747 CONNECT_TIMING_HAS_DNS_TIMES);
1750 // Same as above, but in the reused case.
1751 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1752 base::TimeTicks now = base::TimeTicks::Now();
1753 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1754 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1755 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1757 LoadTimingInfo load_timing_result =
1758 RunLoadTimingTest(job_load_timing, &default_context_);
1760 // Proxy times and connect times should all be replaced with request_start.
1761 EXPECT_EQ(load_timing_result.request_start,
1762 load_timing_result.proxy_resolve_start);
1763 EXPECT_EQ(load_timing_result.request_start,
1764 load_timing_result.proxy_resolve_end);
1766 // Other times should have been left null.
1767 TestLoadTimingReusedWithProxy(load_timing_result);
1770 // Make sure that URLRequest correctly adjusts connect times when they're before
1771 // |request_start|, due to reusing a connected socket. The connected socket is
1772 // not considered reused in this test (May be a preconnect).
1774 // To mix things up, the request has SSL times, but no DNS times.
1775 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1776 base::TimeTicks now = base::TimeTicks::Now();
1777 LoadTimingInfo job_load_timing =
1778 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1779 job_load_timing.connect_timing.connect_start =
1780 now - base::TimeDelta::FromDays(1);
1781 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1782 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1783 job_load_timing.connect_timing.connect_end =
1784 now - base::TimeDelta::FromDays(4);
1786 LoadTimingInfo load_timing_result =
1787 RunLoadTimingTest(job_load_timing, &default_context_);
1789 // Connect times, and SSL times should be replaced with request_start.
1790 EXPECT_EQ(load_timing_result.request_start,
1791 load_timing_result.connect_timing.connect_start);
1792 EXPECT_EQ(load_timing_result.request_start,
1793 load_timing_result.connect_timing.ssl_start);
1794 EXPECT_EQ(load_timing_result.request_start,
1795 load_timing_result.connect_timing.ssl_end);
1796 EXPECT_EQ(load_timing_result.request_start,
1797 load_timing_result.connect_timing.connect_end);
1799 // Other times should have been left null.
1800 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1803 // Make sure that URLRequest correctly adjusts connect times when they're before
1804 // |request_start|, due to reusing a connected socket in the case that there
1805 // are also proxy times. The connected socket is not considered reused in this
1806 // test (May be a preconnect).
1808 // In this test, there are no SSL or DNS times.
1809 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1810 base::TimeTicks now = base::TimeTicks::Now();
1811 LoadTimingInfo job_load_timing =
1812 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1813 job_load_timing.connect_timing.connect_start =
1814 now - base::TimeDelta::FromDays(1);
1815 job_load_timing.connect_timing.connect_end =
1816 now - base::TimeDelta::FromDays(2);
1818 LoadTimingInfo load_timing_result =
1819 RunLoadTimingTest(job_load_timing, &default_context_);
1821 // Connect times should be replaced with proxy_resolve_end.
1822 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1823 load_timing_result.connect_timing.connect_start);
1824 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1825 load_timing_result.connect_timing.connect_end);
1827 // Other times should have been left null.
1828 TestLoadTimingNotReusedWithProxy(load_timing_result,
1829 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1832 // Check that two different URL requests have different identifiers.
1833 TEST_F(URLRequestTest, Identifiers) {
1834 TestDelegate d;
1835 TestURLRequestContext context;
1836 TestURLRequest req(
1837 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1838 TestURLRequest other_req(
1839 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1841 ASSERT_NE(req.identifier(), other_req.identifier());
1844 // Check that a failure to connect to the proxy is reported to the network
1845 // delegate.
1846 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1847 MockHostResolver host_resolver;
1848 host_resolver.rules()->AddSimulatedFailure("*");
1850 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
1851 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1853 TestDelegate d;
1854 URLRequest req(GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1855 req.set_method("GET");
1857 req.Start();
1858 base::RunLoop().Run();
1860 // Check we see a failed request.
1861 EXPECT_FALSE(req.status().is_success());
1862 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1863 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1865 EXPECT_EQ(1, network_delegate.error_count());
1866 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1867 EXPECT_EQ(1, network_delegate.completed_requests());
1870 // Make sure that net::NetworkDelegate::NotifyCompleted is called if
1871 // content is empty.
1872 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1873 TestDelegate d;
1874 URLRequest req(GURL("data:,"), DEFAULT_PRIORITY, &d, &default_context_);
1875 req.Start();
1876 base::RunLoop().Run();
1877 EXPECT_EQ("", d.data_received());
1878 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1881 // Make sure that SetPriority actually sets the URLRequest's priority
1882 // correctly, both before and after start.
1883 TEST_F(URLRequestTest, SetPriorityBasic) {
1884 TestDelegate d;
1885 URLRequest req(GURL("http://test_intercept/foo"),
1886 DEFAULT_PRIORITY,
1888 &default_context_);
1889 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1891 req.SetPriority(LOW);
1892 EXPECT_EQ(LOW, req.priority());
1894 req.Start();
1895 EXPECT_EQ(LOW, req.priority());
1897 req.SetPriority(MEDIUM);
1898 EXPECT_EQ(MEDIUM, req.priority());
1901 // Make sure that URLRequest calls SetPriority on a job before calling
1902 // Start on it.
1903 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1904 TestDelegate d;
1905 URLRequest req(GURL("http://test_intercept/foo"),
1906 DEFAULT_PRIORITY,
1908 &default_context_);
1909 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1911 scoped_refptr<URLRequestTestJob> job =
1912 new URLRequestTestJob(&req, &default_network_delegate_);
1913 AddTestInterceptor()->set_main_intercept_job(job.get());
1914 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1916 req.SetPriority(LOW);
1918 req.Start();
1919 EXPECT_EQ(LOW, job->priority());
1922 // Make sure that URLRequest passes on its priority updates to its
1923 // job.
1924 TEST_F(URLRequestTest, SetJobPriority) {
1925 TestDelegate d;
1926 URLRequest req(GURL("http://test_intercept/foo"),
1927 DEFAULT_PRIORITY,
1929 &default_context_);
1931 scoped_refptr<URLRequestTestJob> job =
1932 new URLRequestTestJob(&req, &default_network_delegate_);
1933 AddTestInterceptor()->set_main_intercept_job(job.get());
1935 req.SetPriority(LOW);
1936 req.Start();
1937 EXPECT_EQ(LOW, job->priority());
1939 req.SetPriority(MEDIUM);
1940 EXPECT_EQ(MEDIUM, req.priority());
1941 EXPECT_EQ(MEDIUM, job->priority());
1944 // Setting the IGNORE_LIMITS load flag should be okay if the priority
1945 // is MAXIMUM_PRIORITY.
1946 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1947 TestDelegate d;
1948 URLRequest req(GURL("http://test_intercept/foo"),
1949 MAXIMUM_PRIORITY,
1951 &default_context_);
1952 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1954 scoped_refptr<URLRequestTestJob> job =
1955 new URLRequestTestJob(&req, &default_network_delegate_);
1956 AddTestInterceptor()->set_main_intercept_job(job.get());
1958 req.SetLoadFlags(LOAD_IGNORE_LIMITS);
1959 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1961 req.SetPriority(MAXIMUM_PRIORITY);
1962 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1964 req.Start();
1965 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1966 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1969 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1970 #if !defined(OS_IOS)
1971 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
1972 // This is to work around mysterious failures in chrome_frame_net_tests. See:
1973 // http://crbug.com/114369
1974 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1975 class LocalHttpTestServer : public SpawnedTestServer {
1976 public:
1977 explicit LocalHttpTestServer(const base::FilePath& document_root)
1978 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1979 ScopedCustomUrlRequestTestHttpHost::value(),
1980 document_root) {}
1981 LocalHttpTestServer()
1982 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1983 ScopedCustomUrlRequestTestHttpHost::value(),
1984 base::FilePath()) {}
1987 TEST_F(URLRequestTest, DelayedCookieCallback) {
1988 LocalHttpTestServer test_server;
1989 ASSERT_TRUE(test_server.Start());
1991 TestURLRequestContext context;
1992 scoped_refptr<DelayedCookieMonster> delayed_cm =
1993 new DelayedCookieMonster();
1994 scoped_refptr<CookieStore> cookie_store = delayed_cm;
1995 context.set_cookie_store(delayed_cm.get());
1997 // Set up a cookie.
1999 TestNetworkDelegate network_delegate;
2000 context.set_network_delegate(&network_delegate);
2001 TestDelegate d;
2002 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2003 DEFAULT_PRIORITY,
2005 &context);
2006 req.Start();
2007 base::RunLoop().Run();
2008 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2009 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2010 EXPECT_EQ(1, network_delegate.set_cookie_count());
2013 // Verify that the cookie is set.
2015 TestNetworkDelegate network_delegate;
2016 context.set_network_delegate(&network_delegate);
2017 TestDelegate d;
2018 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2019 DEFAULT_PRIORITY,
2021 &context);
2022 req.Start();
2023 base::RunLoop().Run();
2025 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2026 != std::string::npos);
2027 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2028 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2032 TEST_F(URLRequestTest, DoNotSendCookies) {
2033 LocalHttpTestServer test_server;
2034 ASSERT_TRUE(test_server.Start());
2036 // Set up a cookie.
2038 TestNetworkDelegate network_delegate;
2039 default_context_.set_network_delegate(&network_delegate);
2040 TestDelegate d;
2041 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2042 DEFAULT_PRIORITY,
2044 &default_context_);
2045 req.Start();
2046 base::RunLoop().Run();
2047 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2048 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2051 // Verify that the cookie is set.
2053 TestNetworkDelegate network_delegate;
2054 default_context_.set_network_delegate(&network_delegate);
2055 TestDelegate d;
2056 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2057 DEFAULT_PRIORITY,
2059 &default_context_);
2060 req.Start();
2061 base::RunLoop().Run();
2063 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2064 != std::string::npos);
2065 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2066 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2069 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2071 TestNetworkDelegate network_delegate;
2072 default_context_.set_network_delegate(&network_delegate);
2073 TestDelegate d;
2074 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2075 DEFAULT_PRIORITY,
2077 &default_context_);
2078 req.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2079 req.Start();
2080 base::RunLoop().Run();
2082 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2083 == std::string::npos);
2085 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2086 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2087 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2091 TEST_F(URLRequestTest, DoNotSaveCookies) {
2092 LocalHttpTestServer test_server;
2093 ASSERT_TRUE(test_server.Start());
2095 // Set up a cookie.
2097 TestNetworkDelegate network_delegate;
2098 default_context_.set_network_delegate(&network_delegate);
2099 TestDelegate d;
2100 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2101 DEFAULT_PRIORITY,
2103 &default_context_);
2104 req.Start();
2105 base::RunLoop().Run();
2107 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2108 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2109 EXPECT_EQ(1, network_delegate.set_cookie_count());
2112 // Try to set-up another cookie and update the previous cookie.
2114 TestNetworkDelegate network_delegate;
2115 default_context_.set_network_delegate(&network_delegate);
2116 TestDelegate d;
2117 URLRequest req(
2118 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2119 DEFAULT_PRIORITY,
2121 &default_context_);
2122 req.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2123 req.Start();
2125 base::RunLoop().Run();
2127 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2128 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2129 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2130 EXPECT_EQ(0, network_delegate.set_cookie_count());
2133 // Verify the cookies weren't saved or updated.
2135 TestNetworkDelegate network_delegate;
2136 default_context_.set_network_delegate(&network_delegate);
2137 TestDelegate d;
2138 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2139 DEFAULT_PRIORITY,
2141 &default_context_);
2142 req.Start();
2143 base::RunLoop().Run();
2145 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2146 == std::string::npos);
2147 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2148 != std::string::npos);
2150 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2151 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2152 EXPECT_EQ(0, network_delegate.set_cookie_count());
2156 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2157 LocalHttpTestServer test_server;
2158 ASSERT_TRUE(test_server.Start());
2160 // Set up a cookie.
2162 TestNetworkDelegate network_delegate;
2163 default_context_.set_network_delegate(&network_delegate);
2164 TestDelegate d;
2165 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2166 DEFAULT_PRIORITY,
2168 &default_context_);
2169 req.Start();
2170 base::RunLoop().Run();
2172 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2173 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2176 // Verify that the cookie is set.
2178 TestNetworkDelegate network_delegate;
2179 default_context_.set_network_delegate(&network_delegate);
2180 TestDelegate d;
2181 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2182 DEFAULT_PRIORITY,
2184 &default_context_);
2185 req.Start();
2186 base::RunLoop().Run();
2188 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2189 != std::string::npos);
2191 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2192 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2195 // Verify that the cookie isn't sent.
2197 TestNetworkDelegate network_delegate;
2198 default_context_.set_network_delegate(&network_delegate);
2199 TestDelegate d;
2200 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2201 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2202 DEFAULT_PRIORITY,
2204 &default_context_);
2205 req.Start();
2206 base::RunLoop().Run();
2208 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2209 == std::string::npos);
2211 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2212 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2216 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2217 LocalHttpTestServer test_server;
2218 ASSERT_TRUE(test_server.Start());
2220 // Set up a cookie.
2222 TestNetworkDelegate network_delegate;
2223 default_context_.set_network_delegate(&network_delegate);
2224 TestDelegate d;
2225 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2226 DEFAULT_PRIORITY,
2228 &default_context_);
2229 req.Start();
2230 base::RunLoop().Run();
2232 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2233 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2236 // Try to set-up another cookie and update the previous cookie.
2238 TestNetworkDelegate network_delegate;
2239 default_context_.set_network_delegate(&network_delegate);
2240 TestDelegate d;
2241 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2242 URLRequest req(
2243 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2244 DEFAULT_PRIORITY,
2246 &default_context_);
2247 req.Start();
2249 base::RunLoop().Run();
2251 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2252 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2255 // Verify the cookies weren't saved or updated.
2257 TestNetworkDelegate network_delegate;
2258 default_context_.set_network_delegate(&network_delegate);
2259 TestDelegate d;
2260 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2261 DEFAULT_PRIORITY,
2263 &default_context_);
2264 req.Start();
2265 base::RunLoop().Run();
2267 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2268 == std::string::npos);
2269 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2270 != std::string::npos);
2272 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2273 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2277 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2278 LocalHttpTestServer test_server;
2279 ASSERT_TRUE(test_server.Start());
2281 // Set up an empty cookie.
2283 TestNetworkDelegate network_delegate;
2284 default_context_.set_network_delegate(&network_delegate);
2285 TestDelegate d;
2286 URLRequest req(test_server.GetURL("set-cookie"),
2287 DEFAULT_PRIORITY,
2289 &default_context_);
2290 req.Start();
2291 base::RunLoop().Run();
2293 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2294 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2295 EXPECT_EQ(0, network_delegate.set_cookie_count());
2299 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2300 LocalHttpTestServer test_server;
2301 ASSERT_TRUE(test_server.Start());
2303 // Set up a cookie.
2305 TestNetworkDelegate network_delegate;
2306 default_context_.set_network_delegate(&network_delegate);
2307 TestDelegate d;
2308 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2309 DEFAULT_PRIORITY,
2311 &default_context_);
2312 req.Start();
2313 base::RunLoop().Run();
2315 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2316 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2319 // Verify that the cookie is set.
2321 TestNetworkDelegate network_delegate;
2322 default_context_.set_network_delegate(&network_delegate);
2323 TestDelegate d;
2324 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2325 DEFAULT_PRIORITY,
2327 &default_context_);
2328 req.Start();
2329 base::RunLoop().Run();
2331 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2332 != std::string::npos);
2334 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2335 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2338 // Verify that the cookie isn't sent.
2340 TestNetworkDelegate network_delegate;
2341 default_context_.set_network_delegate(&network_delegate);
2342 TestDelegate d;
2343 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2344 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2345 DEFAULT_PRIORITY,
2347 &default_context_);
2348 req.Start();
2349 base::RunLoop().Run();
2351 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2352 == std::string::npos);
2354 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2355 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2359 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2360 LocalHttpTestServer test_server;
2361 ASSERT_TRUE(test_server.Start());
2363 // Set up a cookie.
2365 TestNetworkDelegate network_delegate;
2366 default_context_.set_network_delegate(&network_delegate);
2367 TestDelegate d;
2368 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2369 DEFAULT_PRIORITY,
2371 &default_context_);
2372 req.Start();
2373 base::RunLoop().Run();
2375 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2376 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2379 // Try to set-up another cookie and update the previous cookie.
2381 TestNetworkDelegate network_delegate;
2382 default_context_.set_network_delegate(&network_delegate);
2383 TestDelegate d;
2384 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2385 URLRequest req(
2386 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2387 DEFAULT_PRIORITY,
2389 &default_context_);
2390 req.Start();
2392 base::RunLoop().Run();
2394 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2395 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2398 // Verify the cookies weren't saved or updated.
2400 TestNetworkDelegate network_delegate;
2401 default_context_.set_network_delegate(&network_delegate);
2402 TestDelegate d;
2403 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2404 DEFAULT_PRIORITY,
2406 &default_context_);
2407 req.Start();
2408 base::RunLoop().Run();
2410 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2411 == std::string::npos);
2412 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2413 != std::string::npos);
2415 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2416 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2420 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2421 // value for the |fixed_date| argument given to the constructor.
2422 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2423 public:
2424 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2425 : fixed_date_(fixed_date) {}
2426 virtual ~FixedDateNetworkDelegate() {}
2428 // net::NetworkDelegate implementation
2429 virtual int OnHeadersReceived(
2430 net::URLRequest* request,
2431 const net::CompletionCallback& callback,
2432 const net::HttpResponseHeaders* original_response_headers,
2433 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2434 GURL* allowed_unsafe_redirect_url) OVERRIDE;
2436 private:
2437 std::string fixed_date_;
2439 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2442 int FixedDateNetworkDelegate::OnHeadersReceived(
2443 net::URLRequest* request,
2444 const net::CompletionCallback& callback,
2445 const net::HttpResponseHeaders* original_response_headers,
2446 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2447 GURL* allowed_unsafe_redirect_url) {
2448 net::HttpResponseHeaders* new_response_headers =
2449 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2451 new_response_headers->RemoveHeader("Date");
2452 new_response_headers->AddHeader("Date: " + fixed_date_);
2454 *override_response_headers = new_response_headers;
2455 return TestNetworkDelegate::OnHeadersReceived(request,
2456 callback,
2457 original_response_headers,
2458 override_response_headers,
2459 allowed_unsafe_redirect_url);
2462 // Test that cookie expiration times are adjusted for server/client clock
2463 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2464 // headers by defaulting to GMT. (crbug.com/135131)
2465 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2466 LocalHttpTestServer test_server;
2467 ASSERT_TRUE(test_server.Start());
2469 // Set up an expired cookie.
2471 TestNetworkDelegate network_delegate;
2472 default_context_.set_network_delegate(&network_delegate);
2473 TestDelegate d;
2474 URLRequest req(
2475 test_server.GetURL(
2476 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2477 DEFAULT_PRIORITY,
2479 &default_context_);
2480 req.Start();
2481 base::RunLoop().Run();
2483 // Verify that the cookie is not set.
2485 TestNetworkDelegate network_delegate;
2486 default_context_.set_network_delegate(&network_delegate);
2487 TestDelegate d;
2488 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2489 DEFAULT_PRIORITY,
2491 &default_context_);
2492 req.Start();
2493 base::RunLoop().Run();
2495 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2497 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2499 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2500 default_context_.set_network_delegate(&network_delegate);
2501 TestDelegate d;
2502 URLRequest req(
2503 test_server.GetURL(
2504 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2505 DEFAULT_PRIORITY,
2507 &default_context_);
2508 req.Start();
2509 base::RunLoop().Run();
2511 // Verify that the cookie is set.
2513 TestNetworkDelegate network_delegate;
2514 default_context_.set_network_delegate(&network_delegate);
2515 TestDelegate d;
2516 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2517 DEFAULT_PRIORITY,
2519 &default_context_);
2520 req.Start();
2521 base::RunLoop().Run();
2523 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2528 // Check that it is impossible to change the referrer in the extra headers of
2529 // an URLRequest.
2530 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2531 LocalHttpTestServer test_server;
2532 ASSERT_TRUE(test_server.Start());
2534 // If extra headers contain referer and the request contains a referer,
2535 // only the latter shall be respected.
2537 TestDelegate d;
2538 URLRequest req(test_server.GetURL("echoheader?Referer"),
2539 DEFAULT_PRIORITY,
2541 &default_context_);
2542 req.SetReferrer("http://foo.com/");
2544 HttpRequestHeaders headers;
2545 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2546 req.SetExtraRequestHeaders(headers);
2548 req.Start();
2549 base::RunLoop().Run();
2551 EXPECT_EQ("http://foo.com/", d.data_received());
2554 // If extra headers contain a referer but the request does not, no referer
2555 // shall be sent in the header.
2557 TestDelegate d;
2558 URLRequest req(test_server.GetURL("echoheader?Referer"),
2559 DEFAULT_PRIORITY,
2561 &default_context_);
2563 HttpRequestHeaders headers;
2564 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2565 req.SetExtraRequestHeaders(headers);
2566 req.SetLoadFlags(LOAD_VALIDATE_CACHE);
2568 req.Start();
2569 base::RunLoop().Run();
2571 EXPECT_EQ("None", d.data_received());
2575 class URLRequestTestHTTP : public URLRequestTest {
2576 public:
2577 URLRequestTestHTTP()
2578 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2579 "net/data/url_request_unittest"))) {
2582 protected:
2583 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2584 // |request_method| is the method to use for the initial request.
2585 // |redirect_method| is the method that is expected to be used for the second
2586 // request, after redirection.
2587 // If |include_data| is true, data is uploaded with the request. The
2588 // response body is expected to match it exactly, if and only if
2589 // |request_method| == |redirect_method|.
2590 void HTTPRedirectMethodTest(const GURL& redirect_url,
2591 const std::string& request_method,
2592 const std::string& redirect_method,
2593 bool include_data) {
2594 static const char kData[] = "hello world";
2595 TestDelegate d;
2596 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
2597 req.set_method(request_method);
2598 if (include_data) {
2599 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2600 HttpRequestHeaders headers;
2601 headers.SetHeader(HttpRequestHeaders::kContentLength,
2602 base::UintToString(arraysize(kData) - 1));
2603 req.SetExtraRequestHeaders(headers);
2605 req.Start();
2606 base::RunLoop().Run();
2607 EXPECT_EQ(redirect_method, req.method());
2608 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2609 EXPECT_EQ(OK, req.status().error());
2610 if (include_data) {
2611 if (request_method == redirect_method) {
2612 EXPECT_EQ(kData, d.data_received());
2613 } else {
2614 EXPECT_NE(kData, d.data_received());
2617 if (HasFailure())
2618 LOG(WARNING) << "Request method was: " << request_method;
2621 void HTTPUploadDataOperationTest(const std::string& method) {
2622 const int kMsgSize = 20000; // multiple of 10
2623 const int kIterations = 50;
2624 char* uploadBytes = new char[kMsgSize+1];
2625 char* ptr = uploadBytes;
2626 char marker = 'a';
2627 for (int idx = 0; idx < kMsgSize/10; idx++) {
2628 memcpy(ptr, "----------", 10);
2629 ptr += 10;
2630 if (idx % 100 == 0) {
2631 ptr--;
2632 *ptr++ = marker;
2633 if (++marker > 'z')
2634 marker = 'a';
2637 uploadBytes[kMsgSize] = '\0';
2639 for (int i = 0; i < kIterations; ++i) {
2640 TestDelegate d;
2641 URLRequest r(
2642 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
2643 r.set_method(method.c_str());
2645 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
2647 r.Start();
2648 EXPECT_TRUE(r.is_pending());
2650 base::RunLoop().Run();
2652 ASSERT_EQ(1, d.response_started_count())
2653 << "request failed: " << r.status().status()
2654 << ", os error: " << r.status().error();
2656 EXPECT_FALSE(d.received_data_before_response());
2657 EXPECT_EQ(uploadBytes, d.data_received());
2659 delete[] uploadBytes;
2662 void AddChunksToUpload(URLRequest* r) {
2663 r->AppendChunkToUpload("a", 1, false);
2664 r->AppendChunkToUpload("bcd", 3, false);
2665 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2666 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2667 r->AppendChunkToUpload("0", 1, false);
2668 r->AppendChunkToUpload("2323", 4, true);
2671 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2672 // This should match the chunks sent by AddChunksToUpload().
2673 const std::string expected_data =
2674 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2676 ASSERT_EQ(1, d->response_started_count())
2677 << "request failed: " << r->status().status()
2678 << ", os error: " << r->status().error();
2680 EXPECT_FALSE(d->received_data_before_response());
2682 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2683 EXPECT_EQ(expected_data, d->data_received());
2686 bool DoManyCookiesRequest(int num_cookies) {
2687 TestDelegate d;
2688 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2689 base::IntToString(num_cookies)),
2690 DEFAULT_PRIORITY,
2692 &default_context_);
2694 r.Start();
2695 EXPECT_TRUE(r.is_pending());
2697 base::RunLoop().Run();
2699 bool is_success = r.status().is_success();
2701 if (!is_success) {
2702 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2703 // The test server appears to be unable to handle subsequent requests
2704 // after this error is triggered. Force it to restart.
2705 EXPECT_TRUE(test_server_.Stop());
2706 EXPECT_TRUE(test_server_.Start());
2709 return is_success;
2712 LocalHttpTestServer test_server_;
2715 // In this unit test, we're using the HTTPTestServer as a proxy server and
2716 // issuing a CONNECT request with the magic host name "www.redirect.com".
2717 // The HTTPTestServer will return a 302 response, which we should not
2718 // follow.
2719 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2720 ASSERT_TRUE(test_server_.Start());
2722 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2723 TestURLRequestContextWithProxy context(
2724 test_server_.host_port_pair().ToString(), &network_delegate);
2726 TestDelegate d;
2728 URLRequest r(
2729 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2730 r.Start();
2731 EXPECT_TRUE(r.is_pending());
2733 base::RunLoop().Run();
2735 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2736 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2737 EXPECT_EQ(1, d.response_started_count());
2738 // We should not have followed the redirect.
2739 EXPECT_EQ(0, d.received_redirect_count());
2743 // This is the same as the previous test, but checks that the network delegate
2744 // registers the error.
2745 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
2746 ASSERT_TRUE(test_server_.Start());
2748 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2749 TestURLRequestContextWithProxy context(
2750 test_server_.host_port_pair().ToString(), &network_delegate);
2752 TestDelegate d;
2754 URLRequest r(
2755 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2756 r.Start();
2757 EXPECT_TRUE(r.is_pending());
2759 base::RunLoop().Run();
2761 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2762 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2763 EXPECT_EQ(1, d.response_started_count());
2764 // We should not have followed the redirect.
2765 EXPECT_EQ(0, d.received_redirect_count());
2767 EXPECT_EQ(1, network_delegate.error_count());
2768 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
2772 // Tests that we can block and asynchronously return OK in various stages.
2773 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2774 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2775 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2776 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2777 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2779 static const size_t blocking_stages_length = arraysize(blocking_stages);
2781 ASSERT_TRUE(test_server_.Start());
2783 TestDelegate d;
2784 BlockingNetworkDelegate network_delegate(
2785 BlockingNetworkDelegate::USER_CALLBACK);
2786 network_delegate.set_block_on(
2787 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2788 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2789 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2791 TestURLRequestContext context(true);
2792 context.set_network_delegate(&network_delegate);
2793 context.Init();
2796 URLRequest r(
2797 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, &context);
2799 r.Start();
2800 for (size_t i = 0; i < blocking_stages_length; ++i) {
2801 base::RunLoop().Run();
2802 EXPECT_EQ(blocking_stages[i],
2803 network_delegate.stage_blocked_for_callback());
2804 network_delegate.DoCallback(OK);
2806 base::RunLoop().Run();
2807 EXPECT_EQ(200, r.GetResponseCode());
2808 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2809 EXPECT_EQ(1, network_delegate.created_requests());
2810 EXPECT_EQ(0, network_delegate.destroyed_requests());
2812 EXPECT_EQ(1, network_delegate.destroyed_requests());
2815 // Tests that the network delegate can block and cancel a request.
2816 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2817 ASSERT_TRUE(test_server_.Start());
2819 TestDelegate d;
2820 BlockingNetworkDelegate network_delegate(
2821 BlockingNetworkDelegate::AUTO_CALLBACK);
2822 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2823 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
2825 TestURLRequestContextWithProxy context(
2826 test_server_.host_port_pair().ToString(), &network_delegate);
2829 URLRequest r(
2830 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
2832 r.Start();
2833 base::RunLoop().Run();
2835 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2836 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
2837 EXPECT_EQ(1, network_delegate.created_requests());
2838 EXPECT_EQ(0, network_delegate.destroyed_requests());
2840 EXPECT_EQ(1, network_delegate.destroyed_requests());
2843 // Helper function for NetworkDelegateCancelRequestAsynchronously and
2844 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2845 // delegate operating in |block_mode| and a request for |url|. It blocks the
2846 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2847 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2848 BlockingNetworkDelegate::Stage stage,
2849 const GURL& url) {
2850 TestDelegate d;
2851 BlockingNetworkDelegate network_delegate(block_mode);
2852 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2853 network_delegate.set_block_on(stage);
2855 TestURLRequestContext context(true);
2856 context.set_network_delegate(&network_delegate);
2857 context.Init();
2860 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
2862 r.Start();
2863 base::RunLoop().Run();
2865 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2866 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
2867 EXPECT_EQ(1, network_delegate.created_requests());
2868 EXPECT_EQ(0, network_delegate.destroyed_requests());
2870 EXPECT_EQ(1, network_delegate.destroyed_requests());
2873 // The following 3 tests check that the network delegate can cancel a request
2874 // synchronously in various stages of the request.
2875 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2876 ASSERT_TRUE(test_server_.Start());
2877 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2878 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2879 test_server_.GetURL(std::string()));
2882 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2883 ASSERT_TRUE(test_server_.Start());
2884 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2885 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2886 test_server_.GetURL(std::string()));
2889 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2890 ASSERT_TRUE(test_server_.Start());
2891 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2892 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2893 test_server_.GetURL(std::string()));
2896 // The following 3 tests check that the network delegate can cancel a request
2897 // asynchronously in various stages of the request.
2898 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2899 ASSERT_TRUE(test_server_.Start());
2900 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2901 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2902 test_server_.GetURL(std::string()));
2905 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2906 ASSERT_TRUE(test_server_.Start());
2907 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2908 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2909 test_server_.GetURL(std::string()));
2912 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2913 ASSERT_TRUE(test_server_.Start());
2914 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2915 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2916 test_server_.GetURL(std::string()));
2919 // Tests that the network delegate can block and redirect a request to a new
2920 // URL.
2921 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2922 ASSERT_TRUE(test_server_.Start());
2924 TestDelegate d;
2925 BlockingNetworkDelegate network_delegate(
2926 BlockingNetworkDelegate::AUTO_CALLBACK);
2927 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2928 GURL redirect_url(test_server_.GetURL("simple.html"));
2929 network_delegate.set_redirect_url(redirect_url);
2931 TestURLRequestContextWithProxy context(
2932 test_server_.host_port_pair().ToString(), &network_delegate);
2935 GURL original_url(test_server_.GetURL("empty.html"));
2936 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2938 r.Start();
2939 base::RunLoop().Run();
2941 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2942 EXPECT_EQ(0, r.status().error());
2943 EXPECT_EQ(redirect_url, r.url());
2944 EXPECT_EQ(original_url, r.original_url());
2945 EXPECT_EQ(2U, r.url_chain().size());
2946 EXPECT_EQ(1, network_delegate.created_requests());
2947 EXPECT_EQ(0, network_delegate.destroyed_requests());
2949 EXPECT_EQ(1, network_delegate.destroyed_requests());
2952 // Tests that the network delegate can block and redirect a request to a new
2953 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2954 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2955 ASSERT_TRUE(test_server_.Start());
2957 TestDelegate d;
2958 BlockingNetworkDelegate network_delegate(
2959 BlockingNetworkDelegate::SYNCHRONOUS);
2960 GURL redirect_url(test_server_.GetURL("simple.html"));
2961 network_delegate.set_redirect_url(redirect_url);
2963 TestURLRequestContextWithProxy context(
2964 test_server_.host_port_pair().ToString(), &network_delegate);
2967 GURL original_url(test_server_.GetURL("empty.html"));
2968 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2970 r.Start();
2971 base::RunLoop().Run();
2973 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2974 EXPECT_EQ(0, r.status().error());
2975 EXPECT_EQ(redirect_url, r.url());
2976 EXPECT_EQ(original_url, r.original_url());
2977 EXPECT_EQ(2U, r.url_chain().size());
2978 EXPECT_EQ(1, network_delegate.created_requests());
2979 EXPECT_EQ(0, network_delegate.destroyed_requests());
2981 EXPECT_EQ(1, network_delegate.destroyed_requests());
2984 // Tests that redirects caused by the network delegate preserve POST data.
2985 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2986 ASSERT_TRUE(test_server_.Start());
2988 const char kData[] = "hello world";
2990 TestDelegate d;
2991 BlockingNetworkDelegate network_delegate(
2992 BlockingNetworkDelegate::AUTO_CALLBACK);
2993 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2994 GURL redirect_url(test_server_.GetURL("echo"));
2995 network_delegate.set_redirect_url(redirect_url);
2997 TestURLRequestContext context(true);
2998 context.set_network_delegate(&network_delegate);
2999 context.Init();
3002 GURL original_url(test_server_.GetURL("empty.html"));
3003 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
3004 r.set_method("POST");
3005 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
3006 HttpRequestHeaders headers;
3007 headers.SetHeader(HttpRequestHeaders::kContentLength,
3008 base::UintToString(arraysize(kData) - 1));
3009 r.SetExtraRequestHeaders(headers);
3010 r.Start();
3011 base::RunLoop().Run();
3013 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3014 EXPECT_EQ(0, r.status().error());
3015 EXPECT_EQ(redirect_url, r.url());
3016 EXPECT_EQ(original_url, r.original_url());
3017 EXPECT_EQ(2U, r.url_chain().size());
3018 EXPECT_EQ(1, network_delegate.created_requests());
3019 EXPECT_EQ(0, network_delegate.destroyed_requests());
3020 EXPECT_EQ("POST", r.method());
3021 EXPECT_EQ(kData, d.data_received());
3023 EXPECT_EQ(1, network_delegate.destroyed_requests());
3026 // Tests that the network delegate can block and redirect a request to a new
3027 // URL during OnHeadersReceived.
3028 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3029 ASSERT_TRUE(test_server_.Start());
3031 TestDelegate d;
3032 BlockingNetworkDelegate network_delegate(
3033 BlockingNetworkDelegate::AUTO_CALLBACK);
3034 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3035 GURL redirect_url(test_server_.GetURL("simple.html"));
3036 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3038 TestURLRequestContextWithProxy context(
3039 test_server_.host_port_pair().ToString(), &network_delegate);
3042 GURL original_url(test_server_.GetURL("empty.html"));
3043 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
3045 r.Start();
3046 base::RunLoop().Run();
3048 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3049 EXPECT_EQ(net::OK, r.status().error());
3050 EXPECT_EQ(redirect_url, r.url());
3051 EXPECT_EQ(original_url, r.original_url());
3052 EXPECT_EQ(2U, r.url_chain().size());
3053 EXPECT_EQ(2, network_delegate.created_requests());
3054 EXPECT_EQ(0, network_delegate.destroyed_requests());
3056 EXPECT_EQ(1, network_delegate.destroyed_requests());
3059 // Tests that the network delegate can synchronously complete OnAuthRequired
3060 // by taking no action. This indicates that the NetworkDelegate does not want to
3061 // handle the challenge, and is passing the buck along to the
3062 // URLRequest::Delegate.
3063 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3064 ASSERT_TRUE(test_server_.Start());
3066 TestDelegate d;
3067 BlockingNetworkDelegate network_delegate(
3068 BlockingNetworkDelegate::SYNCHRONOUS);
3070 TestURLRequestContext context(true);
3071 context.set_network_delegate(&network_delegate);
3072 context.Init();
3074 d.set_credentials(AuthCredentials(kUser, kSecret));
3077 GURL url(test_server_.GetURL("auth-basic"));
3078 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3079 r.Start();
3081 base::RunLoop().Run();
3083 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3084 EXPECT_EQ(0, r.status().error());
3085 EXPECT_EQ(200, r.GetResponseCode());
3086 EXPECT_TRUE(d.auth_required_called());
3087 EXPECT_EQ(1, network_delegate.created_requests());
3088 EXPECT_EQ(0, network_delegate.destroyed_requests());
3090 EXPECT_EQ(1, network_delegate.destroyed_requests());
3093 TEST_F(URLRequestTestHTTP,
3094 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3095 ASSERT_TRUE(test_server_.Start());
3097 TestDelegate d;
3098 BlockingNetworkDelegate network_delegate(
3099 BlockingNetworkDelegate::SYNCHRONOUS);
3101 TestURLRequestContext context(true);
3102 context.set_network_delegate(&network_delegate);
3103 context.Init();
3105 d.set_credentials(AuthCredentials(kUser, kSecret));
3108 GURL url(test_server_.GetURL("auth-basic"));
3109 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3110 r.Start();
3113 HttpRequestHeaders headers;
3114 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3115 EXPECT_FALSE(headers.HasHeader("Authorization"));
3118 base::RunLoop().Run();
3120 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3121 EXPECT_EQ(0, r.status().error());
3122 EXPECT_EQ(200, r.GetResponseCode());
3123 EXPECT_TRUE(d.auth_required_called());
3124 EXPECT_EQ(1, network_delegate.created_requests());
3125 EXPECT_EQ(0, network_delegate.destroyed_requests());
3127 EXPECT_EQ(1, network_delegate.destroyed_requests());
3130 // Tests that the network delegate can synchronously complete OnAuthRequired
3131 // by setting credentials.
3132 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3133 ASSERT_TRUE(test_server_.Start());
3135 TestDelegate d;
3136 BlockingNetworkDelegate network_delegate(
3137 BlockingNetworkDelegate::SYNCHRONOUS);
3138 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3139 network_delegate.set_auth_retval(
3140 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3142 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3144 TestURLRequestContext context(true);
3145 context.set_network_delegate(&network_delegate);
3146 context.Init();
3149 GURL url(test_server_.GetURL("auth-basic"));
3150 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3151 r.Start();
3152 base::RunLoop().Run();
3154 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3155 EXPECT_EQ(0, r.status().error());
3156 EXPECT_EQ(200, r.GetResponseCode());
3157 EXPECT_FALSE(d.auth_required_called());
3158 EXPECT_EQ(1, network_delegate.created_requests());
3159 EXPECT_EQ(0, network_delegate.destroyed_requests());
3161 EXPECT_EQ(1, network_delegate.destroyed_requests());
3164 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3165 // headers (for the first or second request) when called at the proper times.
3166 TEST_F(URLRequestTestHTTP,
3167 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3168 ASSERT_TRUE(test_server_.Start());
3170 TestDelegate d;
3171 BlockingNetworkDelegate network_delegate(
3172 BlockingNetworkDelegate::SYNCHRONOUS);
3173 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3174 network_delegate.set_auth_retval(
3175 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3177 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3179 TestURLRequestContext context(true);
3180 context.set_network_delegate(&network_delegate);
3181 context.Init();
3184 GURL url(test_server_.GetURL("auth-basic"));
3185 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3186 r.Start();
3187 base::RunLoop().Run();
3189 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3190 EXPECT_EQ(0, r.status().error());
3191 EXPECT_EQ(200, r.GetResponseCode());
3192 EXPECT_FALSE(d.auth_required_called());
3193 EXPECT_EQ(1, network_delegate.created_requests());
3194 EXPECT_EQ(0, network_delegate.destroyed_requests());
3197 HttpRequestHeaders headers;
3198 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3199 EXPECT_TRUE(headers.HasHeader("Authorization"));
3202 EXPECT_EQ(1, network_delegate.destroyed_requests());
3205 // Tests that the network delegate can synchronously complete OnAuthRequired
3206 // by cancelling authentication.
3207 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3208 ASSERT_TRUE(test_server_.Start());
3210 TestDelegate d;
3211 BlockingNetworkDelegate network_delegate(
3212 BlockingNetworkDelegate::SYNCHRONOUS);
3213 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3214 network_delegate.set_auth_retval(
3215 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3217 TestURLRequestContext context(true);
3218 context.set_network_delegate(&network_delegate);
3219 context.Init();
3222 GURL url(test_server_.GetURL("auth-basic"));
3223 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3224 r.Start();
3225 base::RunLoop().Run();
3227 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3228 EXPECT_EQ(OK, r.status().error());
3229 EXPECT_EQ(401, r.GetResponseCode());
3230 EXPECT_FALSE(d.auth_required_called());
3231 EXPECT_EQ(1, network_delegate.created_requests());
3232 EXPECT_EQ(0, network_delegate.destroyed_requests());
3234 EXPECT_EQ(1, network_delegate.destroyed_requests());
3237 // Tests that the network delegate can asynchronously complete OnAuthRequired
3238 // by taking no action. This indicates that the NetworkDelegate does not want
3239 // to handle the challenge, and is passing the buck along to the
3240 // URLRequest::Delegate.
3241 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3242 ASSERT_TRUE(test_server_.Start());
3244 TestDelegate d;
3245 BlockingNetworkDelegate network_delegate(
3246 BlockingNetworkDelegate::AUTO_CALLBACK);
3247 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3249 TestURLRequestContext context(true);
3250 context.set_network_delegate(&network_delegate);
3251 context.Init();
3253 d.set_credentials(AuthCredentials(kUser, kSecret));
3256 GURL url(test_server_.GetURL("auth-basic"));
3257 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3258 r.Start();
3259 base::RunLoop().Run();
3261 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3262 EXPECT_EQ(0, r.status().error());
3263 EXPECT_EQ(200, r.GetResponseCode());
3264 EXPECT_TRUE(d.auth_required_called());
3265 EXPECT_EQ(1, network_delegate.created_requests());
3266 EXPECT_EQ(0, network_delegate.destroyed_requests());
3268 EXPECT_EQ(1, network_delegate.destroyed_requests());
3271 // Tests that the network delegate can asynchronously complete OnAuthRequired
3272 // by setting credentials.
3273 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3274 ASSERT_TRUE(test_server_.Start());
3276 TestDelegate d;
3277 BlockingNetworkDelegate network_delegate(
3278 BlockingNetworkDelegate::AUTO_CALLBACK);
3279 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3280 network_delegate.set_auth_retval(
3281 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3283 AuthCredentials auth_credentials(kUser, kSecret);
3284 network_delegate.set_auth_credentials(auth_credentials);
3286 TestURLRequestContext context(true);
3287 context.set_network_delegate(&network_delegate);
3288 context.Init();
3291 GURL url(test_server_.GetURL("auth-basic"));
3292 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3293 r.Start();
3294 base::RunLoop().Run();
3296 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3297 EXPECT_EQ(0, r.status().error());
3299 EXPECT_EQ(200, r.GetResponseCode());
3300 EXPECT_FALSE(d.auth_required_called());
3301 EXPECT_EQ(1, network_delegate.created_requests());
3302 EXPECT_EQ(0, network_delegate.destroyed_requests());
3304 EXPECT_EQ(1, network_delegate.destroyed_requests());
3307 // Tests that the network delegate can asynchronously complete OnAuthRequired
3308 // by cancelling authentication.
3309 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3310 ASSERT_TRUE(test_server_.Start());
3312 TestDelegate d;
3313 BlockingNetworkDelegate network_delegate(
3314 BlockingNetworkDelegate::AUTO_CALLBACK);
3315 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3316 network_delegate.set_auth_retval(
3317 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3319 TestURLRequestContext context(true);
3320 context.set_network_delegate(&network_delegate);
3321 context.Init();
3324 GURL url(test_server_.GetURL("auth-basic"));
3325 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3326 r.Start();
3327 base::RunLoop().Run();
3329 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3330 EXPECT_EQ(OK, r.status().error());
3331 EXPECT_EQ(401, r.GetResponseCode());
3332 EXPECT_FALSE(d.auth_required_called());
3333 EXPECT_EQ(1, network_delegate.created_requests());
3334 EXPECT_EQ(0, network_delegate.destroyed_requests());
3336 EXPECT_EQ(1, network_delegate.destroyed_requests());
3339 // Tests that we can handle when a network request was canceled while we were
3340 // waiting for the network delegate.
3341 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3342 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3343 ASSERT_TRUE(test_server_.Start());
3345 TestDelegate d;
3346 BlockingNetworkDelegate network_delegate(
3347 BlockingNetworkDelegate::USER_CALLBACK);
3348 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3350 TestURLRequestContext context(true);
3351 context.set_network_delegate(&network_delegate);
3352 context.Init();
3355 URLRequest r(
3356 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3358 r.Start();
3359 base::RunLoop().Run();
3360 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3361 network_delegate.stage_blocked_for_callback());
3362 EXPECT_EQ(0, network_delegate.completed_requests());
3363 // Cancel before callback.
3364 r.Cancel();
3365 // Ensure that network delegate is notified.
3366 EXPECT_EQ(1, network_delegate.completed_requests());
3367 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3368 EXPECT_EQ(ERR_ABORTED, r.status().error());
3369 EXPECT_EQ(1, network_delegate.created_requests());
3370 EXPECT_EQ(0, network_delegate.destroyed_requests());
3372 EXPECT_EQ(1, network_delegate.destroyed_requests());
3375 // Tests that we can handle when a network request was canceled while we were
3376 // waiting for the network delegate.
3377 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3378 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3379 ASSERT_TRUE(test_server_.Start());
3381 TestDelegate d;
3382 BlockingNetworkDelegate network_delegate(
3383 BlockingNetworkDelegate::USER_CALLBACK);
3384 network_delegate.set_block_on(
3385 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
3387 TestURLRequestContext context(true);
3388 context.set_network_delegate(&network_delegate);
3389 context.Init();
3392 URLRequest r(
3393 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3395 r.Start();
3396 base::RunLoop().Run();
3397 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3398 network_delegate.stage_blocked_for_callback());
3399 EXPECT_EQ(0, network_delegate.completed_requests());
3400 // Cancel before callback.
3401 r.Cancel();
3402 // Ensure that network delegate is notified.
3403 EXPECT_EQ(1, network_delegate.completed_requests());
3404 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3405 EXPECT_EQ(ERR_ABORTED, r.status().error());
3406 EXPECT_EQ(1, network_delegate.created_requests());
3407 EXPECT_EQ(0, network_delegate.destroyed_requests());
3409 EXPECT_EQ(1, network_delegate.destroyed_requests());
3412 // Tests that we can handle when a network request was canceled while we were
3413 // waiting for the network delegate.
3414 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3415 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3416 ASSERT_TRUE(test_server_.Start());
3418 TestDelegate d;
3419 BlockingNetworkDelegate network_delegate(
3420 BlockingNetworkDelegate::USER_CALLBACK);
3421 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3423 TestURLRequestContext context(true);
3424 context.set_network_delegate(&network_delegate);
3425 context.Init();
3428 URLRequest r(
3429 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3431 r.Start();
3432 base::RunLoop().Run();
3433 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3434 network_delegate.stage_blocked_for_callback());
3435 EXPECT_EQ(0, network_delegate.completed_requests());
3436 // Cancel before callback.
3437 r.Cancel();
3438 // Ensure that network delegate is notified.
3439 EXPECT_EQ(1, network_delegate.completed_requests());
3440 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3441 EXPECT_EQ(ERR_ABORTED, r.status().error());
3442 EXPECT_EQ(1, network_delegate.created_requests());
3443 EXPECT_EQ(0, network_delegate.destroyed_requests());
3445 EXPECT_EQ(1, network_delegate.destroyed_requests());
3448 // Tests that we can handle when a network request was canceled while we were
3449 // waiting for the network delegate.
3450 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3451 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
3452 ASSERT_TRUE(test_server_.Start());
3454 TestDelegate d;
3455 BlockingNetworkDelegate network_delegate(
3456 BlockingNetworkDelegate::USER_CALLBACK);
3457 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3459 TestURLRequestContext context(true);
3460 context.set_network_delegate(&network_delegate);
3461 context.Init();
3464 URLRequest r(
3465 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, &context);
3467 r.Start();
3468 base::RunLoop().Run();
3469 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3470 network_delegate.stage_blocked_for_callback());
3471 EXPECT_EQ(0, network_delegate.completed_requests());
3472 // Cancel before callback.
3473 r.Cancel();
3474 // Ensure that network delegate is notified.
3475 EXPECT_EQ(1, network_delegate.completed_requests());
3476 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3477 EXPECT_EQ(ERR_ABORTED, r.status().error());
3478 EXPECT_EQ(1, network_delegate.created_requests());
3479 EXPECT_EQ(0, network_delegate.destroyed_requests());
3481 EXPECT_EQ(1, network_delegate.destroyed_requests());
3484 // In this unit test, we're using the HTTPTestServer as a proxy server and
3485 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3486 // The HTTPTestServer will return a 401 response, which we should balk at.
3487 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
3488 ASSERT_TRUE(test_server_.Start());
3490 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3491 TestURLRequestContextWithProxy context(
3492 test_server_.host_port_pair().ToString(), &network_delegate);
3494 TestDelegate d;
3496 URLRequest r(
3497 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, &context);
3499 r.Start();
3500 EXPECT_TRUE(r.is_pending());
3502 base::RunLoop().Run();
3504 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3505 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
3509 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
3510 ASSERT_TRUE(test_server_.Start());
3512 TestDelegate d;
3514 URLRequest r(test_server_.GetURL(std::string()),
3515 DEFAULT_PRIORITY,
3517 &default_context_);
3519 r.Start();
3520 EXPECT_TRUE(r.is_pending());
3522 base::RunLoop().Run();
3524 EXPECT_EQ(1, d.response_started_count());
3525 EXPECT_FALSE(d.received_data_before_response());
3526 EXPECT_NE(0, d.bytes_received());
3527 EXPECT_EQ(test_server_.host_port_pair().host(),
3528 r.GetSocketAddress().host());
3529 EXPECT_EQ(test_server_.host_port_pair().port(),
3530 r.GetSocketAddress().port());
3532 // TODO(eroman): Add back the NetLog tests...
3536 // This test has the server send a large number of cookies to the client.
3537 // To ensure that no number of cookies causes a crash, a galloping binary
3538 // search is used to estimate that maximum number of cookies that are accepted
3539 // by the browser. Beyond the maximum number, the request will fail with
3540 // ERR_RESPONSE_HEADERS_TOO_BIG.
3541 #if defined(OS_WIN)
3542 // http://crbug.com/177916
3543 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3544 #else
3545 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3546 #endif // defined(OS_WIN)
3547 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
3548 ASSERT_TRUE(test_server_.Start());
3550 int lower_bound = 0;
3551 int upper_bound = 1;
3553 // Double the number of cookies until the response header limits are
3554 // exceeded.
3555 while (DoManyCookiesRequest(upper_bound)) {
3556 lower_bound = upper_bound;
3557 upper_bound *= 2;
3558 ASSERT_LT(upper_bound, 1000000);
3561 int tolerance = upper_bound * 0.005;
3562 if (tolerance < 2)
3563 tolerance = 2;
3565 // Perform a binary search to find the highest possible number of cookies,
3566 // within the desired tolerance.
3567 while (upper_bound - lower_bound >= tolerance) {
3568 int num_cookies = (lower_bound + upper_bound) / 2;
3570 if (DoManyCookiesRequest(num_cookies))
3571 lower_bound = num_cookies;
3572 else
3573 upper_bound = num_cookies;
3575 // Success: the test did not crash.
3578 TEST_F(URLRequestTestHTTP, GetTest) {
3579 ASSERT_TRUE(test_server_.Start());
3581 TestDelegate d;
3583 URLRequest r(test_server_.GetURL(std::string()),
3584 DEFAULT_PRIORITY,
3586 &default_context_);
3588 r.Start();
3589 EXPECT_TRUE(r.is_pending());
3591 base::RunLoop().Run();
3593 EXPECT_EQ(1, d.response_started_count());
3594 EXPECT_FALSE(d.received_data_before_response());
3595 EXPECT_NE(0, d.bytes_received());
3596 EXPECT_EQ(test_server_.host_port_pair().host(),
3597 r.GetSocketAddress().host());
3598 EXPECT_EQ(test_server_.host_port_pair().port(),
3599 r.GetSocketAddress().port());
3603 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3604 ASSERT_TRUE(test_server_.Start());
3606 TestDelegate d;
3608 GURL test_url(test_server_.GetURL(std::string()));
3609 URLRequest r(test_url, DEFAULT_PRIORITY, &d, &default_context_);
3611 HttpRequestHeaders headers;
3612 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3614 r.Start();
3615 EXPECT_TRUE(r.is_pending());
3617 base::RunLoop().Run();
3619 EXPECT_EQ(1, d.response_started_count());
3620 EXPECT_FALSE(d.received_data_before_response());
3621 EXPECT_NE(0, d.bytes_received());
3622 EXPECT_EQ(test_server_.host_port_pair().host(),
3623 r.GetSocketAddress().host());
3624 EXPECT_EQ(test_server_.host_port_pair().port(),
3625 r.GetSocketAddress().port());
3627 EXPECT_TRUE(d.have_full_request_headers());
3628 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3632 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3633 ASSERT_TRUE(test_server_.Start());
3635 TestDelegate d;
3637 URLRequest r(test_server_.GetURL(std::string()),
3638 DEFAULT_PRIORITY,
3640 &default_context_);
3642 r.Start();
3643 EXPECT_TRUE(r.is_pending());
3645 base::RunLoop().Run();
3647 LoadTimingInfo load_timing_info;
3648 r.GetLoadTimingInfo(&load_timing_info);
3649 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3651 EXPECT_EQ(1, d.response_started_count());
3652 EXPECT_FALSE(d.received_data_before_response());
3653 EXPECT_NE(0, d.bytes_received());
3654 EXPECT_EQ(test_server_.host_port_pair().host(),
3655 r.GetSocketAddress().host());
3656 EXPECT_EQ(test_server_.host_port_pair().port(),
3657 r.GetSocketAddress().port());
3661 TEST_F(URLRequestTestHTTP, GetZippedTest) {
3662 ASSERT_TRUE(test_server_.Start());
3664 // Parameter that specifies the Content-Length field in the response:
3665 // C - Compressed length.
3666 // U - Uncompressed length.
3667 // L - Large length (larger than both C & U).
3668 // M - Medium length (between C & U).
3669 // S - Small length (smaller than both C & U).
3670 const char test_parameters[] = "CULMS";
3671 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3672 // C & U should be OK.
3673 // L & M are larger than the data sent, and show an error.
3674 // S has too little data, but we seem to accept it.
3675 const bool test_expect_success[num_tests] =
3676 { true, true, false, false, true };
3678 for (int i = 0; i < num_tests ; i++) {
3679 TestDelegate d;
3681 std::string test_file =
3682 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3683 test_parameters[i]);
3685 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3686 TestURLRequestContext context(true);
3687 context.set_network_delegate(&network_delegate);
3688 context.Init();
3690 URLRequest r(
3691 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, &context);
3692 r.Start();
3693 EXPECT_TRUE(r.is_pending());
3695 base::RunLoop().Run();
3697 EXPECT_EQ(1, d.response_started_count());
3698 EXPECT_FALSE(d.received_data_before_response());
3699 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3700 << " status = " << r.status().status()
3701 << " error = " << r.status().error();
3702 if (test_expect_success[i]) {
3703 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3704 << " Parameter = \"" << test_file << "\"";
3705 } else {
3706 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3707 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
3708 << " Parameter = \"" << test_file << "\"";
3714 TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
3715 ASSERT_TRUE(test_server_.Start());
3717 SpawnedTestServer https_test_server(
3718 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
3719 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3720 ASSERT_TRUE(https_test_server.Start());
3722 // An https server is sent a request with an https referer,
3723 // and responds with a redirect to an http url. The http
3724 // server should not be sent the referer.
3725 GURL http_destination = test_server_.GetURL(std::string());
3726 TestDelegate d;
3727 URLRequest req(
3728 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3729 DEFAULT_PRIORITY,
3731 &default_context_);
3732 req.SetReferrer("https://www.referrer.com/");
3733 req.Start();
3734 base::RunLoop().Run();
3736 EXPECT_EQ(1, d.response_started_count());
3737 EXPECT_EQ(1, d.received_redirect_count());
3738 EXPECT_EQ(http_destination, req.url());
3739 EXPECT_EQ(std::string(), req.referrer());
3742 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3743 ASSERT_TRUE(test_server_.Start());
3745 GURL destination_url = test_server_.GetURL(std::string());
3746 GURL original_url =
3747 test_server_.GetURL("server-redirect?" + destination_url.spec());
3748 TestDelegate d;
3749 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3750 req.Start();
3751 base::RunLoop().Run();
3753 EXPECT_EQ(1, d.response_started_count());
3754 EXPECT_EQ(1, d.received_redirect_count());
3755 EXPECT_EQ(destination_url, req.url());
3756 EXPECT_EQ(original_url, req.original_url());
3757 ASSERT_EQ(2U, req.url_chain().size());
3758 EXPECT_EQ(original_url, req.url_chain()[0]);
3759 EXPECT_EQ(destination_url, req.url_chain()[1]);
3761 LoadTimingInfo load_timing_info_before_redirect;
3762 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3763 &load_timing_info_before_redirect));
3764 TestLoadTimingNotReused(load_timing_info_before_redirect,
3765 CONNECT_TIMING_HAS_DNS_TIMES);
3767 LoadTimingInfo load_timing_info;
3768 req.GetLoadTimingInfo(&load_timing_info);
3769 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3771 // Check that a new socket was used on redirect, since the server does not
3772 // supposed keep-alive sockets, and that the times before the redirect are
3773 // before the ones recorded for the second request.
3774 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3775 load_timing_info.socket_log_id);
3776 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3777 load_timing_info.connect_timing.connect_start);
3780 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3781 ASSERT_TRUE(test_server_.Start());
3783 GURL destination_url = test_server_.GetURL(std::string());
3784 GURL middle_redirect_url =
3785 test_server_.GetURL("server-redirect?" + destination_url.spec());
3786 GURL original_url = test_server_.GetURL(
3787 "server-redirect?" + middle_redirect_url.spec());
3788 TestDelegate d;
3789 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3790 req.Start();
3791 base::RunLoop().Run();
3793 EXPECT_EQ(1, d.response_started_count());
3794 EXPECT_EQ(2, d.received_redirect_count());
3795 EXPECT_EQ(destination_url, req.url());
3796 EXPECT_EQ(original_url, req.original_url());
3797 ASSERT_EQ(3U, req.url_chain().size());
3798 EXPECT_EQ(original_url, req.url_chain()[0]);
3799 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3800 EXPECT_EQ(destination_url, req.url_chain()[2]);
3803 // First and second pieces of information logged by delegates to URLRequests.
3804 const char kFirstDelegateInfo[] = "Wonderful delegate";
3805 const char kSecondDelegateInfo[] = "Exciting delegate";
3807 // Logs delegate information to a URLRequest. The first string is logged
3808 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3809 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3810 // another asynchronous call is used to clear the delegate information
3811 // before calling a callback. The object then deletes itself.
3812 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3813 public:
3814 typedef base::Callback<void()> Callback;
3816 // Each time delegate information is added to the URLRequest, the resulting
3817 // load state is checked. The expected load state after each request is
3818 // passed in as an argument.
3819 static void Run(URLRequest* url_request,
3820 LoadState expected_first_load_state,
3821 LoadState expected_second_load_state,
3822 LoadState expected_third_load_state,
3823 const Callback& callback) {
3824 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3825 url_request,
3826 expected_first_load_state,
3827 expected_second_load_state,
3828 expected_third_load_state,
3829 callback);
3830 logger->Start();
3833 // Checks that the log entries, starting with log_position, contain the
3834 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3835 // recorded. Returns the index of entry after the expected number of
3836 // events this logged, or entries.size() if there aren't enough entries.
3837 static size_t CheckDelegateInfo(
3838 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3839 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3840 if (log_position + 3 >= entries.size()) {
3841 ADD_FAILURE() << "Not enough log entries";
3842 return entries.size();
3844 std::string delegate_info;
3845 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3846 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3847 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3848 &delegate_info));
3849 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3851 ++log_position;
3852 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3853 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3855 ++log_position;
3856 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3857 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3858 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3859 &delegate_info));
3860 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3862 ++log_position;
3863 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3864 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3866 return log_position + 1;
3869 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3870 // Returns the position of the end message.
3871 static size_t ExpectBeforeNetworkEvents(
3872 const CapturingNetLog::CapturedEntryList& entries,
3873 size_t log_position) {
3874 log_position =
3875 ExpectLogContainsSomewhereAfter(entries,
3876 log_position,
3877 NetLog::TYPE_URL_REQUEST_DELEGATE,
3878 NetLog::PHASE_BEGIN);
3879 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3880 entries[log_position + 1].type);
3881 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3882 return log_position + 1;
3885 private:
3886 friend class base::RefCounted<AsyncDelegateLogger>;
3888 AsyncDelegateLogger(URLRequest* url_request,
3889 LoadState expected_first_load_state,
3890 LoadState expected_second_load_state,
3891 LoadState expected_third_load_state,
3892 const Callback& callback)
3893 : url_request_(url_request),
3894 expected_first_load_state_(expected_first_load_state),
3895 expected_second_load_state_(expected_second_load_state),
3896 expected_third_load_state_(expected_third_load_state),
3897 callback_(callback) {
3900 ~AsyncDelegateLogger() {}
3902 void Start() {
3903 url_request_->LogBlockedBy(kFirstDelegateInfo);
3904 LoadStateWithParam load_state = url_request_->GetLoadState();
3905 EXPECT_EQ(expected_first_load_state_, load_state.state);
3906 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3907 base::MessageLoop::current()->PostTask(
3908 FROM_HERE,
3909 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3912 void LogSecondDelegate() {
3913 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
3914 LoadStateWithParam load_state = url_request_->GetLoadState();
3915 EXPECT_EQ(expected_second_load_state_, load_state.state);
3916 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3917 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3918 } else {
3919 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3921 base::MessageLoop::current()->PostTask(
3922 FROM_HERE,
3923 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3926 void LogComplete() {
3927 url_request_->LogUnblocked();
3928 LoadStateWithParam load_state = url_request_->GetLoadState();
3929 EXPECT_EQ(expected_third_load_state_, load_state.state);
3930 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3931 EXPECT_EQ(base::string16(), load_state.param);
3932 callback_.Run();
3935 URLRequest* url_request_;
3936 const int expected_first_load_state_;
3937 const int expected_second_load_state_;
3938 const int expected_third_load_state_;
3939 const Callback callback_;
3941 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3944 // NetworkDelegate that logs delegate information before a request is started,
3945 // before headers are sent, when headers are read, and when auth information
3946 // is requested. Uses AsyncDelegateLogger.
3947 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3948 public:
3949 AsyncLoggingNetworkDelegate() {}
3950 virtual ~AsyncLoggingNetworkDelegate() {}
3952 // NetworkDelegate implementation.
3953 virtual int OnBeforeURLRequest(URLRequest* request,
3954 const CompletionCallback& callback,
3955 GURL* new_url) OVERRIDE {
3956 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3957 return RunCallbackAsynchronously(request, callback);
3960 virtual int OnBeforeSendHeaders(URLRequest* request,
3961 const CompletionCallback& callback,
3962 HttpRequestHeaders* headers) OVERRIDE {
3963 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3964 return RunCallbackAsynchronously(request, callback);
3967 virtual int OnHeadersReceived(
3968 URLRequest* request,
3969 const CompletionCallback& callback,
3970 const HttpResponseHeaders* original_response_headers,
3971 scoped_refptr<HttpResponseHeaders>* override_response_headers,
3972 GURL* allowed_unsafe_redirect_url) OVERRIDE {
3973 TestNetworkDelegate::OnHeadersReceived(request,
3974 callback,
3975 original_response_headers,
3976 override_response_headers,
3977 allowed_unsafe_redirect_url);
3978 return RunCallbackAsynchronously(request, callback);
3981 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
3982 URLRequest* request,
3983 const AuthChallengeInfo& auth_info,
3984 const AuthCallback& callback,
3985 AuthCredentials* credentials) OVERRIDE {
3986 AsyncDelegateLogger::Run(
3987 request,
3988 LOAD_STATE_WAITING_FOR_DELEGATE,
3989 LOAD_STATE_WAITING_FOR_DELEGATE,
3990 LOAD_STATE_WAITING_FOR_DELEGATE,
3991 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
3992 callback, credentials));
3993 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
3996 private:
3997 static int RunCallbackAsynchronously(
3998 URLRequest* request,
3999 const CompletionCallback& callback) {
4000 AsyncDelegateLogger::Run(
4001 request,
4002 LOAD_STATE_WAITING_FOR_DELEGATE,
4003 LOAD_STATE_WAITING_FOR_DELEGATE,
4004 LOAD_STATE_WAITING_FOR_DELEGATE,
4005 base::Bind(callback, OK));
4006 return ERR_IO_PENDING;
4009 static void SetAuthAndResume(const AuthCallback& callback,
4010 AuthCredentials* credentials) {
4011 *credentials = AuthCredentials(kUser, kSecret);
4012 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4015 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4018 // URLRequest::Delegate that logs delegate information when the headers
4019 // are received, when each read completes, and during redirects. Uses
4020 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4022 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4023 // advancing to the next step in most cases, as well as cancellation.
4024 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4025 public:
4026 enum CancelStage {
4027 NO_CANCEL = 0,
4028 CANCEL_ON_RECEIVED_REDIRECT,
4029 CANCEL_ON_RESPONSE_STARTED,
4030 CANCEL_ON_READ_COMPLETED
4033 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4034 : cancel_stage_(cancel_stage) {
4035 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4036 set_cancel_in_received_redirect(true);
4037 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4038 set_cancel_in_response_started(true);
4039 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4040 set_cancel_in_received_data(true);
4042 virtual ~AsyncLoggingUrlRequestDelegate() {}
4044 // URLRequest::Delegate implementation:
4045 void virtual OnReceivedRedirect(URLRequest* request,
4046 const GURL& new_url,
4047 bool* defer_redirect) OVERRIDE {
4048 *defer_redirect = true;
4049 AsyncDelegateLogger::Run(
4050 request,
4051 LOAD_STATE_WAITING_FOR_DELEGATE,
4052 LOAD_STATE_WAITING_FOR_DELEGATE,
4053 LOAD_STATE_WAITING_FOR_DELEGATE,
4054 base::Bind(
4055 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4056 base::Unretained(this), request, new_url));
4059 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4060 AsyncDelegateLogger::Run(
4061 request,
4062 LOAD_STATE_WAITING_FOR_DELEGATE,
4063 LOAD_STATE_WAITING_FOR_DELEGATE,
4064 LOAD_STATE_WAITING_FOR_DELEGATE,
4065 base::Bind(
4066 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4067 base::Unretained(this), request));
4070 virtual void OnReadCompleted(URLRequest* request,
4071 int bytes_read) OVERRIDE {
4072 AsyncDelegateLogger::Run(
4073 request,
4074 LOAD_STATE_IDLE,
4075 LOAD_STATE_IDLE,
4076 LOAD_STATE_IDLE,
4077 base::Bind(
4078 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4079 base::Unretained(this), request, bytes_read));
4082 private:
4083 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4084 const GURL& new_url) {
4085 bool defer_redirect = false;
4086 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
4087 // FollowDeferredRedirect should not be called after cancellation.
4088 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4089 return;
4090 if (!defer_redirect)
4091 request->FollowDeferredRedirect();
4094 void OnResponseStartedLoggingComplete(URLRequest* request) {
4095 // The parent class continues the request.
4096 TestDelegate::OnResponseStarted(request);
4099 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4100 // The parent class continues the request.
4101 TestDelegate::OnReadCompleted(request, bytes_read);
4104 const CancelStage cancel_stage_;
4106 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4109 // Tests handling of delegate info before a request starts.
4110 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4111 ASSERT_TRUE(test_server_.Start());
4113 TestDelegate request_delegate;
4114 TestURLRequestContext context(true);
4115 context.set_network_delegate(NULL);
4116 context.set_net_log(&net_log_);
4117 context.Init();
4120 URLRequest r(test_server_.GetURL("empty.html"),
4121 DEFAULT_PRIORITY,
4122 &request_delegate,
4123 &context);
4124 LoadStateWithParam load_state = r.GetLoadState();
4125 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4126 EXPECT_EQ(base::string16(), load_state.param);
4128 AsyncDelegateLogger::Run(
4130 LOAD_STATE_WAITING_FOR_DELEGATE,
4131 LOAD_STATE_WAITING_FOR_DELEGATE,
4132 LOAD_STATE_IDLE,
4133 base::Bind(&URLRequest::Start, base::Unretained(&r)));
4135 base::RunLoop().Run();
4137 EXPECT_EQ(200, r.GetResponseCode());
4138 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4141 CapturingNetLog::CapturedEntryList entries;
4142 net_log_.GetEntries(&entries);
4143 size_t log_position = ExpectLogContainsSomewhereAfter(
4144 entries,
4146 NetLog::TYPE_DELEGATE_INFO,
4147 NetLog::PHASE_BEGIN);
4149 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4151 // Nothing else should add any delegate info to the request.
4152 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4153 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4156 // Tests handling of delegate info from a network delegate.
4157 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4158 ASSERT_TRUE(test_server_.Start());
4160 TestDelegate request_delegate;
4161 AsyncLoggingNetworkDelegate network_delegate;
4162 TestURLRequestContext context(true);
4163 context.set_network_delegate(&network_delegate);
4164 context.set_net_log(&net_log_);
4165 context.Init();
4168 URLRequest r(test_server_.GetURL("simple.html"),
4169 DEFAULT_PRIORITY,
4170 &request_delegate,
4171 &context);
4172 LoadStateWithParam load_state = r.GetLoadState();
4173 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4174 EXPECT_EQ(base::string16(), load_state.param);
4176 r.Start();
4177 base::RunLoop().Run();
4179 EXPECT_EQ(200, r.GetResponseCode());
4180 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4181 EXPECT_EQ(1, network_delegate.created_requests());
4182 EXPECT_EQ(0, network_delegate.destroyed_requests());
4184 EXPECT_EQ(1, network_delegate.destroyed_requests());
4186 size_t log_position = 0;
4187 CapturingNetLog::CapturedEntryList entries;
4188 net_log_.GetEntries(&entries);
4189 for (size_t i = 0; i < 3; ++i) {
4190 log_position = ExpectLogContainsSomewhereAfter(
4191 entries,
4192 log_position + 1,
4193 NetLog::TYPE_URL_REQUEST_DELEGATE,
4194 NetLog::PHASE_BEGIN);
4196 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4197 log_position + 1);
4199 ASSERT_LT(log_position, entries.size());
4200 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4201 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4203 if (i == 1) {
4204 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4205 entries, log_position + 1);
4209 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4210 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4213 // Tests handling of delegate info from a network delegate in the case of an
4214 // HTTP redirect.
4215 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4216 ASSERT_TRUE(test_server_.Start());
4218 TestDelegate request_delegate;
4219 AsyncLoggingNetworkDelegate network_delegate;
4220 TestURLRequestContext context(true);
4221 context.set_network_delegate(&network_delegate);
4222 context.set_net_log(&net_log_);
4223 context.Init();
4226 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4227 DEFAULT_PRIORITY,
4228 &request_delegate,
4229 &context);
4230 LoadStateWithParam load_state = r.GetLoadState();
4231 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4232 EXPECT_EQ(base::string16(), load_state.param);
4234 r.Start();
4235 base::RunLoop().Run();
4237 EXPECT_EQ(200, r.GetResponseCode());
4238 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4239 EXPECT_EQ(2, network_delegate.created_requests());
4240 EXPECT_EQ(0, network_delegate.destroyed_requests());
4242 EXPECT_EQ(1, network_delegate.destroyed_requests());
4244 size_t log_position = 0;
4245 CapturingNetLog::CapturedEntryList entries;
4246 net_log_.GetEntries(&entries);
4247 // The NetworkDelegate logged information in OnBeforeURLRequest,
4248 // OnBeforeSendHeaders, and OnHeadersReceived.
4249 for (size_t i = 0; i < 3; ++i) {
4250 log_position = ExpectLogContainsSomewhereAfter(
4251 entries,
4252 log_position + 1,
4253 NetLog::TYPE_URL_REQUEST_DELEGATE,
4254 NetLog::PHASE_BEGIN);
4256 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4257 log_position + 1);
4259 ASSERT_LT(log_position, entries.size());
4260 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4261 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4263 if (i == 1) {
4264 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4265 entries, log_position + 1);
4269 // The URLRequest::Delegate then gets informed about the redirect.
4270 log_position = ExpectLogContainsSomewhereAfter(
4271 entries,
4272 log_position + 1,
4273 NetLog::TYPE_URL_REQUEST_DELEGATE,
4274 NetLog::PHASE_BEGIN);
4276 // The NetworkDelegate logged information in the same three events as before.
4277 for (size_t i = 0; i < 3; ++i) {
4278 log_position = ExpectLogContainsSomewhereAfter(
4279 entries,
4280 log_position + 1,
4281 NetLog::TYPE_URL_REQUEST_DELEGATE,
4282 NetLog::PHASE_BEGIN);
4284 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4285 log_position + 1);
4287 ASSERT_LT(log_position, entries.size());
4288 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4289 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4292 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4293 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4296 // Tests handling of delegate info from a network delegate in the case of HTTP
4297 // AUTH.
4298 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4299 ASSERT_TRUE(test_server_.Start());
4301 TestDelegate request_delegate;
4302 AsyncLoggingNetworkDelegate network_delegate;
4303 TestURLRequestContext context(true);
4304 context.set_network_delegate(&network_delegate);
4305 context.set_net_log(&net_log_);
4306 context.Init();
4309 URLRequest r(test_server_.GetURL("auth-basic"),
4310 DEFAULT_PRIORITY,
4311 &request_delegate,
4312 &context);
4313 LoadStateWithParam load_state = r.GetLoadState();
4314 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4315 EXPECT_EQ(base::string16(), load_state.param);
4317 r.Start();
4318 base::RunLoop().Run();
4320 EXPECT_EQ(200, r.GetResponseCode());
4321 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4322 EXPECT_EQ(1, network_delegate.created_requests());
4323 EXPECT_EQ(0, network_delegate.destroyed_requests());
4325 EXPECT_EQ(1, network_delegate.destroyed_requests());
4327 size_t log_position = 0;
4328 CapturingNetLog::CapturedEntryList entries;
4329 net_log_.GetEntries(&entries);
4330 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4331 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4332 // OnBeforeURLRequest and OnBeforeSendHeaders.
4333 for (size_t i = 0; i < 6; ++i) {
4334 log_position = ExpectLogContainsSomewhereAfter(
4335 entries,
4336 log_position + 1,
4337 NetLog::TYPE_URL_REQUEST_DELEGATE,
4338 NetLog::PHASE_BEGIN);
4340 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4341 log_position + 1);
4343 ASSERT_LT(log_position, entries.size());
4344 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4345 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4347 if (i == 1) {
4348 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4349 entries, log_position + 1);
4353 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4354 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4357 // Tests handling of delegate info from a URLRequest::Delegate.
4358 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4359 ASSERT_TRUE(test_server_.Start());
4361 AsyncLoggingUrlRequestDelegate request_delegate(
4362 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4363 TestURLRequestContext context(true);
4364 context.set_network_delegate(NULL);
4365 context.set_net_log(&net_log_);
4366 context.Init();
4369 // A chunked response with delays between chunks is used to make sure that
4370 // attempts by the URLRequest delegate to log information while reading the
4371 // body are ignored. Since they are ignored, this test is robust against
4372 // the possibility of multiple reads being combined in the unlikely event
4373 // that it occurs.
4374 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
4375 DEFAULT_PRIORITY,
4376 &request_delegate,
4377 &context);
4378 LoadStateWithParam load_state = r.GetLoadState();
4379 r.Start();
4380 base::RunLoop().Run();
4382 EXPECT_EQ(200, r.GetResponseCode());
4383 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4386 CapturingNetLog::CapturedEntryList entries;
4387 net_log_.GetEntries(&entries);
4389 size_t log_position = 0;
4391 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4392 entries, log_position);
4394 // The delegate info should only have been logged on header complete. Other
4395 // times it should silently be ignored.
4396 log_position =
4397 ExpectLogContainsSomewhereAfter(entries,
4398 log_position + 1,
4399 NetLog::TYPE_URL_REQUEST_DELEGATE,
4400 NetLog::PHASE_BEGIN);
4402 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4403 log_position + 1);
4405 ASSERT_LT(log_position, entries.size());
4406 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4407 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4409 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4410 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4411 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4412 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4415 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4416 // an HTTP redirect.
4417 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4418 ASSERT_TRUE(test_server_.Start());
4420 AsyncLoggingUrlRequestDelegate request_delegate(
4421 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4422 TestURLRequestContext context(true);
4423 context.set_network_delegate(NULL);
4424 context.set_net_log(&net_log_);
4425 context.Init();
4428 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4429 DEFAULT_PRIORITY,
4430 &request_delegate,
4431 &context);
4432 LoadStateWithParam load_state = r.GetLoadState();
4433 r.Start();
4434 base::RunLoop().Run();
4436 EXPECT_EQ(200, r.GetResponseCode());
4437 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4440 CapturingNetLog::CapturedEntryList entries;
4441 net_log_.GetEntries(&entries);
4443 // Delegate info should only have been logged in OnReceivedRedirect and
4444 // OnResponseStarted.
4445 size_t log_position = 0;
4446 for (int i = 0; i < 2; ++i) {
4447 if (i == 0) {
4448 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4449 entries, log_position) + 1;
4452 log_position = ExpectLogContainsSomewhereAfter(
4453 entries,
4454 log_position,
4455 NetLog::TYPE_URL_REQUEST_DELEGATE,
4456 NetLog::PHASE_BEGIN);
4458 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4459 log_position + 1);
4461 ASSERT_LT(log_position, entries.size());
4462 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4463 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4466 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4467 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4468 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4469 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4472 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4473 // an HTTP redirect, with cancellation at various points.
4474 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4475 ASSERT_TRUE(test_server_.Start());
4477 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4478 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4479 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4480 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4483 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4484 ++test_case) {
4485 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4486 TestURLRequestContext context(true);
4487 CapturingNetLog net_log;
4488 context.set_network_delegate(NULL);
4489 context.set_net_log(&net_log);
4490 context.Init();
4493 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4494 DEFAULT_PRIORITY,
4495 &request_delegate,
4496 &context);
4497 LoadStateWithParam load_state = r.GetLoadState();
4498 r.Start();
4499 base::RunLoop().Run();
4500 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4503 CapturingNetLog::CapturedEntryList entries;
4504 net_log.GetEntries(&entries);
4506 // Delegate info is always logged in both OnReceivedRedirect and
4507 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4508 // OnResponseStarted delegate call is after cancellation, but logging is
4509 // still currently supported in that call.
4510 size_t log_position = 0;
4511 for (int i = 0; i < 2; ++i) {
4512 if (i == 0) {
4513 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4514 entries, log_position) + 1;
4517 log_position = ExpectLogContainsSomewhereAfter(
4518 entries,
4519 log_position,
4520 NetLog::TYPE_URL_REQUEST_DELEGATE,
4521 NetLog::PHASE_BEGIN);
4523 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4524 log_position + 1);
4526 ASSERT_LT(log_position, entries.size());
4527 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4528 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4531 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4532 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4533 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4534 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4538 namespace {
4540 const char kExtraHeader[] = "Allow-Snafu";
4541 const char kExtraValue[] = "fubar";
4543 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
4544 virtual void OnReceivedRedirect(net::URLRequest* request,
4545 const GURL& new_url,
4546 bool* defer_redirect) OVERRIDE {
4547 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4548 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4552 } // namespace
4554 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4555 ASSERT_TRUE(test_server_.Start());
4557 GURL destination_url = test_server_.GetURL(
4558 "echoheader?" + std::string(kExtraHeader));
4559 GURL original_url = test_server_.GetURL(
4560 "server-redirect?" + destination_url.spec());
4561 RedirectWithAdditionalHeadersDelegate d;
4562 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4563 req.Start();
4564 base::RunLoop().Run();
4566 std::string value;
4567 const HttpRequestHeaders& headers = req.extra_request_headers();
4568 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4569 EXPECT_EQ(kExtraValue, value);
4570 EXPECT_FALSE(req.is_pending());
4571 EXPECT_FALSE(req.is_redirecting());
4572 EXPECT_EQ(kExtraValue, d.data_received());
4575 namespace {
4577 const char kExtraHeaderToRemove[] = "To-Be-Removed";
4579 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
4580 virtual void OnReceivedRedirect(net::URLRequest* request,
4581 const GURL& new_url,
4582 bool* defer_redirect) OVERRIDE {
4583 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4584 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4588 } // namespace
4590 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4591 ASSERT_TRUE(test_server_.Start());
4593 GURL destination_url = test_server_.GetURL(
4594 "echoheader?" + std::string(kExtraHeaderToRemove));
4595 GURL original_url = test_server_.GetURL(
4596 "server-redirect?" + destination_url.spec());
4597 RedirectWithHeaderRemovalDelegate d;
4598 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4599 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4600 req.Start();
4601 base::RunLoop().Run();
4603 std::string value;
4604 const HttpRequestHeaders& headers = req.extra_request_headers();
4605 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4606 EXPECT_FALSE(req.is_pending());
4607 EXPECT_FALSE(req.is_redirecting());
4608 EXPECT_EQ("None", d.data_received());
4611 TEST_F(URLRequestTestHTTP, CancelTest) {
4612 TestDelegate d;
4614 URLRequest r(GURL("http://www.google.com/"),
4615 DEFAULT_PRIORITY,
4617 &default_context_);
4619 r.Start();
4620 EXPECT_TRUE(r.is_pending());
4622 r.Cancel();
4624 base::RunLoop().Run();
4626 // We expect to receive OnResponseStarted even though the request has been
4627 // cancelled.
4628 EXPECT_EQ(1, d.response_started_count());
4629 EXPECT_EQ(0, d.bytes_received());
4630 EXPECT_FALSE(d.received_data_before_response());
4634 TEST_F(URLRequestTestHTTP, CancelTest2) {
4635 ASSERT_TRUE(test_server_.Start());
4637 TestDelegate d;
4639 URLRequest r(test_server_.GetURL(std::string()),
4640 DEFAULT_PRIORITY,
4642 &default_context_);
4644 d.set_cancel_in_response_started(true);
4646 r.Start();
4647 EXPECT_TRUE(r.is_pending());
4649 base::RunLoop().Run();
4651 EXPECT_EQ(1, d.response_started_count());
4652 EXPECT_EQ(0, d.bytes_received());
4653 EXPECT_FALSE(d.received_data_before_response());
4654 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4658 TEST_F(URLRequestTestHTTP, CancelTest3) {
4659 ASSERT_TRUE(test_server_.Start());
4661 TestDelegate d;
4663 URLRequest r(test_server_.GetURL(std::string()),
4664 DEFAULT_PRIORITY,
4666 &default_context_);
4668 d.set_cancel_in_received_data(true);
4670 r.Start();
4671 EXPECT_TRUE(r.is_pending());
4673 base::RunLoop().Run();
4675 EXPECT_EQ(1, d.response_started_count());
4676 // There is no guarantee about how much data was received
4677 // before the cancel was issued. It could have been 0 bytes,
4678 // or it could have been all the bytes.
4679 // EXPECT_EQ(0, d.bytes_received());
4680 EXPECT_FALSE(d.received_data_before_response());
4681 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4685 TEST_F(URLRequestTestHTTP, CancelTest4) {
4686 ASSERT_TRUE(test_server_.Start());
4688 TestDelegate d;
4690 URLRequest r(test_server_.GetURL(std::string()),
4691 DEFAULT_PRIORITY,
4693 &default_context_);
4695 r.Start();
4696 EXPECT_TRUE(r.is_pending());
4698 // The request will be implicitly canceled when it is destroyed. The
4699 // test delegate must not post a quit message when this happens because
4700 // this test doesn't actually have a message loop. The quit message would
4701 // get put on this thread's message queue and the next test would exit
4702 // early, causing problems.
4703 d.set_quit_on_complete(false);
4705 // expect things to just cleanup properly.
4707 // we won't actually get a received reponse here because we've never run the
4708 // message loop
4709 EXPECT_FALSE(d.received_data_before_response());
4710 EXPECT_EQ(0, d.bytes_received());
4713 TEST_F(URLRequestTestHTTP, CancelTest5) {
4714 ASSERT_TRUE(test_server_.Start());
4716 // populate cache
4718 TestDelegate d;
4719 URLRequest r(test_server_.GetURL("cachetime"),
4720 DEFAULT_PRIORITY,
4722 &default_context_);
4723 r.Start();
4724 base::RunLoop().Run();
4725 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4728 // cancel read from cache (see bug 990242)
4730 TestDelegate d;
4731 URLRequest r(test_server_.GetURL("cachetime"),
4732 DEFAULT_PRIORITY,
4734 &default_context_);
4735 r.Start();
4736 r.Cancel();
4737 base::RunLoop().Run();
4739 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4740 EXPECT_EQ(1, d.response_started_count());
4741 EXPECT_EQ(0, d.bytes_received());
4742 EXPECT_FALSE(d.received_data_before_response());
4746 TEST_F(URLRequestTestHTTP, PostTest) {
4747 ASSERT_TRUE(test_server_.Start());
4748 HTTPUploadDataOperationTest("POST");
4751 TEST_F(URLRequestTestHTTP, PutTest) {
4752 ASSERT_TRUE(test_server_.Start());
4753 HTTPUploadDataOperationTest("PUT");
4756 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4757 ASSERT_TRUE(test_server_.Start());
4759 TestDelegate d;
4761 URLRequest r(
4762 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4763 r.set_method("POST");
4765 r.Start();
4766 EXPECT_TRUE(r.is_pending());
4768 base::RunLoop().Run();
4770 ASSERT_EQ(1, d.response_started_count())
4771 << "request failed: " << r.status().status()
4772 << ", error: " << r.status().error();
4774 EXPECT_FALSE(d.received_data_before_response());
4775 EXPECT_TRUE(d.data_received().empty());
4779 TEST_F(URLRequestTestHTTP, PostFileTest) {
4780 ASSERT_TRUE(test_server_.Start());
4782 TestDelegate d;
4784 URLRequest r(
4785 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4786 r.set_method("POST");
4788 base::FilePath dir;
4789 PathService::Get(base::DIR_EXE, &dir);
4790 base::SetCurrentDirectory(dir);
4792 ScopedVector<UploadElementReader> element_readers;
4794 base::FilePath path;
4795 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4796 path = path.Append(FILE_PATH_LITERAL("net"));
4797 path = path.Append(FILE_PATH_LITERAL("data"));
4798 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4799 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4800 element_readers.push_back(
4801 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4802 path,
4804 kuint64max,
4805 base::Time()));
4806 r.set_upload(make_scoped_ptr(
4807 new UploadDataStream(element_readers.Pass(), 0)));
4809 r.Start();
4810 EXPECT_TRUE(r.is_pending());
4812 base::RunLoop().Run();
4814 int64 size = 0;
4815 ASSERT_EQ(true, base::GetFileSize(path, &size));
4816 scoped_ptr<char[]> buf(new char[size]);
4818 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
4820 ASSERT_EQ(1, d.response_started_count())
4821 << "request failed: " << r.status().status()
4822 << ", error: " << r.status().error();
4824 EXPECT_FALSE(d.received_data_before_response());
4826 EXPECT_EQ(size, d.bytes_received());
4827 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
4831 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4832 ASSERT_TRUE(test_server_.Start());
4834 TestDelegate d;
4836 URLRequest r(test_server_.GetURL("echo"), DEFAULT_PRIORITY,
4837 &d, &default_context_);
4838 r.set_method("POST");
4840 ScopedVector<UploadElementReader> element_readers;
4842 element_readers.push_back(new UploadFileElementReader(
4843 base::MessageLoopProxy::current().get(),
4844 base::FilePath(FILE_PATH_LITERAL(
4845 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4847 kuint64max,
4848 base::Time()));
4849 r.set_upload(make_scoped_ptr(
4850 new UploadDataStream(element_readers.Pass(), 0)));
4852 r.Start();
4853 EXPECT_TRUE(r.is_pending());
4855 base::RunLoop().Run();
4857 EXPECT_TRUE(d.request_failed());
4858 EXPECT_FALSE(d.received_data_before_response());
4859 EXPECT_EQ(0, d.bytes_received());
4860 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
4861 EXPECT_EQ(ERR_FILE_NOT_FOUND, r.status().error());
4865 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4866 ASSERT_TRUE(test_server_.Start());
4868 TestDelegate d;
4870 URLRequest r(
4871 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4872 r.EnableChunkedUpload();
4873 r.set_method("POST");
4874 AddChunksToUpload(&r);
4875 r.Start();
4876 EXPECT_TRUE(r.is_pending());
4878 base::RunLoop().Run();
4880 VerifyReceivedDataMatchesChunks(&r, &d);
4884 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4885 ASSERT_TRUE(test_server_.Start());
4887 TestDelegate d;
4889 URLRequest r(
4890 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4891 r.EnableChunkedUpload();
4892 r.set_method("POST");
4893 r.Start();
4894 EXPECT_TRUE(r.is_pending());
4895 AddChunksToUpload(&r);
4896 base::RunLoop().Run();
4898 VerifyReceivedDataMatchesChunks(&r, &d);
4902 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4903 ASSERT_TRUE(test_server_.Start());
4905 TestDelegate d;
4907 URLRequest r(
4908 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4909 r.EnableChunkedUpload();
4910 r.set_method("POST");
4911 r.Start();
4912 EXPECT_TRUE(r.is_pending());
4914 base::RunLoop().RunUntilIdle();
4915 AddChunksToUpload(&r);
4916 base::RunLoop().Run();
4918 VerifyReceivedDataMatchesChunks(&r, &d);
4922 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4923 ASSERT_TRUE(test_server_.Start());
4925 TestDelegate d;
4926 URLRequest req(test_server_.GetURL("files/with-headers.html"),
4927 DEFAULT_PRIORITY,
4929 &default_context_);
4930 req.Start();
4931 base::RunLoop().Run();
4933 const HttpResponseHeaders* headers = req.response_headers();
4935 // Simple sanity check that response_info() accesses the same data.
4936 EXPECT_EQ(headers, req.response_info().headers.get());
4938 std::string header;
4939 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4940 EXPECT_EQ("private", header);
4942 header.clear();
4943 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4944 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4946 // The response has two "X-Multiple-Entries" headers.
4947 // This verfies our output has them concatenated together.
4948 header.clear();
4949 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4950 EXPECT_EQ("a, b", header);
4953 TEST_F(URLRequestTestHTTP, ProcessSTS) {
4954 SpawnedTestServer::SSLOptions ssl_options;
4955 SpawnedTestServer https_test_server(
4956 SpawnedTestServer::TYPE_HTTPS,
4957 ssl_options,
4958 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4959 ASSERT_TRUE(https_test_server.Start());
4961 TestDelegate d;
4962 URLRequest request(https_test_server.GetURL("files/hsts-headers.html"),
4963 DEFAULT_PRIORITY,
4965 &default_context_);
4966 request.Start();
4967 base::RunLoop().Run();
4969 TransportSecurityState* security_state =
4970 default_context_.transport_security_state();
4971 TransportSecurityState::DomainState domain_state;
4972 EXPECT_TRUE(security_state->GetDynamicDomainState(
4973 SpawnedTestServer::kLocalhost, &domain_state));
4974 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4975 domain_state.sts.upgrade_mode);
4976 EXPECT_TRUE(domain_state.sts.include_subdomains);
4977 EXPECT_FALSE(domain_state.pkp.include_subdomains);
4978 #if defined(OS_ANDROID)
4979 // Android's CertVerifyProc does not (yet) handle pins.
4980 #else
4981 EXPECT_FALSE(domain_state.HasPublicKeyPins());
4982 #endif
4985 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
4986 // reject HPKP headers, and a test setting only HPKP headers will fail (no
4987 // DomainState present because header rejected).
4988 #if defined(OS_ANDROID)
4989 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
4990 #else
4991 #define MAYBE_ProcessPKP ProcessPKP
4992 #endif
4994 // Tests that enabling HPKP on a domain does not affect the HSTS
4995 // validity/expiration.
4996 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
4997 SpawnedTestServer::SSLOptions ssl_options;
4998 SpawnedTestServer https_test_server(
4999 SpawnedTestServer::TYPE_HTTPS,
5000 ssl_options,
5001 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5002 ASSERT_TRUE(https_test_server.Start());
5004 TestDelegate d;
5005 URLRequest request(https_test_server.GetURL("files/hpkp-headers.html"),
5006 DEFAULT_PRIORITY,
5008 &default_context_);
5009 request.Start();
5010 base::RunLoop().Run();
5012 TransportSecurityState* security_state =
5013 default_context_.transport_security_state();
5014 TransportSecurityState::DomainState domain_state;
5015 EXPECT_TRUE(security_state->GetDynamicDomainState(
5016 SpawnedTestServer::kLocalhost, &domain_state));
5017 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5018 domain_state.sts.upgrade_mode);
5019 EXPECT_FALSE(domain_state.sts.include_subdomains);
5020 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5021 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5022 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5025 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5026 SpawnedTestServer::SSLOptions ssl_options;
5027 SpawnedTestServer https_test_server(
5028 SpawnedTestServer::TYPE_HTTPS,
5029 ssl_options,
5030 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5031 ASSERT_TRUE(https_test_server.Start());
5033 TestDelegate d;
5034 URLRequest request(
5035 https_test_server.GetURL("files/hsts-multiple-headers.html"),
5036 DEFAULT_PRIORITY,
5038 &default_context_);
5039 request.Start();
5040 base::RunLoop().Run();
5042 // We should have set parameters from the first header, not the second.
5043 TransportSecurityState* security_state =
5044 default_context_.transport_security_state();
5045 TransportSecurityState::DomainState domain_state;
5046 EXPECT_TRUE(security_state->GetDynamicDomainState(
5047 SpawnedTestServer::kLocalhost, &domain_state));
5048 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5049 domain_state.sts.upgrade_mode);
5050 EXPECT_FALSE(domain_state.sts.include_subdomains);
5051 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5054 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5055 SpawnedTestServer::SSLOptions ssl_options;
5056 SpawnedTestServer https_test_server(
5057 SpawnedTestServer::TYPE_HTTPS,
5058 ssl_options,
5059 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5060 ASSERT_TRUE(https_test_server.Start());
5062 TestDelegate d;
5063 URLRequest request(
5064 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5065 DEFAULT_PRIORITY,
5067 &default_context_);
5068 request.Start();
5069 base::RunLoop().Run();
5071 // We should have set parameters from the first header, not the second.
5072 TransportSecurityState* security_state =
5073 default_context_.transport_security_state();
5074 TransportSecurityState::DomainState domain_state;
5075 EXPECT_TRUE(security_state->GetDynamicDomainState(
5076 SpawnedTestServer::kLocalhost, &domain_state));
5077 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5078 domain_state.sts.upgrade_mode);
5079 #if defined(OS_ANDROID)
5080 // Android's CertVerifyProc does not (yet) handle pins.
5081 #else
5082 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5083 #endif
5084 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5086 // Even though there is an HSTS header asserting includeSubdomains, it is
5087 // the *second* such header, and we MUST process only the first.
5088 EXPECT_FALSE(domain_state.sts.include_subdomains);
5089 // includeSubdomains does not occur in the test HPKP header.
5090 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5093 // Tests that when multiple HPKP headers are present, asserting different
5094 // policies, that only the first such policy is processed.
5095 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5096 SpawnedTestServer::SSLOptions ssl_options;
5097 SpawnedTestServer https_test_server(
5098 SpawnedTestServer::TYPE_HTTPS,
5099 ssl_options,
5100 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5101 ASSERT_TRUE(https_test_server.Start());
5103 TestDelegate d;
5104 URLRequest request(
5105 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5106 DEFAULT_PRIORITY,
5108 &default_context_);
5109 request.Start();
5110 base::RunLoop().Run();
5112 TransportSecurityState* security_state =
5113 default_context_.transport_security_state();
5114 TransportSecurityState::DomainState domain_state;
5115 EXPECT_TRUE(security_state->GetDynamicDomainState(
5116 SpawnedTestServer::kLocalhost, &domain_state));
5117 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5118 domain_state.sts.upgrade_mode);
5119 #if defined(OS_ANDROID)
5120 // Android's CertVerifyProc does not (yet) handle pins.
5121 #else
5122 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5123 #endif
5124 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5126 EXPECT_TRUE(domain_state.sts.include_subdomains);
5127 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5130 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5131 ASSERT_TRUE(test_server_.Start());
5133 TestDelegate d;
5134 URLRequest req(test_server_.GetURL("files/content-type-normalization.html"),
5135 DEFAULT_PRIORITY,
5137 &default_context_);
5138 req.Start();
5139 base::RunLoop().Run();
5141 std::string mime_type;
5142 req.GetMimeType(&mime_type);
5143 EXPECT_EQ("text/html", mime_type);
5145 std::string charset;
5146 req.GetCharset(&charset);
5147 EXPECT_EQ("utf-8", charset);
5148 req.Cancel();
5151 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
5152 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5153 GURL data_url("data:,foo");
5154 DataProtocolHandler data_protocol_handler;
5155 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5157 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5158 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
5161 #if !defined(DISABLE_FILE_SUPPORT)
5162 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5163 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5164 GURL file_url("file:///foo.txt");
5165 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5166 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5168 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5169 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
5172 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5173 ASSERT_TRUE(test_server_.Start());
5175 TestDelegate d;
5176 URLRequest req(test_server_.GetURL("files/redirect-to-file.html"),
5177 DEFAULT_PRIORITY,
5179 &default_context_);
5180 req.Start();
5181 base::RunLoop().Run();
5183 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5184 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5186 #endif // !defined(DISABLE_FILE_SUPPORT)
5188 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5189 ASSERT_TRUE(test_server_.Start());
5191 TestDelegate d;
5192 URLRequest req(test_server_.GetURL("files/redirect-to-data.html"),
5193 DEFAULT_PRIORITY,
5195 &default_context_);
5196 req.Start();
5197 base::MessageLoop::current()->Run();
5199 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5200 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5203 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5204 ASSERT_TRUE(test_server_.Start());
5206 TestDelegate d;
5207 URLRequest req(test_server_.GetURL("files/redirect-to-invalid-url.html"),
5208 DEFAULT_PRIORITY,
5210 &default_context_);
5211 req.Start();
5212 base::RunLoop().Run();
5214 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5215 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
5218 // Make sure redirects are cached, despite not reading their bodies.
5219 TEST_F(URLRequestTestHTTP, CacheRedirect) {
5220 ASSERT_TRUE(test_server_.Start());
5221 GURL redirect_url =
5222 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5225 TestDelegate d;
5226 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5227 req.Start();
5228 base::RunLoop().Run();
5229 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5230 EXPECT_EQ(1, d.received_redirect_count());
5231 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5235 TestDelegate d;
5236 d.set_quit_on_redirect(true);
5237 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5238 req.Start();
5239 base::RunLoop().Run();
5241 EXPECT_EQ(1, d.received_redirect_count());
5242 EXPECT_EQ(0, d.response_started_count());
5243 EXPECT_TRUE(req.was_cached());
5245 req.FollowDeferredRedirect();
5246 base::RunLoop().Run();
5247 EXPECT_EQ(1, d.received_redirect_count());
5248 EXPECT_EQ(1, d.response_started_count());
5249 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5250 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5254 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5255 // when the headers are read, since the body won't have been read.
5256 TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5257 ASSERT_TRUE(test_server_.Start());
5258 // URL that is normally cached.
5259 GURL initial_url = test_server_.GetURL("cachetime");
5262 // Set up the TestNetworkDelegate tp force a redirect.
5263 GURL redirect_to_url = test_server_.GetURL("echo");
5264 default_network_delegate_.set_redirect_on_headers_received_url(
5265 redirect_to_url);
5267 TestDelegate d;
5268 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5269 req.Start();
5270 base::RunLoop().Run();
5271 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5272 EXPECT_EQ(1, d.received_redirect_count());
5273 EXPECT_EQ(redirect_to_url, req.url());
5277 TestDelegate d;
5278 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5279 req.Start();
5280 base::RunLoop().Run();
5282 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5283 EXPECT_FALSE(req.was_cached());
5284 EXPECT_EQ(0, d.received_redirect_count());
5285 EXPECT_EQ(initial_url, req.url());
5289 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5290 // safe.
5291 TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5292 ASSERT_TRUE(test_server_.Start());
5294 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5295 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5296 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5298 TestDelegate d;
5300 URLRequest r(test_server_.GetURL("whatever"),
5301 DEFAULT_PRIORITY,
5303 &default_context_);
5305 r.Start();
5306 base::RunLoop().Run();
5308 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5310 EXPECT_EQ(2U, r.url_chain().size());
5311 EXPECT_EQ(net::OK, r.status().error());
5312 EXPECT_EQ(unsafe_url, r.url());
5313 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5317 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5318 // some other URL to the whitelist.
5319 TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5320 ASSERT_TRUE(test_server_.Start());
5322 GURL unsafe_url("data:text/html,something");
5323 GURL different_unsafe_url("data:text/html,something-else");
5324 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5325 default_network_delegate_.set_allowed_unsafe_redirect_url(
5326 different_unsafe_url);
5328 TestDelegate d;
5330 URLRequest r(test_server_.GetURL("whatever"),
5331 DEFAULT_PRIORITY,
5333 &default_context_);
5335 r.Start();
5336 base::RunLoop().Run();
5338 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
5339 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r.status().error());
5343 // Redirects from an URL with fragment to an unsafe URL with fragment should
5344 // be allowed, and the reference fragment of the target URL should be preserved.
5345 TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5346 ASSERT_TRUE(test_server_.Start());
5348 GURL original_url(test_server_.GetURL("original#fragment1"));
5349 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5350 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5352 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5353 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5355 TestDelegate d;
5357 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5359 r.Start();
5360 base::RunLoop().Run();
5362 EXPECT_EQ(2U, r.url_chain().size());
5363 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5364 EXPECT_EQ(net::OK, r.status().error());
5365 EXPECT_EQ(original_url, r.original_url());
5366 EXPECT_EQ(expected_url, r.url());
5370 // When a delegate has specified a safe redirect URL, but it does not match the
5371 // redirect target, then do not prevent the reference fragment from being added.
5372 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
5373 ASSERT_TRUE(test_server_.Start());
5375 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5376 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5377 GURL redirect_url(test_server_.GetURL("target"));
5378 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5380 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5381 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5383 TestDelegate d;
5385 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5387 r.Start();
5388 base::RunLoop().Run();
5390 EXPECT_EQ(2U, r.url_chain().size());
5391 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5392 EXPECT_EQ(net::OK, r.status().error());
5393 EXPECT_EQ(original_url, r.original_url());
5394 EXPECT_EQ(expected_redirect_url, r.url());
5398 // When a delegate has specified a safe redirect URL, assume that the redirect
5399 // URL should not be changed. In particular, the reference fragment should not
5400 // be modified.
5401 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5402 ASSERT_TRUE(test_server_.Start());
5404 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5405 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5407 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5408 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5410 TestDelegate d;
5412 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5414 r.Start();
5415 base::RunLoop().Run();
5417 EXPECT_EQ(2U, r.url_chain().size());
5418 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5419 EXPECT_EQ(net::OK, r.status().error());
5420 EXPECT_EQ(original_url, r.original_url());
5421 EXPECT_EQ(redirect_url, r.url());
5425 // When a URLRequestRedirectJob is created, the redirection must be followed and
5426 // the reference fragment of the target URL must not be modified.
5427 TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5428 ASSERT_TRUE(test_server_.Start());
5430 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5431 GURL redirect_url(test_server_.GetURL("echo"));
5433 TestDelegate d;
5434 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5436 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5437 &r, &default_network_delegate_, redirect_url,
5438 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5439 AddTestInterceptor()->set_main_intercept_job(job);
5441 r.Start();
5442 base::RunLoop().Run();
5444 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5445 EXPECT_EQ(net::OK, r.status().error());
5446 EXPECT_EQ(original_url, r.original_url());
5447 EXPECT_EQ(redirect_url, r.url());
5450 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5451 ASSERT_TRUE(test_server_.Start());
5453 TestDelegate d;
5454 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5455 DEFAULT_PRIORITY,
5457 &default_context_);
5458 req.SetReferrer("http://user:pass@foo.com/");
5459 req.Start();
5460 base::RunLoop().Run();
5462 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5465 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5466 ASSERT_TRUE(test_server_.Start());
5468 TestDelegate d;
5469 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5470 DEFAULT_PRIORITY,
5472 &default_context_);
5473 req.SetReferrer("http://foo.com/test#fragment");
5474 req.Start();
5475 base::RunLoop().Run();
5477 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5480 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5481 ASSERT_TRUE(test_server_.Start());
5483 TestDelegate d;
5484 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5485 DEFAULT_PRIORITY,
5487 &default_context_);
5488 req.SetReferrer("http://foo.com/test#fragment");
5489 req.SetReferrer("");
5490 req.Start();
5491 base::RunLoop().Run();
5493 EXPECT_EQ(std::string("None"), d.data_received());
5496 // Defer network start and then resume, checking that the request was a success
5497 // and bytes were received.
5498 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5499 ASSERT_TRUE(test_server_.Start());
5501 TestDelegate d;
5503 d.set_quit_on_network_start(true);
5504 GURL test_url(test_server_.GetURL("echo"));
5505 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5507 req.Start();
5508 base::RunLoop().Run();
5510 EXPECT_EQ(1, d.received_before_network_start_count());
5511 EXPECT_EQ(0, d.response_started_count());
5513 req.ResumeNetworkStart();
5514 base::RunLoop().Run();
5516 EXPECT_EQ(1, d.response_started_count());
5517 EXPECT_NE(0, d.bytes_received());
5518 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5522 // Check that OnBeforeNetworkStart is only called once even if there is a
5523 // redirect.
5524 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5525 ASSERT_TRUE(test_server_.Start());
5527 TestDelegate d;
5529 d.set_quit_on_redirect(true);
5530 d.set_quit_on_network_start(true);
5531 URLRequest req(test_server_.GetURL("server-redirect?echo"),
5532 DEFAULT_PRIORITY,
5534 &default_context_);
5536 req.Start();
5537 base::RunLoop().Run();
5539 EXPECT_EQ(1, d.received_before_network_start_count());
5540 EXPECT_EQ(0, d.response_started_count());
5541 EXPECT_EQ(0, d.received_redirect_count());
5543 req.ResumeNetworkStart();
5544 base::RunLoop().Run();
5546 EXPECT_EQ(1, d.received_redirect_count());
5547 req.FollowDeferredRedirect();
5548 base::RunLoop().Run();
5550 // Check that the redirect's new network transaction does not get propagated
5551 // to a second OnBeforeNetworkStart() notification.
5552 EXPECT_EQ(1, d.received_before_network_start_count());
5554 EXPECT_EQ(1, d.response_started_count());
5555 EXPECT_NE(0, d.bytes_received());
5556 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5560 // Cancel the request after learning that the request would use the network.
5561 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5562 ASSERT_TRUE(test_server_.Start());
5564 TestDelegate d;
5566 d.set_quit_on_network_start(true);
5567 GURL test_url(test_server_.GetURL("echo"));
5568 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5570 req.Start();
5571 base::RunLoop().Run();
5573 EXPECT_EQ(1, d.received_before_network_start_count());
5574 EXPECT_EQ(0, d.response_started_count());
5576 req.Cancel();
5577 base::RunLoop().Run();
5579 EXPECT_EQ(1, d.response_started_count());
5580 EXPECT_EQ(0, d.bytes_received());
5581 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5585 TEST_F(URLRequestTestHTTP, CancelRedirect) {
5586 ASSERT_TRUE(test_server_.Start());
5588 TestDelegate d;
5590 d.set_cancel_in_received_redirect(true);
5591 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5592 DEFAULT_PRIORITY,
5594 &default_context_);
5595 req.Start();
5596 base::RunLoop().Run();
5598 EXPECT_EQ(1, d.response_started_count());
5599 EXPECT_EQ(0, d.bytes_received());
5600 EXPECT_FALSE(d.received_data_before_response());
5601 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5605 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5606 ASSERT_TRUE(test_server_.Start());
5608 TestDelegate d;
5610 d.set_quit_on_redirect(true);
5611 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5612 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5614 req.Start();
5615 base::RunLoop().Run();
5617 EXPECT_EQ(1, d.received_redirect_count());
5619 req.FollowDeferredRedirect();
5620 base::RunLoop().Run();
5622 EXPECT_EQ(1, d.response_started_count());
5623 EXPECT_FALSE(d.received_data_before_response());
5624 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5626 base::FilePath path;
5627 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5628 path = path.Append(FILE_PATH_LITERAL("net"));
5629 path = path.Append(FILE_PATH_LITERAL("data"));
5630 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5631 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5633 std::string contents;
5634 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5635 EXPECT_EQ(contents, d.data_received());
5639 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5640 ASSERT_TRUE(test_server_.Start());
5642 TestDelegate d;
5644 d.set_quit_on_redirect(true);
5645 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5646 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5648 EXPECT_FALSE(d.have_full_request_headers());
5650 req.Start();
5651 base::RunLoop().Run();
5653 EXPECT_EQ(1, d.received_redirect_count());
5654 EXPECT_TRUE(d.have_full_request_headers());
5655 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5656 d.ClearFullRequestHeaders();
5658 req.FollowDeferredRedirect();
5659 base::RunLoop().Run();
5661 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5662 EXPECT_EQ(1, d.response_started_count());
5663 EXPECT_TRUE(d.have_full_request_headers());
5664 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5665 EXPECT_FALSE(d.received_data_before_response());
5666 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5668 base::FilePath path;
5669 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5670 path = path.Append(FILE_PATH_LITERAL("net"));
5671 path = path.Append(FILE_PATH_LITERAL("data"));
5672 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5673 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5675 std::string contents;
5676 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5677 EXPECT_EQ(contents, d.data_received());
5681 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5682 ASSERT_TRUE(test_server_.Start());
5684 TestDelegate d;
5686 d.set_quit_on_redirect(true);
5687 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5688 DEFAULT_PRIORITY,
5690 &default_context_);
5691 req.Start();
5692 base::RunLoop().Run();
5694 EXPECT_EQ(1, d.received_redirect_count());
5696 req.Cancel();
5697 base::RunLoop().Run();
5699 EXPECT_EQ(1, d.response_started_count());
5700 EXPECT_EQ(0, d.bytes_received());
5701 EXPECT_FALSE(d.received_data_before_response());
5702 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5706 TEST_F(URLRequestTestHTTP, VaryHeader) {
5707 ASSERT_TRUE(test_server_.Start());
5709 // Populate the cache.
5711 TestDelegate d;
5712 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5713 DEFAULT_PRIORITY,
5715 &default_context_);
5716 HttpRequestHeaders headers;
5717 headers.SetHeader("foo", "1");
5718 req.SetExtraRequestHeaders(headers);
5719 req.Start();
5720 base::RunLoop().Run();
5722 LoadTimingInfo load_timing_info;
5723 req.GetLoadTimingInfo(&load_timing_info);
5724 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5727 // Expect a cache hit.
5729 TestDelegate d;
5730 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5731 DEFAULT_PRIORITY,
5733 &default_context_);
5734 HttpRequestHeaders headers;
5735 headers.SetHeader("foo", "1");
5736 req.SetExtraRequestHeaders(headers);
5737 req.Start();
5738 base::RunLoop().Run();
5740 EXPECT_TRUE(req.was_cached());
5742 LoadTimingInfo load_timing_info;
5743 req.GetLoadTimingInfo(&load_timing_info);
5744 TestLoadTimingCacheHitNoNetwork(load_timing_info);
5747 // Expect a cache miss.
5749 TestDelegate d;
5750 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5751 DEFAULT_PRIORITY,
5753 &default_context_);
5754 HttpRequestHeaders headers;
5755 headers.SetHeader("foo", "2");
5756 req.SetExtraRequestHeaders(headers);
5757 req.Start();
5758 base::RunLoop().Run();
5760 EXPECT_FALSE(req.was_cached());
5762 LoadTimingInfo load_timing_info;
5763 req.GetLoadTimingInfo(&load_timing_info);
5764 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5768 TEST_F(URLRequestTestHTTP, BasicAuth) {
5769 ASSERT_TRUE(test_server_.Start());
5771 // populate the cache
5773 TestDelegate d;
5774 d.set_credentials(AuthCredentials(kUser, kSecret));
5776 URLRequest r(test_server_.GetURL("auth-basic"),
5777 DEFAULT_PRIORITY,
5779 &default_context_);
5780 r.Start();
5782 base::RunLoop().Run();
5784 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5787 // repeat request with end-to-end validation. since auth-basic results in a
5788 // cachable page, we expect this test to result in a 304. in which case, the
5789 // response should be fetched from the cache.
5791 TestDelegate d;
5792 d.set_credentials(AuthCredentials(kUser, kSecret));
5794 URLRequest r(test_server_.GetURL("auth-basic"),
5795 DEFAULT_PRIORITY,
5797 &default_context_);
5798 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5799 r.Start();
5801 base::RunLoop().Run();
5803 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5805 // Should be the same cached document.
5806 EXPECT_TRUE(r.was_cached());
5810 // Check that Set-Cookie headers in 401 responses are respected.
5811 // http://crbug.com/6450
5812 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5813 ASSERT_TRUE(test_server_.Start());
5815 GURL url_requiring_auth =
5816 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5818 // Request a page that will give a 401 containing a Set-Cookie header.
5819 // Verify that when the transaction is restarted, it includes the new cookie.
5821 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5822 TestURLRequestContext context(true);
5823 context.set_network_delegate(&network_delegate);
5824 context.Init();
5826 TestDelegate d;
5827 d.set_credentials(AuthCredentials(kUser, kSecret));
5829 URLRequest r(url_requiring_auth, DEFAULT_PRIORITY, &d, &context);
5830 r.Start();
5832 base::RunLoop().Run();
5834 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5836 // Make sure we sent the cookie in the restarted transaction.
5837 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5838 != std::string::npos);
5841 // Same test as above, except this time the restart is initiated earlier
5842 // (without user intervention since identity is embedded in the URL).
5844 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5845 TestURLRequestContext context(true);
5846 context.set_network_delegate(&network_delegate);
5847 context.Init();
5849 TestDelegate d;
5851 GURL::Replacements replacements;
5852 std::string username("user2");
5853 std::string password("secret");
5854 replacements.SetUsernameStr(username);
5855 replacements.SetPasswordStr(password);
5856 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5858 URLRequest r(url_with_identity, DEFAULT_PRIORITY, &d, &context);
5859 r.Start();
5861 base::RunLoop().Run();
5863 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5865 // Make sure we sent the cookie in the restarted transaction.
5866 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5867 != std::string::npos);
5871 // Tests that load timing works as expected with auth and the cache.
5872 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5873 ASSERT_TRUE(test_server_.Start());
5875 // populate the cache
5877 TestDelegate d;
5878 d.set_credentials(AuthCredentials(kUser, kSecret));
5880 URLRequest r(test_server_.GetURL("auth-basic"),
5881 DEFAULT_PRIORITY,
5883 &default_context_);
5884 r.Start();
5886 base::RunLoop().Run();
5888 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5890 LoadTimingInfo load_timing_info_before_auth;
5891 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5892 &load_timing_info_before_auth));
5893 TestLoadTimingNotReused(load_timing_info_before_auth,
5894 CONNECT_TIMING_HAS_DNS_TIMES);
5896 LoadTimingInfo load_timing_info;
5897 r.GetLoadTimingInfo(&load_timing_info);
5898 // The test server does not support keep alive sockets, so the second
5899 // request with auth should use a new socket.
5900 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5901 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5902 load_timing_info.socket_log_id);
5903 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5904 load_timing_info.connect_timing.connect_start);
5907 // Repeat request with end-to-end validation. Since auth-basic results in a
5908 // cachable page, we expect this test to result in a 304. In which case, the
5909 // response should be fetched from the cache.
5911 TestDelegate d;
5912 d.set_credentials(AuthCredentials(kUser, kSecret));
5914 URLRequest r(test_server_.GetURL("auth-basic"),
5915 DEFAULT_PRIORITY,
5917 &default_context_);
5918 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5919 r.Start();
5921 base::RunLoop().Run();
5923 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5925 // Should be the same cached document.
5926 EXPECT_TRUE(r.was_cached());
5928 // Since there was a request that went over the wire, the load timing
5929 // information should include connection times.
5930 LoadTimingInfo load_timing_info;
5931 r.GetLoadTimingInfo(&load_timing_info);
5932 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5936 // In this test, we do a POST which the server will 302 redirect.
5937 // The subsequent transaction should use GET, and should not send the
5938 // Content-Type header.
5939 // http://code.google.com/p/chromium/issues/detail?id=843
5940 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5941 ASSERT_TRUE(test_server_.Start());
5943 const char kData[] = "hello world";
5945 TestDelegate d;
5946 URLRequest req(test_server_.GetURL("files/redirect-to-echoall"),
5947 DEFAULT_PRIORITY,
5949 &default_context_);
5950 req.set_method("POST");
5951 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
5953 // Set headers (some of which are specific to the POST).
5954 HttpRequestHeaders headers;
5955 headers.AddHeadersFromString(
5956 "Content-Type: multipart/form-data; "
5957 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5958 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5959 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5960 "Accept-Language: en-US,en\r\n"
5961 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5962 "Content-Length: 11\r\n"
5963 "Origin: http://localhost:1337/");
5964 req.SetExtraRequestHeaders(headers);
5965 req.Start();
5966 base::RunLoop().Run();
5968 std::string mime_type;
5969 req.GetMimeType(&mime_type);
5970 EXPECT_EQ("text/html", mime_type);
5972 const std::string& data = d.data_received();
5974 // Check that the post-specific headers were stripped:
5975 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
5976 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
5977 EXPECT_FALSE(ContainsString(data, "Origin:"));
5979 // These extra request headers should not have been stripped.
5980 EXPECT_TRUE(ContainsString(data, "Accept:"));
5981 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
5982 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
5985 // The following tests check that we handle mutating the request method for
5986 // HTTP redirects as expected.
5987 // See http://crbug.com/56373 and http://crbug.com/102130.
5989 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
5990 ASSERT_TRUE(test_server_.Start());
5992 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
5994 HTTPRedirectMethodTest(url, "POST", "GET", true);
5995 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5996 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5999 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6000 ASSERT_TRUE(test_server_.Start());
6002 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6004 HTTPRedirectMethodTest(url, "POST", "GET", true);
6005 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6006 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6009 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6010 ASSERT_TRUE(test_server_.Start());
6012 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6014 HTTPRedirectMethodTest(url, "POST", "GET", true);
6015 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6016 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6019 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6020 ASSERT_TRUE(test_server_.Start());
6022 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6024 HTTPRedirectMethodTest(url, "POST", "POST", true);
6025 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6026 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6029 TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6030 ASSERT_TRUE(test_server_.Start());
6032 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6034 HTTPRedirectMethodTest(url, "POST", "POST", true);
6035 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6036 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6039 // Make sure that 308 responses without bodies are not treated as redirects.
6040 // Certain legacy apis that pre-date the response code expect this behavior
6041 // (Like Google Drive).
6042 TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6043 ASSERT_TRUE(test_server_.Start());
6045 TestDelegate d;
6046 const GURL url = test_server_.GetURL("files/308-without-location-header");
6048 URLRequest request(url, DEFAULT_PRIORITY, &d, &default_context_);
6050 request.Start();
6051 base::RunLoop().Run();
6052 EXPECT_EQ(URLRequestStatus::SUCCESS, request.status().status());
6053 EXPECT_EQ(OK, request.status().error());
6054 EXPECT_EQ(0, d.received_redirect_count());
6055 EXPECT_EQ(308, request.response_headers()->response_code());
6056 EXPECT_EQ("This is not a redirect.", d.data_received());
6059 TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6060 ASSERT_TRUE(test_server_.Start());
6062 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6063 GURL expected_url(test_server_.GetURL("echo#fragment"));
6065 TestDelegate d;
6067 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
6069 r.Start();
6070 base::RunLoop().Run();
6072 EXPECT_EQ(2U, r.url_chain().size());
6073 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
6074 EXPECT_EQ(net::OK, r.status().error());
6075 EXPECT_EQ(original_url, r.original_url());
6076 EXPECT_EQ(expected_url, r.url());
6080 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6081 ASSERT_TRUE(test_server_.Start());
6083 const char kData[] = "hello world";
6085 TestDelegate d;
6086 URLRequest req(test_server_.GetURL("empty.html"),
6087 DEFAULT_PRIORITY,
6089 &default_context_);
6090 req.set_method("POST");
6091 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6092 HttpRequestHeaders headers;
6093 headers.SetHeader(HttpRequestHeaders::kContentLength,
6094 base::UintToString(arraysize(kData) - 1));
6095 req.SetExtraRequestHeaders(headers);
6097 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6098 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6099 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6100 AddTestInterceptor()->set_main_intercept_job(job);
6102 req.Start();
6103 base::RunLoop().Run();
6104 EXPECT_EQ("GET", req.method());
6107 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6108 ASSERT_TRUE(test_server_.Start());
6110 const char kData[] = "hello world";
6112 TestDelegate d;
6113 URLRequest req(test_server_.GetURL("empty.html"),
6114 DEFAULT_PRIORITY,
6116 &default_context_);
6117 req.set_method("POST");
6118 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6119 HttpRequestHeaders headers;
6120 headers.SetHeader(HttpRequestHeaders::kContentLength,
6121 base::UintToString(arraysize(kData) - 1));
6122 req.SetExtraRequestHeaders(headers);
6124 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6125 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6126 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6127 "Very Good Reason");
6128 AddTestInterceptor()->set_main_intercept_job(job);
6130 req.Start();
6131 base::RunLoop().Run();
6132 EXPECT_EQ("POST", req.method());
6133 EXPECT_EQ(kData, d.data_received());
6136 // Check that default A-L header is sent.
6137 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6138 ASSERT_TRUE(test_server_.Start());
6140 StaticHttpUserAgentSettings settings("en", std::string());
6141 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6142 TestURLRequestContext context(true);
6143 context.set_network_delegate(&network_delegate);
6144 context.set_http_user_agent_settings(&settings);
6145 context.Init();
6147 TestDelegate d;
6148 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6149 DEFAULT_PRIORITY,
6151 &context);
6152 req.Start();
6153 base::RunLoop().Run();
6154 EXPECT_EQ("en", d.data_received());
6157 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6158 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6159 ASSERT_TRUE(test_server_.Start());
6161 std::string empty_string; // Avoid most vexing parse on line below.
6162 StaticHttpUserAgentSettings settings(empty_string, empty_string);
6163 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6164 TestURLRequestContext context(true);
6165 context.set_network_delegate(&network_delegate);
6166 context.Init();
6167 // We override the language after initialization because empty entries
6168 // get overridden by Init().
6169 context.set_http_user_agent_settings(&settings);
6171 TestDelegate d;
6172 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6173 DEFAULT_PRIORITY,
6175 &context);
6176 req.Start();
6177 base::RunLoop().Run();
6178 EXPECT_EQ("None", d.data_received());
6181 // Check that if request overrides the A-L header, the default is not appended.
6182 // See http://crbug.com/20894
6183 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6184 ASSERT_TRUE(test_server_.Start());
6186 TestDelegate d;
6187 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6188 DEFAULT_PRIORITY,
6190 &default_context_);
6191 HttpRequestHeaders headers;
6192 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6193 req.SetExtraRequestHeaders(headers);
6194 req.Start();
6195 base::RunLoop().Run();
6196 EXPECT_EQ(std::string("ru"), d.data_received());
6199 // Check that default A-E header is sent.
6200 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6201 ASSERT_TRUE(test_server_.Start());
6203 TestDelegate d;
6204 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
6205 DEFAULT_PRIORITY,
6207 &default_context_);
6208 HttpRequestHeaders headers;
6209 req.SetExtraRequestHeaders(headers);
6210 req.Start();
6211 base::RunLoop().Run();
6212 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6215 // Check that if request overrides the A-E header, the default is not appended.
6216 // See http://crbug.com/47381
6217 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6218 ASSERT_TRUE(test_server_.Start());
6220 TestDelegate d;
6221 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
6222 DEFAULT_PRIORITY,
6224 &default_context_);
6225 HttpRequestHeaders headers;
6226 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6227 req.SetExtraRequestHeaders(headers);
6228 req.Start();
6229 base::RunLoop().Run();
6230 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6231 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6234 // Check that setting the A-C header sends the proper header.
6235 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
6236 ASSERT_TRUE(test_server_.Start());
6238 TestDelegate d;
6239 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
6240 DEFAULT_PRIORITY,
6242 &default_context_);
6243 HttpRequestHeaders headers;
6244 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6245 req.SetExtraRequestHeaders(headers);
6246 req.Start();
6247 base::RunLoop().Run();
6248 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6251 // Check that default User-Agent header is sent.
6252 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6253 ASSERT_TRUE(test_server_.Start());
6255 TestDelegate d;
6256 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
6257 DEFAULT_PRIORITY,
6259 &default_context_);
6260 req.Start();
6261 base::RunLoop().Run();
6262 EXPECT_EQ(req.context()->http_user_agent_settings()->GetUserAgent(),
6263 d.data_received());
6266 // Check that if request overrides the User-Agent header,
6267 // the default is not appended.
6268 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6269 ASSERT_TRUE(test_server_.Start());
6271 TestDelegate d;
6272 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
6273 DEFAULT_PRIORITY,
6275 &default_context_);
6276 HttpRequestHeaders headers;
6277 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6278 req.SetExtraRequestHeaders(headers);
6279 req.Start();
6280 base::RunLoop().Run();
6281 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
6284 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6285 // User-Agent header to be sent but does not send the Accept-Language and
6286 // Accept-Charset headers.
6287 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6288 ASSERT_TRUE(test_server_.Start());
6290 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6291 TestURLRequestContext context(true);
6292 context.set_network_delegate(&network_delegate);
6293 context.Init();
6294 // We override the HttpUserAgentSettings after initialization because empty
6295 // entries get overridden by Init().
6296 context.set_http_user_agent_settings(NULL);
6298 struct {
6299 const char* request;
6300 const char* expected_response;
6301 } tests[] = { { "echoheader?Accept-Language", "None" },
6302 { "echoheader?Accept-Charset", "None" },
6303 { "echoheader?User-Agent", "" } };
6305 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
6306 TestDelegate d;
6307 URLRequest req(
6308 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, &context);
6309 req.Start();
6310 base::RunLoop().Run();
6311 EXPECT_EQ(tests[i].expected_response, d.data_received())
6312 << " Request = \"" << tests[i].request << "\"";
6316 // Make sure that URLRequest passes on its priority updates to
6317 // newly-created jobs after the first one.
6318 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6319 ASSERT_TRUE(test_server_.Start());
6321 TestDelegate d;
6322 URLRequest req(test_server_.GetURL("empty.html"),
6323 DEFAULT_PRIORITY,
6325 &default_context_);
6326 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
6328 scoped_refptr<URLRequestRedirectJob> redirect_job =
6329 new URLRequestRedirectJob(
6330 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6331 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6332 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
6334 req.SetPriority(LOW);
6335 req.Start();
6336 EXPECT_TRUE(req.is_pending());
6338 scoped_refptr<URLRequestTestJob> job =
6339 new URLRequestTestJob(&req, &default_network_delegate_);
6340 AddTestInterceptor()->set_main_intercept_job(job.get());
6342 // Should trigger |job| to be started.
6343 base::RunLoop().Run();
6344 EXPECT_EQ(LOW, job->priority());
6347 // Check that creating a network request while entering/exiting suspend mode
6348 // fails as it should. This is the only case where an HttpTransactionFactory
6349 // does not return an HttpTransaction.
6350 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6351 // Create a new HttpNetworkLayer that thinks it's suspended.
6352 HttpNetworkSession::Params params;
6353 params.host_resolver = default_context_.host_resolver();
6354 params.cert_verifier = default_context_.cert_verifier();
6355 params.transport_security_state = default_context_.transport_security_state();
6356 params.proxy_service = default_context_.proxy_service();
6357 params.ssl_config_service = default_context_.ssl_config_service();
6358 params.http_auth_handler_factory =
6359 default_context_.http_auth_handler_factory();
6360 params.network_delegate = &default_network_delegate_;
6361 params.http_server_properties = default_context_.http_server_properties();
6362 scoped_ptr<HttpNetworkLayer> network_layer(
6363 new HttpNetworkLayer(new HttpNetworkSession(params)));
6364 network_layer->OnSuspend();
6366 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6367 HttpCache::DefaultBackend::InMemory(0));
6369 TestURLRequestContext context(true);
6370 context.set_http_transaction_factory(&http_cache);
6371 context.Init();
6373 TestDelegate d;
6374 URLRequest req(GURL("http://127.0.0.1/"),
6375 DEFAULT_PRIORITY,
6377 &context);
6378 req.Start();
6379 base::RunLoop().Run();
6381 EXPECT_TRUE(d.request_failed());
6382 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6383 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6386 // Check that creating a network request while entering/exiting suspend mode
6387 // fails as it should in the case there is no cache. This is the only case
6388 // where an HttpTransactionFactory does not return an HttpTransaction.
6389 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6390 // Create a new HttpNetworkLayer that thinks it's suspended.
6391 HttpNetworkSession::Params params;
6392 params.host_resolver = default_context_.host_resolver();
6393 params.cert_verifier = default_context_.cert_verifier();
6394 params.transport_security_state = default_context_.transport_security_state();
6395 params.proxy_service = default_context_.proxy_service();
6396 params.ssl_config_service = default_context_.ssl_config_service();
6397 params.http_auth_handler_factory =
6398 default_context_.http_auth_handler_factory();
6399 params.network_delegate = &default_network_delegate_;
6400 params.http_server_properties = default_context_.http_server_properties();
6401 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6402 network_layer.OnSuspend();
6404 TestURLRequestContext context(true);
6405 context.set_http_transaction_factory(&network_layer);
6406 context.Init();
6408 TestDelegate d;
6409 URLRequest req(GURL("http://127.0.0.1/"),
6410 DEFAULT_PRIORITY,
6412 &context);
6413 req.Start();
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 class HTTPSRequestTest : public testing::Test {
6422 public:
6423 HTTPSRequestTest() : default_context_(true) {
6424 default_context_.set_network_delegate(&default_network_delegate_);
6425 default_context_.Init();
6427 virtual ~HTTPSRequestTest() {}
6429 protected:
6430 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
6431 TestURLRequestContext default_context_;
6434 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
6435 SpawnedTestServer test_server(
6436 SpawnedTestServer::TYPE_HTTPS,
6437 SpawnedTestServer::kLocalhost,
6438 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6439 ASSERT_TRUE(test_server.Start());
6441 TestDelegate d;
6443 URLRequest r(test_server.GetURL(std::string()),
6444 DEFAULT_PRIORITY,
6446 &default_context_);
6447 r.Start();
6448 EXPECT_TRUE(r.is_pending());
6450 base::RunLoop().Run();
6452 EXPECT_EQ(1, d.response_started_count());
6453 EXPECT_FALSE(d.received_data_before_response());
6454 EXPECT_NE(0, d.bytes_received());
6455 CheckSSLInfo(r.ssl_info());
6456 EXPECT_EQ(test_server.host_port_pair().host(),
6457 r.GetSocketAddress().host());
6458 EXPECT_EQ(test_server.host_port_pair().port(),
6459 r.GetSocketAddress().port());
6463 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
6464 SpawnedTestServer::SSLOptions ssl_options(
6465 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6466 SpawnedTestServer test_server(
6467 SpawnedTestServer::TYPE_HTTPS,
6468 ssl_options,
6469 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6470 ASSERT_TRUE(test_server.Start());
6472 bool err_allowed = true;
6473 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6474 TestDelegate d;
6476 d.set_allow_certificate_errors(err_allowed);
6477 URLRequest r(test_server.GetURL(std::string()),
6478 DEFAULT_PRIORITY,
6480 &default_context_);
6482 r.Start();
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_TRUE(d.have_certificate_errors());
6490 if (err_allowed) {
6491 EXPECT_NE(0, d.bytes_received());
6492 CheckSSLInfo(r.ssl_info());
6493 } else {
6494 EXPECT_EQ(0, d.bytes_received());
6500 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
6501 SpawnedTestServer::SSLOptions ssl_options(
6502 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6503 SpawnedTestServer test_server(
6504 SpawnedTestServer::TYPE_HTTPS,
6505 ssl_options,
6506 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6507 ASSERT_TRUE(test_server.Start());
6509 // Iterate from false to true, just so that we do the opposite of the
6510 // previous test in order to increase test coverage.
6511 bool err_allowed = false;
6512 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6513 TestDelegate d;
6515 d.set_allow_certificate_errors(err_allowed);
6516 URLRequest r(test_server.GetURL(std::string()),
6517 DEFAULT_PRIORITY,
6519 &default_context_);
6521 r.Start();
6522 EXPECT_TRUE(r.is_pending());
6524 base::RunLoop().Run();
6526 EXPECT_EQ(1, d.response_started_count());
6527 EXPECT_FALSE(d.received_data_before_response());
6528 EXPECT_TRUE(d.have_certificate_errors());
6529 if (err_allowed) {
6530 EXPECT_NE(0, d.bytes_received());
6531 CheckSSLInfo(r.ssl_info());
6532 } else {
6533 EXPECT_EQ(0, d.bytes_received());
6539 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
6540 // than necessary.
6541 TEST_F(HTTPSRequestTest, TLSv1Fallback) {
6542 // The OpenSSL library in use may not support TLS 1.1.
6543 #if !defined(USE_OPENSSL)
6544 EXPECT_GT(kDefaultSSLVersionMax, SSL_PROTOCOL_VERSION_TLS1);
6545 #endif
6546 if (kDefaultSSLVersionMax <= SSL_PROTOCOL_VERSION_TLS1)
6547 return;
6549 SpawnedTestServer::SSLOptions ssl_options(
6550 SpawnedTestServer::SSLOptions::CERT_OK);
6551 ssl_options.tls_intolerant =
6552 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
6553 SpawnedTestServer test_server(
6554 SpawnedTestServer::TYPE_HTTPS,
6555 ssl_options,
6556 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6557 ASSERT_TRUE(test_server.Start());
6559 TestDelegate d;
6560 TestURLRequestContext context(true);
6561 context.Init();
6562 d.set_allow_certificate_errors(true);
6563 URLRequest r(
6564 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6565 r.Start();
6567 base::RunLoop().Run();
6569 EXPECT_EQ(1, d.response_started_count());
6570 EXPECT_NE(0, d.bytes_received());
6571 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
6572 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6573 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6576 // Tests that we don't fallback with servers that implement TLS_FALLBACK_SCSV.
6577 #if defined(USE_OPENSSL)
6578 TEST_F(HTTPSRequestTest, DISABLED_FallbackSCSV) {
6579 #else
6580 TEST_F(HTTPSRequestTest, FallbackSCSV) {
6581 #endif
6582 SpawnedTestServer::SSLOptions ssl_options(
6583 SpawnedTestServer::SSLOptions::CERT_OK);
6584 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
6585 // a version fallback.
6586 ssl_options.tls_intolerant =
6587 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6588 // Have the server process TLS_FALLBACK_SCSV so that version fallback
6589 // connections are rejected.
6590 ssl_options.fallback_scsv_enabled = true;
6592 SpawnedTestServer test_server(
6593 SpawnedTestServer::TYPE_HTTPS,
6594 ssl_options,
6595 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6596 ASSERT_TRUE(test_server.Start());
6598 TestDelegate d;
6599 TestURLRequestContext context(true);
6600 context.Init();
6601 d.set_allow_certificate_errors(true);
6602 URLRequest r(
6603 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6604 r.Start();
6606 base::RunLoop().Run();
6608 EXPECT_EQ(1, d.response_started_count());
6609 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
6610 // intolerance. If the fallback SCSV is processed when the original error
6611 // that caused the fallback should be returned, which should be
6612 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
6613 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, r.status().error());
6616 // This tests that a load of www.google.com with a certificate error sets
6617 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
6618 // the interstitial to be fatal.
6619 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
6620 SpawnedTestServer::SSLOptions ssl_options(
6621 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6622 SpawnedTestServer test_server(
6623 SpawnedTestServer::TYPE_HTTPS,
6624 ssl_options,
6625 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6626 ASSERT_TRUE(test_server.Start());
6628 // We require that the URL be www.google.com in order to pick up the
6629 // preloaded HSTS entries in the TransportSecurityState. This means that we
6630 // have to use a MockHostResolver in order to direct www.google.com to the
6631 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6633 MockHostResolver host_resolver;
6634 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6635 TestURLRequestContext context(true);
6636 context.set_network_delegate(&network_delegate);
6637 context.set_host_resolver(&host_resolver);
6638 TransportSecurityState transport_security_state;
6639 context.set_transport_security_state(&transport_security_state);
6640 context.Init();
6642 TestDelegate d;
6643 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6644 test_server.host_port_pair().port())),
6645 DEFAULT_PRIORITY,
6647 &context);
6649 r.Start();
6650 EXPECT_TRUE(r.is_pending());
6652 base::RunLoop().Run();
6654 EXPECT_EQ(1, d.response_started_count());
6655 EXPECT_FALSE(d.received_data_before_response());
6656 EXPECT_TRUE(d.have_certificate_errors());
6657 EXPECT_TRUE(d.certificate_errors_are_fatal());
6660 // This tests that cached HTTPS page loads do not cause any updates to the
6661 // TransportSecurityState.
6662 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6663 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6664 // matter. It just has to be any error.
6665 SpawnedTestServer::SSLOptions ssl_options(
6666 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6667 SpawnedTestServer test_server(
6668 SpawnedTestServer::TYPE_HTTPS,
6669 ssl_options,
6670 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6671 ASSERT_TRUE(test_server.Start());
6673 // We require that the URL be www.google.com in order to pick up the static
6674 // and dynamic STS and PKP entries in the TransportSecurityState. This means
6675 // that we have to use a MockHostResolver in order to direct www.google.com to
6676 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6678 MockHostResolver host_resolver;
6679 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6680 TestURLRequestContext context(true);
6681 context.set_network_delegate(&network_delegate);
6682 context.set_host_resolver(&host_resolver);
6683 TransportSecurityState transport_security_state;
6685 TransportSecurityState::DomainState static_domain_state;
6686 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6687 "www.google.com", true, &static_domain_state));
6688 context.set_transport_security_state(&transport_security_state);
6689 context.Init();
6691 TransportSecurityState::DomainState dynamic_domain_state;
6692 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6693 "www.google.com", &dynamic_domain_state));
6695 TestDelegate d;
6696 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6697 test_server.host_port_pair().port())),
6698 DEFAULT_PRIORITY,
6700 &context);
6702 r.Start();
6703 EXPECT_TRUE(r.is_pending());
6705 base::RunLoop().Run();
6707 EXPECT_EQ(1, d.response_started_count());
6708 EXPECT_FALSE(d.received_data_before_response());
6709 EXPECT_TRUE(d.have_certificate_errors());
6710 EXPECT_TRUE(d.certificate_errors_are_fatal());
6712 // Get a fresh copy of the states, and check that they haven't changed.
6713 TransportSecurityState::DomainState new_static_domain_state;
6714 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6715 "www.google.com", true, &new_static_domain_state));
6716 TransportSecurityState::DomainState new_dynamic_domain_state;
6717 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6718 "www.google.com", &new_dynamic_domain_state));
6720 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
6721 static_domain_state.sts.upgrade_mode);
6722 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
6723 static_domain_state.sts.include_subdomains);
6724 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
6725 static_domain_state.pkp.include_subdomains);
6726 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
6727 static_domain_state.pkp.spki_hashes));
6728 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
6729 static_domain_state.pkp.bad_spki_hashes));
6732 // Make sure HSTS preserves a POST request's method and body.
6733 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6734 static const char kData[] = "hello world";
6736 SpawnedTestServer::SSLOptions ssl_options(
6737 SpawnedTestServer::SSLOptions::CERT_OK);
6738 SpawnedTestServer test_server(
6739 SpawnedTestServer::TYPE_HTTPS,
6740 ssl_options,
6741 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6742 ASSERT_TRUE(test_server.Start());
6745 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6746 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
6747 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6748 // to 127.0.0.1.
6749 MockHostResolver host_resolver;
6751 // Force https for www.somewhere.com.
6752 TransportSecurityState transport_security_state;
6753 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6754 bool include_subdomains = false;
6755 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6756 include_subdomains);
6758 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6760 TestURLRequestContext context(true);
6761 context.set_host_resolver(&host_resolver);
6762 context.set_transport_security_state(&transport_security_state);
6763 context.set_network_delegate(&network_delegate);
6764 context.Init();
6766 TestDelegate d;
6767 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6768 // cause a certificate error. Ignore the error.
6769 d.set_allow_certificate_errors(true);
6771 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6772 test_server.host_port_pair().port())),
6773 DEFAULT_PRIORITY,
6775 &context);
6776 req.set_method("POST");
6777 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6779 req.Start();
6780 base::RunLoop().Run();
6782 EXPECT_EQ("https", req.url().scheme());
6783 EXPECT_EQ("POST", req.method());
6784 EXPECT_EQ(kData, d.data_received());
6786 LoadTimingInfo load_timing_info;
6787 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6788 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6789 TestLoadTimingCacheHitNoNetwork(load_timing_info);
6792 TEST_F(HTTPSRequestTest, SSLv3Fallback) {
6793 SpawnedTestServer::SSLOptions ssl_options(
6794 SpawnedTestServer::SSLOptions::CERT_OK);
6795 ssl_options.tls_intolerant =
6796 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6797 SpawnedTestServer test_server(
6798 SpawnedTestServer::TYPE_HTTPS,
6799 ssl_options,
6800 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6801 ASSERT_TRUE(test_server.Start());
6803 TestDelegate d;
6804 TestURLRequestContext context(true);
6805 context.Init();
6806 d.set_allow_certificate_errors(true);
6807 URLRequest r(
6808 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6809 r.Start();
6811 base::RunLoop().Run();
6813 EXPECT_EQ(1, d.response_started_count());
6814 EXPECT_NE(0, d.bytes_received());
6815 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
6816 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6817 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6820 namespace {
6822 class SSLClientAuthTestDelegate : public TestDelegate {
6823 public:
6824 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6826 virtual void OnCertificateRequested(
6827 URLRequest* request,
6828 SSLCertRequestInfo* cert_request_info) OVERRIDE {
6829 on_certificate_requested_count_++;
6830 base::MessageLoop::current()->Quit();
6832 int on_certificate_requested_count() {
6833 return on_certificate_requested_count_;
6835 private:
6836 int on_certificate_requested_count_;
6839 } // namespace
6841 // TODO(davidben): Test the rest of the code. Specifically,
6842 // - Filtering which certificates to select.
6843 // - Sending a certificate back.
6844 // - Getting a certificate request in an SSL renegotiation sending the
6845 // HTTP request.
6846 TEST_F(HTTPSRequestTest, ClientAuthTest) {
6847 SpawnedTestServer::SSLOptions ssl_options;
6848 ssl_options.request_client_certificate = true;
6849 SpawnedTestServer test_server(
6850 SpawnedTestServer::TYPE_HTTPS,
6851 ssl_options,
6852 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6853 ASSERT_TRUE(test_server.Start());
6855 SSLClientAuthTestDelegate d;
6857 URLRequest r(test_server.GetURL(std::string()),
6858 DEFAULT_PRIORITY,
6860 &default_context_);
6862 r.Start();
6863 EXPECT_TRUE(r.is_pending());
6865 base::RunLoop().Run();
6867 EXPECT_EQ(1, d.on_certificate_requested_count());
6868 EXPECT_FALSE(d.received_data_before_response());
6869 EXPECT_EQ(0, d.bytes_received());
6871 // Send no certificate.
6872 // TODO(davidben): Get temporary client cert import (with keys) working on
6873 // all platforms so we can test sending a cert as well.
6874 r.ContinueWithCertificate(NULL);
6876 base::RunLoop().Run();
6878 EXPECT_EQ(1, d.response_started_count());
6879 EXPECT_FALSE(d.received_data_before_response());
6880 EXPECT_NE(0, d.bytes_received());
6884 TEST_F(HTTPSRequestTest, ResumeTest) {
6885 // Test that we attempt a session resume when making two connections to the
6886 // same host.
6887 SpawnedTestServer::SSLOptions ssl_options;
6888 ssl_options.record_resume = true;
6889 SpawnedTestServer test_server(
6890 SpawnedTestServer::TYPE_HTTPS,
6891 ssl_options,
6892 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6893 ASSERT_TRUE(test_server.Start());
6895 SSLClientSocket::ClearSessionCache();
6898 TestDelegate d;
6899 URLRequest r(test_server.GetURL("ssl-session-cache"),
6900 DEFAULT_PRIORITY,
6902 &default_context_);
6904 r.Start();
6905 EXPECT_TRUE(r.is_pending());
6907 base::RunLoop().Run();
6909 EXPECT_EQ(1, d.response_started_count());
6912 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6913 CloseAllConnections();
6916 TestDelegate d;
6917 URLRequest r(test_server.GetURL("ssl-session-cache"),
6918 DEFAULT_PRIORITY,
6920 &default_context_);
6922 r.Start();
6923 EXPECT_TRUE(r.is_pending());
6925 base::RunLoop().Run();
6927 // The response will look like;
6928 // insert abc
6929 // lookup abc
6930 // insert xyz
6932 // With a newline at the end which makes the split think that there are
6933 // four lines.
6935 EXPECT_EQ(1, d.response_started_count());
6936 std::vector<std::string> lines;
6937 base::SplitString(d.data_received(), '\n', &lines);
6938 ASSERT_EQ(4u, lines.size()) << d.data_received();
6940 std::string session_id;
6942 for (size_t i = 0; i < 2; i++) {
6943 std::vector<std::string> parts;
6944 base::SplitString(lines[i], '\t', &parts);
6945 ASSERT_EQ(2u, parts.size());
6946 if (i == 0) {
6947 EXPECT_EQ("insert", parts[0]);
6948 session_id = parts[1];
6949 } else {
6950 EXPECT_EQ("lookup", parts[0]);
6951 EXPECT_EQ(session_id, parts[1]);
6957 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6958 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6959 // differs.
6960 SpawnedTestServer::SSLOptions ssl_options;
6961 ssl_options.record_resume = true;
6962 SpawnedTestServer test_server(
6963 SpawnedTestServer::TYPE_HTTPS,
6964 ssl_options,
6965 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6966 ASSERT_TRUE(test_server.Start());
6968 SSLClientSocket::ClearSessionCache();
6971 TestDelegate d;
6972 URLRequest r(test_server.GetURL("ssl-session-cache"),
6973 DEFAULT_PRIORITY,
6975 &default_context_);
6977 r.Start();
6978 EXPECT_TRUE(r.is_pending());
6980 base::RunLoop().Run();
6982 EXPECT_EQ(1, d.response_started_count());
6985 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6986 HttpNetworkSession::Params params;
6987 params.host_resolver = default_context_.host_resolver();
6988 params.cert_verifier = default_context_.cert_verifier();
6989 params.transport_security_state = default_context_.transport_security_state();
6990 params.proxy_service = default_context_.proxy_service();
6991 params.ssl_config_service = default_context_.ssl_config_service();
6992 params.http_auth_handler_factory =
6993 default_context_.http_auth_handler_factory();
6994 params.network_delegate = &default_network_delegate_;
6995 params.http_server_properties = default_context_.http_server_properties();
6996 params.ssl_session_cache_shard = "alternate";
6998 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
6999 new net::HttpNetworkSession(params),
7000 net::HttpCache::DefaultBackend::InMemory(0)));
7002 default_context_.set_http_transaction_factory(cache.get());
7005 TestDelegate d;
7006 URLRequest r(test_server.GetURL("ssl-session-cache"),
7007 DEFAULT_PRIORITY,
7009 &default_context_);
7011 r.Start();
7012 EXPECT_TRUE(r.is_pending());
7014 base::RunLoop().Run();
7016 // The response will look like;
7017 // insert abc
7018 // insert xyz
7020 // With a newline at the end which makes the split think that there are
7021 // three lines.
7023 EXPECT_EQ(1, d.response_started_count());
7024 std::vector<std::string> lines;
7025 base::SplitString(d.data_received(), '\n', &lines);
7026 ASSERT_EQ(3u, lines.size());
7028 std::string session_id;
7029 for (size_t i = 0; i < 2; i++) {
7030 std::vector<std::string> parts;
7031 base::SplitString(lines[i], '\t', &parts);
7032 ASSERT_EQ(2u, parts.size());
7033 EXPECT_EQ("insert", parts[0]);
7034 if (i == 0) {
7035 session_id = parts[1];
7036 } else {
7037 EXPECT_NE(session_id, parts[1]);
7043 class HTTPSSessionTest : public testing::Test {
7044 public:
7045 HTTPSSessionTest() : default_context_(true) {
7046 cert_verifier_.set_default_result(net::OK);
7048 default_context_.set_network_delegate(&default_network_delegate_);
7049 default_context_.set_cert_verifier(&cert_verifier_);
7050 default_context_.Init();
7052 virtual ~HTTPSSessionTest() {}
7054 protected:
7055 MockCertVerifier cert_verifier_;
7056 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7057 TestURLRequestContext default_context_;
7060 // Tests that session resumption is not attempted if an invalid certificate
7061 // is presented.
7062 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7063 SpawnedTestServer::SSLOptions ssl_options;
7064 ssl_options.record_resume = true;
7065 SpawnedTestServer test_server(
7066 SpawnedTestServer::TYPE_HTTPS,
7067 ssl_options,
7068 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7069 ASSERT_TRUE(test_server.Start());
7071 SSLClientSocket::ClearSessionCache();
7073 // Simulate the certificate being expired and attempt a connection.
7074 cert_verifier_.set_default_result(net::ERR_CERT_DATE_INVALID);
7076 TestDelegate d;
7077 URLRequest r(test_server.GetURL("ssl-session-cache"),
7078 DEFAULT_PRIORITY,
7080 &default_context_);
7082 r.Start();
7083 EXPECT_TRUE(r.is_pending());
7085 base::RunLoop().Run();
7087 EXPECT_EQ(1, d.response_started_count());
7090 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7091 CloseAllConnections();
7093 // Now change the certificate to be acceptable (so that the response is
7094 // loaded), and ensure that no session id is presented to the peer.
7095 cert_verifier_.set_default_result(net::OK);
7097 TestDelegate d;
7098 URLRequest r(test_server.GetURL("ssl-session-cache"),
7099 DEFAULT_PRIORITY,
7101 &default_context_);
7103 r.Start();
7104 EXPECT_TRUE(r.is_pending());
7106 base::RunLoop().Run();
7108 // The response will look like;
7109 // insert abc
7110 // insert xyz
7112 // With a newline at the end which makes the split think that there are
7113 // three lines.
7115 // If a session was presented (eg: a bug), then the response would look
7116 // like;
7117 // insert abc
7118 // lookup abc
7119 // insert xyz
7121 EXPECT_EQ(1, d.response_started_count());
7122 std::vector<std::string> lines;
7123 base::SplitString(d.data_received(), '\n', &lines);
7124 ASSERT_EQ(3u, lines.size()) << d.data_received();
7126 std::string session_id;
7127 for (size_t i = 0; i < 2; i++) {
7128 std::vector<std::string> parts;
7129 base::SplitString(lines[i], '\t', &parts);
7130 ASSERT_EQ(2u, parts.size());
7131 EXPECT_EQ("insert", parts[0]);
7132 if (i == 0) {
7133 session_id = parts[1];
7134 } else {
7135 EXPECT_NE(session_id, parts[1]);
7141 class TestSSLConfigService : public SSLConfigService {
7142 public:
7143 TestSSLConfigService(bool ev_enabled,
7144 bool online_rev_checking,
7145 bool rev_checking_required_local_anchors)
7146 : ev_enabled_(ev_enabled),
7147 online_rev_checking_(online_rev_checking),
7148 rev_checking_required_local_anchors_(
7149 rev_checking_required_local_anchors) {}
7151 // SSLConfigService:
7152 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
7153 *config = SSLConfig();
7154 config->rev_checking_enabled = online_rev_checking_;
7155 config->verify_ev_cert = ev_enabled_;
7156 config->rev_checking_required_local_anchors =
7157 rev_checking_required_local_anchors_;
7160 protected:
7161 virtual ~TestSSLConfigService() {}
7163 private:
7164 const bool ev_enabled_;
7165 const bool online_rev_checking_;
7166 const bool rev_checking_required_local_anchors_;
7169 // This the fingerprint of the "Testing CA" certificate used by the testserver.
7170 // See net/data/ssl/certificates/ocsp-test-root.pem.
7171 static const SHA1HashValue kOCSPTestCertFingerprint =
7172 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7173 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7175 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7176 // testserver.
7177 static const SHA256HashValue kOCSPTestCertSPKI = { {
7178 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7179 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7180 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7181 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7182 } };
7184 // This is the policy OID contained in the certificates that testserver
7185 // generates.
7186 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
7188 class HTTPSOCSPTest : public HTTPSRequestTest {
7189 public:
7190 HTTPSOCSPTest()
7191 : context_(true),
7192 ev_test_policy_(
7193 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7194 kOCSPTestCertFingerprint,
7195 kOCSPTestCertPolicy)) {
7198 virtual void SetUp() OVERRIDE {
7199 SetupContext(&context_);
7200 context_.Init();
7202 scoped_refptr<net::X509Certificate> root_cert =
7203 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
7204 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
7205 test_root_.reset(new ScopedTestRoot(root_cert.get()));
7207 #if defined(USE_NSS) || defined(OS_IOS)
7208 SetURLRequestContextForNSSHttpIO(&context_);
7209 EnsureNSSHttpIOInit();
7210 #endif
7213 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
7214 CertStatus* out_cert_status) {
7215 // We always overwrite out_cert_status.
7216 *out_cert_status = 0;
7217 SpawnedTestServer test_server(
7218 SpawnedTestServer::TYPE_HTTPS,
7219 ssl_options,
7220 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7221 ASSERT_TRUE(test_server.Start());
7223 TestDelegate d;
7224 d.set_allow_certificate_errors(true);
7225 URLRequest r(
7226 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context_);
7227 r.Start();
7229 base::RunLoop().Run();
7231 EXPECT_EQ(1, d.response_started_count());
7232 *out_cert_status = r.ssl_info().cert_status;
7235 virtual ~HTTPSOCSPTest() {
7236 #if defined(USE_NSS) || defined(OS_IOS)
7237 ShutdownNSSHttpIO();
7238 #endif
7241 protected:
7242 // SetupContext configures the URLRequestContext that will be used for making
7243 // connetions to testserver. This can be overridden in test subclasses for
7244 // different behaviour.
7245 virtual void SetupContext(URLRequestContext* context) {
7246 context->set_ssl_config_service(
7247 new TestSSLConfigService(true /* check for EV */,
7248 true /* online revocation checking */,
7249 false /* require rev. checking for local
7250 anchors */));
7253 scoped_ptr<ScopedTestRoot> test_root_;
7254 TestURLRequestContext context_;
7255 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
7258 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
7259 #if defined(OS_WIN)
7260 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7261 // have that ability on other platforms.
7262 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
7263 #else
7264 return 0;
7265 #endif
7268 // SystemSupportsHardFailRevocationChecking returns true iff the current
7269 // operating system supports revocation checking and can distinguish between
7270 // situations where a given certificate lacks any revocation information (eg:
7271 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7272 // revocation information cannot be obtained (eg: the CRL was unreachable).
7273 // If it does not, then tests which rely on 'hard fail' behaviour should be
7274 // skipped.
7275 static bool SystemSupportsHardFailRevocationChecking() {
7276 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7277 return true;
7278 #else
7279 return false;
7280 #endif
7283 // SystemUsesChromiumEVMetadata returns true iff the current operating system
7284 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7285 // several tests are effected because our testing EV certificate won't be
7286 // recognised as EV.
7287 static bool SystemUsesChromiumEVMetadata() {
7288 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
7289 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7290 return false;
7291 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7292 // On OS X and Android, we use the system to tell us whether a certificate is
7293 // EV or not and the system won't recognise our testing root.
7294 return false;
7295 #else
7296 return true;
7297 #endif
7300 static bool SystemSupportsOCSP() {
7301 #if defined(USE_OPENSSL)
7302 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7303 return false;
7304 #elif defined(OS_WIN)
7305 return base::win::GetVersion() >= base::win::VERSION_VISTA;
7306 #elif defined(OS_ANDROID)
7307 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7308 return false;
7309 #else
7310 return true;
7311 #endif
7314 TEST_F(HTTPSOCSPTest, Valid) {
7315 if (!SystemSupportsOCSP()) {
7316 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7317 return;
7320 SpawnedTestServer::SSLOptions ssl_options(
7321 SpawnedTestServer::SSLOptions::CERT_AUTO);
7322 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7324 CertStatus cert_status;
7325 DoConnection(ssl_options, &cert_status);
7327 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7329 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7330 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7332 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7335 TEST_F(HTTPSOCSPTest, Revoked) {
7336 if (!SystemSupportsOCSP()) {
7337 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7338 return;
7341 SpawnedTestServer::SSLOptions ssl_options(
7342 SpawnedTestServer::SSLOptions::CERT_AUTO);
7343 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7345 CertStatus cert_status;
7346 DoConnection(ssl_options, &cert_status);
7348 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
7349 // Doesn't pass on OS X yet for reasons that need to be investigated.
7350 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7351 #endif
7352 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7353 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7356 TEST_F(HTTPSOCSPTest, Invalid) {
7357 if (!SystemSupportsOCSP()) {
7358 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7359 return;
7362 SpawnedTestServer::SSLOptions ssl_options(
7363 SpawnedTestServer::SSLOptions::CERT_AUTO);
7364 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7366 CertStatus cert_status;
7367 DoConnection(ssl_options, &cert_status);
7369 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7370 cert_status & CERT_STATUS_ALL_ERRORS);
7372 // Without a positive OCSP response, we shouldn't show the EV status.
7373 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7374 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7377 class HTTPSHardFailTest : public HTTPSOCSPTest {
7378 protected:
7379 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7380 context->set_ssl_config_service(
7381 new TestSSLConfigService(false /* check for EV */,
7382 false /* online revocation checking */,
7383 true /* require rev. checking for local
7384 anchors */));
7389 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
7390 if (!SystemSupportsOCSP()) {
7391 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7392 return;
7395 if (!SystemSupportsHardFailRevocationChecking()) {
7396 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
7397 << "revocation checking";
7398 return;
7401 SpawnedTestServer::SSLOptions ssl_options(
7402 SpawnedTestServer::SSLOptions::CERT_AUTO);
7403 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7405 CertStatus cert_status;
7406 DoConnection(ssl_options, &cert_status);
7408 EXPECT_EQ(CERT_STATUS_REVOKED,
7409 cert_status & CERT_STATUS_REVOKED);
7411 // Without a positive OCSP response, we shouldn't show the EV status.
7412 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7415 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
7416 protected:
7417 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7418 context->set_ssl_config_service(
7419 new TestSSLConfigService(true /* check for EV */,
7420 false /* online revocation checking */,
7421 false /* require rev. checking for local
7422 anchors */));
7426 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
7427 if (!SystemSupportsOCSP()) {
7428 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7429 return;
7432 SpawnedTestServer::SSLOptions ssl_options(
7433 SpawnedTestServer::SSLOptions::CERT_AUTO);
7434 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7435 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7437 CertStatus cert_status;
7438 DoConnection(ssl_options, &cert_status);
7440 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7441 cert_status & CERT_STATUS_ALL_ERRORS);
7443 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7444 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7445 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7448 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
7449 if (!SystemSupportsOCSP()) {
7450 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7451 return;
7454 SpawnedTestServer::SSLOptions ssl_options(
7455 SpawnedTestServer::SSLOptions::CERT_AUTO);
7456 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7457 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7459 CertStatus cert_status;
7460 DoConnection(ssl_options, &cert_status);
7462 // Currently only works for Windows. When using NSS or OS X, it's not
7463 // possible to determine whether the check failed because of actual
7464 // revocation or because there was an OCSP failure.
7465 #if defined(OS_WIN)
7466 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7467 #else
7468 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7469 #endif
7471 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7472 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7473 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7476 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
7477 if (!SystemSupportsOCSP()) {
7478 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7479 return;
7482 SpawnedTestServer::SSLOptions ssl_options(
7483 SpawnedTestServer::SSLOptions::CERT_AUTO);
7484 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7485 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7487 CertStatus cert_status;
7488 DoConnection(ssl_options, &cert_status);
7490 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7492 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7493 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7494 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7495 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7498 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
7499 if (!SystemSupportsOCSP()) {
7500 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7501 return;
7504 SpawnedTestServer::SSLOptions ssl_options(
7505 SpawnedTestServer::SSLOptions::CERT_AUTO);
7506 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7507 SSLConfigService::SetCRLSet(
7508 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7510 CertStatus cert_status;
7511 DoConnection(ssl_options, &cert_status);
7513 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7514 cert_status & CERT_STATUS_ALL_ERRORS);
7516 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7517 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7518 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7521 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
7522 if (!SystemSupportsOCSP()) {
7523 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7524 return;
7527 SpawnedTestServer::SSLOptions ssl_options(
7528 SpawnedTestServer::SSLOptions::CERT_AUTO);
7529 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7530 SSLConfigService::SetCRLSet(
7531 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7532 false, &kOCSPTestCertSPKI, "")));
7534 CertStatus cert_status;
7535 DoConnection(ssl_options, &cert_status);
7537 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7538 // revocation check for EV.
7539 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7540 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7541 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7542 EXPECT_FALSE(
7543 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7546 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
7547 if (!SystemSupportsOCSP()) {
7548 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7549 return;
7552 SpawnedTestServer::SSLOptions ssl_options(
7553 SpawnedTestServer::SSLOptions::CERT_AUTO);
7554 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7555 SSLConfigService::SetCRLSet(
7556 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
7558 CertStatus cert_status = 0;
7559 DoConnection(ssl_options, &cert_status);
7561 // Even with a fresh CRLSet, we should still do online revocation checks when
7562 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7563 // test.
7564 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7565 cert_status & CERT_STATUS_ALL_ERRORS);
7567 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7568 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7569 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7572 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
7573 // Test that when EV verification is requested, but online revocation
7574 // checking is disabled, and the leaf certificate is not in fact EV, that
7575 // no revocation checking actually happens.
7576 if (!SystemSupportsOCSP()) {
7577 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7578 return;
7581 // Unmark the certificate's OID as EV, which should disable revocation
7582 // checking (as per the user preference)
7583 ev_test_policy_.reset();
7585 SpawnedTestServer::SSLOptions ssl_options(
7586 SpawnedTestServer::SSLOptions::CERT_AUTO);
7587 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7588 SSLConfigService::SetCRLSet(
7589 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7591 CertStatus cert_status;
7592 DoConnection(ssl_options, &cert_status);
7594 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7596 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7597 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7600 class HTTPSCRLSetTest : public HTTPSOCSPTest {
7601 protected:
7602 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7603 context->set_ssl_config_service(
7604 new TestSSLConfigService(false /* check for EV */,
7605 false /* online revocation checking */,
7606 false /* require rev. checking for local
7607 anchors */));
7611 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
7612 SpawnedTestServer::SSLOptions ssl_options(
7613 SpawnedTestServer::SSLOptions::CERT_AUTO);
7614 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7615 SSLConfigService::SetCRLSet(
7616 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7618 CertStatus cert_status;
7619 DoConnection(ssl_options, &cert_status);
7621 // If we're not trying EV verification then, even if the CRLSet has expired,
7622 // we don't fall back to online revocation checks.
7623 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7624 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7625 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7628 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
7629 #if defined(USE_OPENSSL)
7630 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
7631 return;
7632 #endif
7634 SpawnedTestServer::SSLOptions ssl_options(
7635 SpawnedTestServer::SSLOptions::CERT_AUTO);
7636 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7637 ssl_options.cert_serial = 10;
7638 SSLConfigService::SetCRLSet(
7639 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7640 false, &kOCSPTestCertSPKI, "\x0a")));
7642 CertStatus cert_status = 0;
7643 DoConnection(ssl_options, &cert_status);
7645 // If the certificate is recorded as revoked in the CRLSet, that should be
7646 // reflected without online revocation checking.
7647 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7648 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7649 EXPECT_FALSE(
7650 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7652 #endif // !defined(OS_IOS)
7654 #if !defined(DISABLE_FTP_SUPPORT)
7655 class URLRequestTestFTP : public URLRequestTest {
7656 public:
7657 URLRequestTestFTP()
7658 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
7659 base::FilePath()) {
7662 protected:
7663 SpawnedTestServer test_server_;
7666 // Make sure an FTP request using an unsafe ports fails.
7667 TEST_F(URLRequestTestFTP, UnsafePort) {
7668 ASSERT_TRUE(test_server_.Start());
7670 URLRequestJobFactoryImpl job_factory;
7671 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
7673 GURL url("ftp://127.0.0.1:7");
7674 job_factory.SetProtocolHandler(
7675 "ftp",
7676 new FtpProtocolHandler(&ftp_transaction_factory));
7677 default_context_.set_job_factory(&job_factory);
7679 TestDelegate d;
7681 URLRequest r(url, DEFAULT_PRIORITY, &d, &default_context_);
7682 r.Start();
7683 EXPECT_TRUE(r.is_pending());
7685 base::RunLoop().Run();
7687 EXPECT_FALSE(r.is_pending());
7688 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
7689 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
7693 // Flaky, see http://crbug.com/25045.
7694 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
7695 ASSERT_TRUE(test_server_.Start());
7697 TestDelegate d;
7699 URLRequest r(
7700 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, &default_context_);
7701 r.Start();
7702 EXPECT_TRUE(r.is_pending());
7704 base::RunLoop().Run();
7706 EXPECT_FALSE(r.is_pending());
7707 EXPECT_EQ(1, d.response_started_count());
7708 EXPECT_FALSE(d.received_data_before_response());
7709 EXPECT_LT(0, d.bytes_received());
7710 EXPECT_EQ(test_server_.host_port_pair().host(),
7711 r.GetSocketAddress().host());
7712 EXPECT_EQ(test_server_.host_port_pair().port(),
7713 r.GetSocketAddress().port());
7717 // Flaky, see http://crbug.com/25045.
7718 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
7719 ASSERT_TRUE(test_server_.Start());
7721 base::FilePath app_path;
7722 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7723 app_path = app_path.AppendASCII("LICENSE");
7724 TestDelegate d;
7726 URLRequest r(test_server_.GetURL("/LICENSE"),
7727 DEFAULT_PRIORITY,
7729 &default_context_);
7730 r.Start();
7731 EXPECT_TRUE(r.is_pending());
7733 base::RunLoop().Run();
7735 int64 file_size = 0;
7736 base::GetFileSize(app_path, &file_size);
7738 EXPECT_FALSE(r.is_pending());
7739 EXPECT_EQ(1, d.response_started_count());
7740 EXPECT_FALSE(d.received_data_before_response());
7741 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7742 EXPECT_EQ(test_server_.host_port_pair().host(),
7743 r.GetSocketAddress().host());
7744 EXPECT_EQ(test_server_.host_port_pair().port(),
7745 r.GetSocketAddress().port());
7749 // Flaky, see http://crbug.com/25045.
7750 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
7751 ASSERT_TRUE(test_server_.Start());
7753 base::FilePath app_path;
7754 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7755 app_path = app_path.AppendASCII("LICENSE");
7756 TestDelegate d;
7758 URLRequest r(
7759 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7760 DEFAULT_PRIORITY,
7762 &default_context_);
7763 r.Start();
7764 EXPECT_TRUE(r.is_pending());
7766 base::RunLoop().Run();
7768 int64 file_size = 0;
7769 base::GetFileSize(app_path, &file_size);
7771 EXPECT_FALSE(r.is_pending());
7772 EXPECT_EQ(test_server_.host_port_pair().host(),
7773 r.GetSocketAddress().host());
7774 EXPECT_EQ(test_server_.host_port_pair().port(),
7775 r.GetSocketAddress().port());
7776 EXPECT_EQ(1, d.response_started_count());
7777 EXPECT_FALSE(d.received_data_before_response());
7778 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7780 LoadTimingInfo load_timing_info;
7781 r.GetLoadTimingInfo(&load_timing_info);
7782 TestLoadTimingNoHttpResponse(load_timing_info);
7786 // Flaky, see http://crbug.com/25045.
7787 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
7788 ASSERT_TRUE(test_server_.Start());
7790 base::FilePath app_path;
7791 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7792 app_path = app_path.AppendASCII("LICENSE");
7793 TestDelegate d;
7795 URLRequest r(test_server_.GetURLWithUserAndPassword(
7796 "/LICENSE", "chrome", "wrong_password"),
7797 DEFAULT_PRIORITY,
7799 &default_context_);
7800 r.Start();
7801 EXPECT_TRUE(r.is_pending());
7803 base::RunLoop().Run();
7805 int64 file_size = 0;
7806 base::GetFileSize(app_path, &file_size);
7808 EXPECT_FALSE(r.is_pending());
7809 EXPECT_EQ(1, d.response_started_count());
7810 EXPECT_FALSE(d.received_data_before_response());
7811 EXPECT_EQ(d.bytes_received(), 0);
7815 // Flaky, see http://crbug.com/25045.
7816 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
7817 ASSERT_TRUE(test_server_.Start());
7819 base::FilePath app_path;
7820 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7821 app_path = app_path.AppendASCII("LICENSE");
7822 TestDelegate d;
7823 // Set correct login credentials. The delegate will be asked for them when
7824 // the initial login with wrong credentials will fail.
7825 d.set_credentials(AuthCredentials(kChrome, kChrome));
7827 URLRequest r(test_server_.GetURLWithUserAndPassword(
7828 "/LICENSE", "chrome", "wrong_password"),
7829 DEFAULT_PRIORITY,
7831 &default_context_);
7832 r.Start();
7833 EXPECT_TRUE(r.is_pending());
7835 base::RunLoop().Run();
7837 int64 file_size = 0;
7838 base::GetFileSize(app_path, &file_size);
7840 EXPECT_FALSE(r.is_pending());
7841 EXPECT_EQ(1, d.response_started_count());
7842 EXPECT_FALSE(d.received_data_before_response());
7843 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7847 // Flaky, see http://crbug.com/25045.
7848 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
7849 ASSERT_TRUE(test_server_.Start());
7851 base::FilePath app_path;
7852 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7853 app_path = app_path.AppendASCII("LICENSE");
7854 TestDelegate d;
7856 URLRequest r(test_server_.GetURLWithUserAndPassword(
7857 "/LICENSE", "wrong_user", "chrome"),
7858 DEFAULT_PRIORITY,
7860 &default_context_);
7861 r.Start();
7862 EXPECT_TRUE(r.is_pending());
7864 base::RunLoop().Run();
7866 int64 file_size = 0;
7867 base::GetFileSize(app_path, &file_size);
7869 EXPECT_FALSE(r.is_pending());
7870 EXPECT_EQ(1, d.response_started_count());
7871 EXPECT_FALSE(d.received_data_before_response());
7872 EXPECT_EQ(d.bytes_received(), 0);
7876 // Flaky, see http://crbug.com/25045.
7877 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
7878 ASSERT_TRUE(test_server_.Start());
7880 base::FilePath app_path;
7881 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7882 app_path = app_path.AppendASCII("LICENSE");
7883 TestDelegate d;
7884 // Set correct login credentials. The delegate will be asked for them when
7885 // the initial login with wrong credentials will fail.
7886 d.set_credentials(AuthCredentials(kChrome, kChrome));
7888 URLRequest r(test_server_.GetURLWithUserAndPassword(
7889 "/LICENSE", "wrong_user", "chrome"),
7890 DEFAULT_PRIORITY,
7892 &default_context_);
7893 r.Start();
7894 EXPECT_TRUE(r.is_pending());
7896 base::RunLoop().Run();
7898 int64 file_size = 0;
7899 base::GetFileSize(app_path, &file_size);
7901 EXPECT_FALSE(r.is_pending());
7902 EXPECT_EQ(1, d.response_started_count());
7903 EXPECT_FALSE(d.received_data_before_response());
7904 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7908 // Flaky, see http://crbug.com/25045.
7909 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
7910 ASSERT_TRUE(test_server_.Start());
7912 base::FilePath app_path;
7913 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7914 app_path = app_path.AppendASCII("LICENSE");
7916 scoped_ptr<TestDelegate> d(new TestDelegate);
7918 // Pass correct login identity in the URL.
7919 URLRequest r(
7920 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7921 DEFAULT_PRIORITY,
7922 d.get(),
7923 &default_context_);
7924 r.Start();
7925 EXPECT_TRUE(r.is_pending());
7927 base::RunLoop().Run();
7929 int64 file_size = 0;
7930 base::GetFileSize(app_path, &file_size);
7932 EXPECT_FALSE(r.is_pending());
7933 EXPECT_EQ(1, d->response_started_count());
7934 EXPECT_FALSE(d->received_data_before_response());
7935 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7938 d.reset(new TestDelegate);
7940 // This request should use cached identity from previous request.
7941 URLRequest r(test_server_.GetURL("/LICENSE"),
7942 DEFAULT_PRIORITY,
7943 d.get(),
7944 &default_context_);
7945 r.Start();
7946 EXPECT_TRUE(r.is_pending());
7948 base::RunLoop().Run();
7950 int64 file_size = 0;
7951 base::GetFileSize(app_path, &file_size);
7953 EXPECT_FALSE(r.is_pending());
7954 EXPECT_EQ(1, d->response_started_count());
7955 EXPECT_FALSE(d->received_data_before_response());
7956 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7960 // Flaky, see http://crbug.com/25045.
7961 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
7962 ASSERT_TRUE(test_server_.Start());
7964 base::FilePath app_path;
7965 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7966 app_path = app_path.AppendASCII("LICENSE");
7968 scoped_ptr<TestDelegate> d(new TestDelegate);
7969 // Set correct login credentials. The delegate will be asked for them when
7970 // the initial login with wrong credentials will fail.
7971 d->set_credentials(AuthCredentials(kChrome, kChrome));
7973 URLRequest r(test_server_.GetURLWithUserAndPassword(
7974 "/LICENSE", "chrome", "wrong_password"),
7975 DEFAULT_PRIORITY,
7976 d.get(),
7977 &default_context_);
7978 r.Start();
7979 EXPECT_TRUE(r.is_pending());
7981 base::RunLoop().Run();
7983 int64 file_size = 0;
7984 base::GetFileSize(app_path, &file_size);
7986 EXPECT_FALSE(r.is_pending());
7987 EXPECT_EQ(1, d->response_started_count());
7988 EXPECT_FALSE(d->received_data_before_response());
7989 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7992 // Use a new delegate without explicit credentials. The cached ones should be
7993 // used.
7994 d.reset(new TestDelegate);
7996 // Don't pass wrong credentials in the URL, they would override valid cached
7997 // ones.
7998 URLRequest r(test_server_.GetURL("/LICENSE"),
7999 DEFAULT_PRIORITY,
8000 d.get(),
8001 &default_context_);
8002 r.Start();
8003 EXPECT_TRUE(r.is_pending());
8005 base::RunLoop().Run();
8007 int64 file_size = 0;
8008 base::GetFileSize(app_path, &file_size);
8010 EXPECT_FALSE(r.is_pending());
8011 EXPECT_EQ(1, d->response_started_count());
8012 EXPECT_FALSE(d->received_data_before_response());
8013 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8016 #endif // !defined(DISABLE_FTP_SUPPORT)
8018 } // namespace net