1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "build/build_config.h"
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/files/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/format_macros.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/memory/weak_ptr.h"
23 #include "base/message_loop/message_loop.h"
24 #include "base/message_loop/message_loop_proxy.h"
25 #include "base/path_service.h"
26 #include "base/run_loop.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/stringprintf.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "net/base/capturing_net_log.h"
34 #include "net/base/chunked_upload_data_stream.h"
35 #include "net/base/elements_upload_data_stream.h"
36 #include "net/base/load_flags.h"
37 #include "net/base/load_timing_info.h"
38 #include "net/base/load_timing_info_test_util.h"
39 #include "net/base/net_errors.h"
40 #include "net/base/net_log.h"
41 #include "net/base/net_log_unittest.h"
42 #include "net/base/net_module.h"
43 #include "net/base/net_util.h"
44 #include "net/base/request_priority.h"
45 #include "net/base/test_data_directory.h"
46 #include "net/base/upload_bytes_element_reader.h"
47 #include "net/base/upload_data_stream.h"
48 #include "net/base/upload_file_element_reader.h"
49 #include "net/cert/ev_root_ca_metadata.h"
50 #include "net/cert/mock_cert_verifier.h"
51 #include "net/cert/test_root_certs.h"
52 #include "net/cookies/cookie_monster.h"
53 #include "net/cookies/cookie_store_test_helpers.h"
54 #include "net/disk_cache/disk_cache.h"
55 #include "net/dns/mock_host_resolver.h"
56 #include "net/ftp/ftp_network_layer.h"
57 #include "net/http/http_byte_range.h"
58 #include "net/http/http_cache.h"
59 #include "net/http/http_network_layer.h"
60 #include "net/http/http_network_session.h"
61 #include "net/http/http_request_headers.h"
62 #include "net/http/http_response_headers.h"
63 #include "net/http/http_util.h"
64 #include "net/ocsp/nss_ocsp.h"
65 #include "net/proxy/proxy_service.h"
66 #include "net/socket/ssl_client_socket.h"
67 #include "net/ssl/ssl_cipher_suite_names.h"
68 #include "net/ssl/ssl_connection_status_flags.h"
69 #include "net/test/cert_test_util.h"
70 #include "net/test/spawned_test_server/spawned_test_server.h"
71 #include "net/url_request/data_protocol_handler.h"
72 #include "net/url_request/static_http_user_agent_settings.h"
73 #include "net/url_request/url_request.h"
74 #include "net/url_request/url_request_http_job.h"
75 #include "net/url_request/url_request_intercepting_job_factory.h"
76 #include "net/url_request/url_request_interceptor.h"
77 #include "net/url_request/url_request_job_factory_impl.h"
78 #include "net/url_request/url_request_redirect_job.h"
79 #include "net/url_request/url_request_test_job.h"
80 #include "net/url_request/url_request_test_util.h"
81 #include "testing/gtest/include/gtest/gtest.h"
82 #include "testing/platform_test.h"
84 #if !defined(DISABLE_FILE_SUPPORT)
85 #include "net/base/filename_util.h"
86 #include "net/url_request/file_protocol_handler.h"
87 #include "net/url_request/url_request_file_dir_job.h"
90 #if !defined(DISABLE_FTP_SUPPORT)
91 #include "net/url_request/ftp_protocol_handler.h"
95 #include "base/win/scoped_com_initializer.h"
96 #include "base/win/scoped_comptr.h"
97 #include "base/win/windows_version.h"
100 using base::ASCIIToUTF16;
107 const base::string16 kChrome(ASCIIToUTF16("chrome"));
108 const base::string16 kSecret(ASCIIToUTF16("secret"));
109 const base::string16 kUser(ASCIIToUTF16("user"));
111 // Tests load timing information in the case a fresh connection was used, with
113 void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
114 int connect_timing_flags) {
115 EXPECT_FALSE(load_timing_info.socket_reused);
116 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
118 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
119 EXPECT_FALSE(load_timing_info.request_start.is_null());
121 EXPECT_LE(load_timing_info.request_start,
122 load_timing_info.connect_timing.connect_start);
123 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
124 connect_timing_flags);
125 EXPECT_LE(load_timing_info.connect_timing.connect_end,
126 load_timing_info.send_start);
127 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
128 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
130 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
131 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
134 // Same as above, but with proxy times.
135 void TestLoadTimingNotReusedWithProxy(
136 const LoadTimingInfo& load_timing_info,
137 int connect_timing_flags) {
138 EXPECT_FALSE(load_timing_info.socket_reused);
139 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
141 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
142 EXPECT_FALSE(load_timing_info.request_start.is_null());
144 EXPECT_LE(load_timing_info.request_start,
145 load_timing_info.proxy_resolve_start);
146 EXPECT_LE(load_timing_info.proxy_resolve_start,
147 load_timing_info.proxy_resolve_end);
148 EXPECT_LE(load_timing_info.proxy_resolve_end,
149 load_timing_info.connect_timing.connect_start);
150 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
151 connect_timing_flags);
152 EXPECT_LE(load_timing_info.connect_timing.connect_end,
153 load_timing_info.send_start);
154 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
155 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
158 // Same as above, but with a reused socket and proxy times.
159 void TestLoadTimingReusedWithProxy(
160 const LoadTimingInfo& load_timing_info) {
161 EXPECT_TRUE(load_timing_info.socket_reused);
162 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
164 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
165 EXPECT_FALSE(load_timing_info.request_start.is_null());
167 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
169 EXPECT_LE(load_timing_info.request_start,
170 load_timing_info.proxy_resolve_start);
171 EXPECT_LE(load_timing_info.proxy_resolve_start,
172 load_timing_info.proxy_resolve_end);
173 EXPECT_LE(load_timing_info.proxy_resolve_end,
174 load_timing_info.send_start);
175 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
176 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
179 // Tests load timing information in the case of a cache hit, when no cache
180 // validation request was sent over the wire.
181 base::StringPiece TestNetResourceProvider(int key) {
185 void FillBuffer(char* buffer, size_t len) {
186 static bool called = false;
189 int seed = static_cast<int>(Time::Now().ToInternalValue());
193 for (size_t i = 0; i < len; i++) {
194 buffer[i] = static_cast<char>(rand());
201 void TestLoadTimingCacheHitNoNetwork(
202 const LoadTimingInfo& load_timing_info) {
203 EXPECT_FALSE(load_timing_info.socket_reused);
204 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
206 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
207 EXPECT_FALSE(load_timing_info.request_start.is_null());
209 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
210 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
211 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
212 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
214 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
215 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
218 // Tests load timing in the case that there is no HTTP response. This can be
219 // used to test in the case of errors or non-HTTP requests.
220 void TestLoadTimingNoHttpResponse(
221 const LoadTimingInfo& load_timing_info) {
222 EXPECT_FALSE(load_timing_info.socket_reused);
223 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
225 // Only the request times should be non-null.
226 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
227 EXPECT_FALSE(load_timing_info.request_start.is_null());
229 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
231 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
232 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
233 EXPECT_TRUE(load_timing_info.send_start.is_null());
234 EXPECT_TRUE(load_timing_info.send_end.is_null());
235 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
238 // Do a case-insensitive search through |haystack| for |needle|.
239 bool ContainsString(const std::string& haystack, const char* needle) {
240 std::string::const_iterator it =
241 std::search(haystack.begin(),
244 needle + strlen(needle),
245 base::CaseInsensitiveCompare<char>());
246 return it != haystack.end();
249 scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
250 scoped_ptr<UploadElementReader> reader(
251 new UploadBytesElementReader(data, strlen(data)));
252 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
255 // Verify that the SSLInfo of a successful SSL connection has valid values.
256 void CheckSSLInfo(const SSLInfo& ssl_info) {
257 // -1 means unknown. 0 means no encryption.
258 EXPECT_GT(ssl_info.security_bits, 0);
260 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
261 int cipher_suite = SSLConnectionStatusToCipherSuite(
262 ssl_info.connection_status);
263 EXPECT_NE(0, cipher_suite);
266 void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
267 const GURL& host_url) {
268 std::string sent_value;
270 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
271 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
273 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
274 EXPECT_EQ("keep-alive", sent_value);
277 bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
278 size_t size = a.size();
280 if (size != b.size())
283 for (size_t i = 0; i < size; ++i) {
284 if (!a[i].Equals(b[i]))
290 #endif // !defined(OS_IOS)
292 // A network delegate that allows the user to choose a subset of request stages
293 // to block in. When blocking, the delegate can do one of the following:
294 // * synchronously return a pre-specified error code, or
295 // * asynchronously return that value via an automatically called callback,
297 // * block and wait for the user to do a callback.
298 // Additionally, the user may also specify a redirect URL -- then each request
299 // with the current URL different from the redirect target will be redirected
300 // to that target, in the on-before-URL-request stage, independent of whether
301 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
302 class BlockingNetworkDelegate : public TestNetworkDelegate {
304 // Stages in which the delegate can block.
307 ON_BEFORE_URL_REQUEST = 1 << 0,
308 ON_BEFORE_SEND_HEADERS = 1 << 1,
309 ON_HEADERS_RECEIVED = 1 << 2,
310 ON_AUTH_REQUIRED = 1 << 3
313 // Behavior during blocked stages. During other stages, just
314 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
316 SYNCHRONOUS, // No callback, returns specified return values.
317 AUTO_CALLBACK, // |this| posts a task to run the callback using the
318 // specified return codes.
319 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
320 // |auth_retval_| are ignored. In every blocking stage the
321 // message loop is quit.
324 // Creates a delegate which does not block at all.
325 explicit BlockingNetworkDelegate(BlockMode block_mode);
327 // For users to trigger a callback returning |response|.
328 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
329 // Only call if |block_mode_| == USER_CALLBACK.
330 void DoCallback(int response);
331 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
334 void set_retval(int retval) {
335 ASSERT_NE(USER_CALLBACK, block_mode_);
336 ASSERT_NE(ERR_IO_PENDING, retval);
337 ASSERT_NE(OK, retval);
341 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
342 // |auth_credentials_| will be passed with the response.
343 void set_auth_retval(AuthRequiredResponse auth_retval) {
344 ASSERT_NE(USER_CALLBACK, block_mode_);
345 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
346 auth_retval_ = auth_retval;
348 void set_auth_credentials(const AuthCredentials& auth_credentials) {
349 auth_credentials_ = auth_credentials;
352 void set_redirect_url(const GURL& url) {
356 void set_block_on(int block_on) {
357 block_on_ = block_on;
360 // Allows the user to check in which state did we block.
361 Stage stage_blocked_for_callback() const {
362 EXPECT_EQ(USER_CALLBACK, block_mode_);
363 return stage_blocked_for_callback_;
367 void RunCallback(int response, const CompletionCallback& callback);
368 void RunAuthCallback(AuthRequiredResponse response,
369 const AuthCallback& callback);
371 // TestNetworkDelegate implementation.
372 int OnBeforeURLRequest(URLRequest* request,
373 const CompletionCallback& callback,
374 GURL* new_url) override;
376 int OnBeforeSendHeaders(URLRequest* request,
377 const CompletionCallback& callback,
378 HttpRequestHeaders* headers) override;
380 int OnHeadersReceived(
382 const CompletionCallback& callback,
383 const HttpResponseHeaders* original_response_headers,
384 scoped_refptr<HttpResponseHeaders>* override_response_headers,
385 GURL* allowed_unsafe_redirect_url) override;
387 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
389 const AuthChallengeInfo& auth_info,
390 const AuthCallback& callback,
391 AuthCredentials* credentials) override;
393 // Resets the callbacks and |stage_blocked_for_callback_|.
396 // Checks whether we should block in |stage|. If yes, returns an error code
397 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
398 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
400 // Configuration parameters, can be adjusted by public methods:
401 const BlockMode block_mode_;
403 // Values returned on blocking stages when mode is SYNCHRONOUS or
404 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
405 int retval_; // To be returned in non-auth stages.
406 AuthRequiredResponse auth_retval_;
408 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
409 int block_on_; // Bit mask: in which stages to block.
411 // |auth_credentials_| will be copied to |*target_auth_credential_| on
413 AuthCredentials auth_credentials_;
414 AuthCredentials* target_auth_credentials_;
416 // Internal variables, not set by not the user:
417 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
419 Stage stage_blocked_for_callback_;
421 // Callback objects stored during blocking stages.
422 CompletionCallback callback_;
423 AuthCallback auth_callback_;
425 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
427 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
430 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
431 : block_mode_(block_mode),
433 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
435 target_auth_credentials_(NULL),
436 stage_blocked_for_callback_(NOT_BLOCKED),
437 weak_factory_(this) {
440 void BlockingNetworkDelegate::DoCallback(int response) {
441 ASSERT_EQ(USER_CALLBACK, block_mode_);
442 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
443 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
444 CompletionCallback callback = callback_;
446 RunCallback(response, callback);
449 void BlockingNetworkDelegate::DoAuthCallback(
450 NetworkDelegate::AuthRequiredResponse response) {
451 ASSERT_EQ(USER_CALLBACK, block_mode_);
452 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
453 AuthCallback auth_callback = auth_callback_;
455 RunAuthCallback(response, auth_callback);
458 void BlockingNetworkDelegate::RunCallback(int response,
459 const CompletionCallback& callback) {
460 callback.Run(response);
463 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
464 const AuthCallback& callback) {
465 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
466 ASSERT_TRUE(target_auth_credentials_ != NULL);
467 *target_auth_credentials_ = auth_credentials_;
469 callback.Run(response);
472 int BlockingNetworkDelegate::OnBeforeURLRequest(
474 const CompletionCallback& callback,
476 if (redirect_url_ == request->url())
477 return OK; // We've already seen this request and redirected elsewhere.
479 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
481 if (!redirect_url_.is_empty())
482 *new_url = redirect_url_;
484 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
487 int BlockingNetworkDelegate::OnBeforeSendHeaders(
489 const CompletionCallback& callback,
490 HttpRequestHeaders* headers) {
491 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
493 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
496 int BlockingNetworkDelegate::OnHeadersReceived(
498 const CompletionCallback& callback,
499 const HttpResponseHeaders* original_response_headers,
500 scoped_refptr<HttpResponseHeaders>* override_response_headers,
501 GURL* allowed_unsafe_redirect_url) {
502 TestNetworkDelegate::OnHeadersReceived(request,
504 original_response_headers,
505 override_response_headers,
506 allowed_unsafe_redirect_url);
508 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
511 NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
513 const AuthChallengeInfo& auth_info,
514 const AuthCallback& callback,
515 AuthCredentials* credentials) {
516 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
518 // Check that the user has provided callback for the previous blocked stage.
519 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
521 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
522 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
525 target_auth_credentials_ = credentials;
527 switch (block_mode_) {
529 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
530 *target_auth_credentials_ = auth_credentials_;
534 base::MessageLoop::current()->PostTask(
536 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
537 weak_factory_.GetWeakPtr(), auth_retval_, callback));
538 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
541 auth_callback_ = callback;
542 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
543 base::MessageLoop::current()->PostTask(FROM_HERE,
544 base::MessageLoop::QuitClosure());
545 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
548 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
551 void BlockingNetworkDelegate::Reset() {
552 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
553 stage_blocked_for_callback_ = NOT_BLOCKED;
555 auth_callback_.Reset();
558 int BlockingNetworkDelegate::MaybeBlockStage(
559 BlockingNetworkDelegate::Stage stage,
560 const CompletionCallback& callback) {
561 // Check that the user has provided callback for the previous blocked stage.
562 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
564 if ((block_on_ & stage) == 0) {
568 switch (block_mode_) {
570 EXPECT_NE(OK, retval_);
574 base::MessageLoop::current()->PostTask(
576 base::Bind(&BlockingNetworkDelegate::RunCallback,
577 weak_factory_.GetWeakPtr(), retval_, callback));
578 return ERR_IO_PENDING;
581 callback_ = callback;
582 stage_blocked_for_callback_ = stage;
583 base::MessageLoop::current()->PostTask(FROM_HERE,
584 base::MessageLoop::QuitClosure());
585 return ERR_IO_PENDING;
591 class TestURLRequestContextWithProxy : public TestURLRequestContext {
593 // Does not own |delegate|.
594 TestURLRequestContextWithProxy(const std::string& proxy,
595 NetworkDelegate* delegate)
596 : TestURLRequestContext(true) {
597 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
598 set_network_delegate(delegate);
601 ~TestURLRequestContextWithProxy() override {}
606 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
607 class URLRequestTest : public PlatformTest {
609 URLRequestTest() : default_context_(true) {
610 default_context_.set_network_delegate(&default_network_delegate_);
611 default_context_.set_net_log(&net_log_);
612 job_factory_impl_ = new URLRequestJobFactoryImpl();
613 job_factory_.reset(job_factory_impl_);
616 ~URLRequestTest() override {
617 // URLRequestJobs may post clean-up tasks on destruction.
618 base::RunLoop().RunUntilIdle();
621 virtual void SetUp() {
623 default_context_.set_job_factory(job_factory_.get());
624 default_context_.Init();
625 PlatformTest::SetUp();
628 virtual void SetUpFactory() {
629 job_factory_impl_->SetProtocolHandler("data", new DataProtocolHandler);
630 #if !defined(DISABLE_FILE_SUPPORT)
631 job_factory_impl_->SetProtocolHandler(
632 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
636 TestNetworkDelegate* default_network_delegate() {
637 return &default_network_delegate_;
640 const TestURLRequestContext& default_context() const {
641 return default_context_;
645 // Adds the TestJobInterceptor to the default context.
646 TestJobInterceptor* AddTestInterceptor() {
647 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
648 job_factory_impl_->SetProtocolHandler("http", NULL);
649 job_factory_impl_->SetProtocolHandler("http", protocol_handler_);
650 return protocol_handler_;
654 CapturingNetLog net_log_;
655 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
656 URLRequestJobFactoryImpl* job_factory_impl_;
657 scoped_ptr<URLRequestJobFactory> job_factory_;
658 TestURLRequestContext default_context_;
661 TEST_F(URLRequestTest, AboutBlankTest) {
664 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
665 GURL("about:blank"), DEFAULT_PRIORITY, &d, NULL));
668 EXPECT_TRUE(r->is_pending());
670 base::RunLoop().Run();
672 EXPECT_TRUE(!r->is_pending());
673 EXPECT_FALSE(d.received_data_before_response());
674 EXPECT_EQ(d.bytes_received(), 0);
675 EXPECT_EQ("", r->GetSocketAddress().host());
676 EXPECT_EQ(0, r->GetSocketAddress().port());
678 HttpRequestHeaders headers;
679 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
683 TEST_F(URLRequestTest, DataURLImageTest) {
686 // Use our nice little Chrome logo.
687 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
689 "data:image/png;base64,"
690 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
691 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
692 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
693 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
694 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
695 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
696 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
697 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
698 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
699 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
700 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
701 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
702 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
703 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
704 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
705 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
706 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
707 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
708 DEFAULT_PRIORITY, &d, NULL));
711 EXPECT_TRUE(r->is_pending());
713 base::RunLoop().Run();
715 EXPECT_TRUE(!r->is_pending());
716 EXPECT_FALSE(d.received_data_before_response());
717 EXPECT_EQ(d.bytes_received(), 911);
718 EXPECT_EQ("", r->GetSocketAddress().host());
719 EXPECT_EQ(0, r->GetSocketAddress().port());
721 HttpRequestHeaders headers;
722 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
726 #if !defined(DISABLE_FILE_SUPPORT)
727 TEST_F(URLRequestTest, FileTest) {
728 base::FilePath app_path;
729 PathService::Get(base::FILE_EXE, &app_path);
730 GURL app_url = FilePathToFileURL(app_path);
734 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
735 app_url, DEFAULT_PRIORITY, &d, NULL));
738 EXPECT_TRUE(r->is_pending());
740 base::RunLoop().Run();
742 int64 file_size = -1;
743 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
745 EXPECT_TRUE(!r->is_pending());
746 EXPECT_EQ(1, d.response_started_count());
747 EXPECT_FALSE(d.received_data_before_response());
748 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
749 EXPECT_EQ("", r->GetSocketAddress().host());
750 EXPECT_EQ(0, r->GetSocketAddress().port());
752 HttpRequestHeaders headers;
753 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
757 TEST_F(URLRequestTest, FileTestCancel) {
758 base::FilePath app_path;
759 PathService::Get(base::FILE_EXE, &app_path);
760 GURL app_url = FilePathToFileURL(app_path);
764 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
765 app_url, DEFAULT_PRIORITY, &d, NULL));
768 EXPECT_TRUE(r->is_pending());
771 // Async cancellation should be safe even when URLRequest has been already
773 base::RunLoop().RunUntilIdle();
776 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
777 const size_t buffer_size = 4000;
778 scoped_ptr<char[]> buffer(new char[buffer_size]);
779 FillBuffer(buffer.get(), buffer_size);
781 base::FilePath temp_path;
782 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
783 GURL temp_url = FilePathToFileURL(temp_path);
784 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
787 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
789 const size_t first_byte_position = 500;
790 const size_t last_byte_position = buffer_size - first_byte_position;
791 const size_t content_length = last_byte_position - first_byte_position + 1;
792 std::string partial_buffer_string(buffer.get() + first_byte_position,
793 buffer.get() + last_byte_position + 1);
797 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
798 temp_url, DEFAULT_PRIORITY, &d, NULL));
800 HttpRequestHeaders headers;
802 HttpRequestHeaders::kRange,
803 HttpByteRange::Bounded(
804 first_byte_position, last_byte_position).GetHeaderValue());
805 r->SetExtraRequestHeaders(headers);
807 EXPECT_TRUE(r->is_pending());
809 base::RunLoop().Run();
810 EXPECT_TRUE(!r->is_pending());
811 EXPECT_EQ(1, d.response_started_count());
812 EXPECT_FALSE(d.received_data_before_response());
813 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
814 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
815 EXPECT_TRUE(partial_buffer_string == d.data_received());
818 EXPECT_TRUE(base::DeleteFile(temp_path, false));
821 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
822 const size_t buffer_size = 4000;
823 scoped_ptr<char[]> buffer(new char[buffer_size]);
824 FillBuffer(buffer.get(), buffer_size);
826 base::FilePath temp_path;
827 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
828 GURL temp_url = FilePathToFileURL(temp_path);
829 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
832 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
834 const size_t first_byte_position = 500;
835 const size_t last_byte_position = buffer_size - 1;
836 const size_t content_length = last_byte_position - first_byte_position + 1;
837 std::string partial_buffer_string(buffer.get() + first_byte_position,
838 buffer.get() + last_byte_position + 1);
842 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
843 temp_url, DEFAULT_PRIORITY, &d, NULL));
845 HttpRequestHeaders headers;
846 headers.SetHeader(HttpRequestHeaders::kRange,
847 HttpByteRange::RightUnbounded(
848 first_byte_position).GetHeaderValue());
849 r->SetExtraRequestHeaders(headers);
851 EXPECT_TRUE(r->is_pending());
853 base::RunLoop().Run();
854 EXPECT_TRUE(!r->is_pending());
855 EXPECT_EQ(1, d.response_started_count());
856 EXPECT_FALSE(d.received_data_before_response());
857 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
858 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
859 EXPECT_TRUE(partial_buffer_string == d.data_received());
862 EXPECT_TRUE(base::DeleteFile(temp_path, false));
865 TEST_F(URLRequestTest, FileTestMultipleRanges) {
866 const size_t buffer_size = 400000;
867 scoped_ptr<char[]> buffer(new char[buffer_size]);
868 FillBuffer(buffer.get(), buffer_size);
870 base::FilePath temp_path;
871 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
872 GURL temp_url = FilePathToFileURL(temp_path);
873 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
876 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
880 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
881 temp_url, DEFAULT_PRIORITY, &d, NULL));
883 HttpRequestHeaders headers;
884 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
885 r->SetExtraRequestHeaders(headers);
887 EXPECT_TRUE(r->is_pending());
889 base::RunLoop().Run();
890 EXPECT_TRUE(d.request_failed());
893 EXPECT_TRUE(base::DeleteFile(temp_path, false));
896 TEST_F(URLRequestTest, AllowFileURLs) {
897 base::ScopedTempDir temp_dir;
898 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
899 base::FilePath test_file;
900 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
901 std::string test_data("monkey");
902 base::WriteFile(test_file, test_data.data(), test_data.size());
903 GURL test_file_url = FilePathToFileURL(test_file);
907 TestNetworkDelegate network_delegate;
908 network_delegate.set_can_access_files(true);
909 default_context_.set_network_delegate(&network_delegate);
910 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
911 test_file_url, DEFAULT_PRIORITY, &d, NULL));
913 base::RunLoop().Run();
914 EXPECT_FALSE(d.request_failed());
915 EXPECT_EQ(test_data, d.data_received());
920 TestNetworkDelegate network_delegate;
921 network_delegate.set_can_access_files(false);
922 default_context_.set_network_delegate(&network_delegate);
923 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
924 test_file_url, DEFAULT_PRIORITY, &d, NULL));
926 base::RunLoop().Run();
927 EXPECT_TRUE(d.request_failed());
928 EXPECT_EQ("", d.data_received());
933 TEST_F(URLRequestTest, FileDirCancelTest) {
934 // Put in mock resource provider.
935 NetModule::SetResourceProvider(TestNetResourceProvider);
939 base::FilePath file_path;
940 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
941 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
942 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
944 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
945 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, NULL));
947 EXPECT_TRUE(req->is_pending());
949 d.set_cancel_in_received_data_pending(true);
951 base::RunLoop().Run();
954 // Take out mock resource provider.
955 NetModule::SetResourceProvider(NULL);
958 TEST_F(URLRequestTest, FileDirOutputSanity) {
959 // Verify the general sanity of the the output of the file:
960 // directory lister by checking for the output of a known existing
962 const char sentinel_name[] = "filedir-sentinel";
965 PathService::Get(base::DIR_SOURCE_ROOT, &path);
966 path = path.Append(FILE_PATH_LITERAL("net"));
967 path = path.Append(FILE_PATH_LITERAL("data"));
968 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
971 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
972 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
974 base::RunLoop().Run();
976 // Generate entry for the sentinel file.
977 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
978 base::File::Info info;
979 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
980 EXPECT_GT(info.size, 0);
981 std::string sentinel_output = GetDirectoryListingEntry(
982 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
983 std::string(sentinel_name),
988 ASSERT_LT(0, d.bytes_received());
989 ASSERT_FALSE(d.request_failed());
990 ASSERT_TRUE(req->status().is_success());
991 // Check for the entry generated for the "sentinel" file.
992 const std::string& data = d.data_received();
993 ASSERT_NE(data.find(sentinel_output), std::string::npos);
996 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
997 // There is an implicit redirect when loading a file path that matches a
998 // directory and does not end with a slash. Ensure that following such
999 // redirects does not crash. See http://crbug.com/18686.
1001 base::FilePath path;
1002 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1003 path = path.Append(FILE_PATH_LITERAL("net"));
1004 path = path.Append(FILE_PATH_LITERAL("data"));
1005 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1008 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1009 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
1011 base::RunLoop().Run();
1013 ASSERT_EQ(1, d.received_redirect_count());
1014 ASSERT_LT(0, d.bytes_received());
1015 ASSERT_FALSE(d.request_failed());
1016 ASSERT_TRUE(req->status().is_success());
1020 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1021 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1023 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1024 GURL("file:///"), DEFAULT_PRIORITY, &d, NULL));
1026 base::RunLoop().Run();
1028 ASSERT_EQ(1, d.received_redirect_count());
1029 ASSERT_FALSE(req->status().is_success());
1031 #endif // defined(OS_WIN)
1033 #endif // !defined(DISABLE_FILE_SUPPORT)
1035 TEST_F(URLRequestTest, InvalidUrlTest) {
1038 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1039 GURL("invalid url"), DEFAULT_PRIORITY, &d, NULL));
1042 EXPECT_TRUE(r->is_pending());
1044 base::RunLoop().Run();
1045 EXPECT_TRUE(d.request_failed());
1049 TEST_F(URLRequestTest, InvalidReferrerTest) {
1050 TestURLRequestContext context;
1051 TestNetworkDelegate network_delegate;
1052 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1053 context.set_network_delegate(&network_delegate);
1055 scoped_ptr<URLRequest> req(context.CreateRequest(
1056 GURL("http://localhost/"), DEFAULT_PRIORITY, &d, NULL));
1057 req->SetReferrer("https://somewhere.com/");
1060 base::RunLoop().Run();
1061 EXPECT_TRUE(d.request_failed());
1065 TEST_F(URLRequestTest, ResolveShortcutTest) {
1066 base::FilePath app_path;
1067 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1068 app_path = app_path.AppendASCII("net");
1069 app_path = app_path.AppendASCII("data");
1070 app_path = app_path.AppendASCII("url_request_unittest");
1071 app_path = app_path.AppendASCII("with-headers.html");
1073 std::wstring lnk_path = app_path.value() + L".lnk";
1075 base::win::ScopedCOMInitializer com_initializer;
1077 // Temporarily create a shortcut for test
1079 base::win::ScopedComPtr<IShellLink> shell;
1080 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1081 CLSCTX_INPROC_SERVER)));
1082 base::win::ScopedComPtr<IPersistFile> persist;
1083 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1084 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1085 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1086 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1091 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1092 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1096 EXPECT_TRUE(r->is_pending());
1098 base::RunLoop().Run();
1100 WIN32_FILE_ATTRIBUTE_DATA data;
1101 GetFileAttributesEx(app_path.value().c_str(),
1102 GetFileExInfoStandard, &data);
1103 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1104 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1105 FILE_ATTRIBUTE_NORMAL, NULL);
1106 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1107 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1110 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1112 std::string content(buffer.get(), read_size);
1115 EXPECT_TRUE(!r->is_pending());
1116 EXPECT_EQ(1, d.received_redirect_count());
1117 EXPECT_EQ(content, d.data_received());
1120 // Clean the shortcut
1121 DeleteFile(lnk_path.c_str());
1123 #endif // defined(OS_WIN)
1125 // Custom URLRequestJobs for use with interceptor tests
1126 class RestartTestJob : public URLRequestTestJob {
1128 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1129 : URLRequestTestJob(request, network_delegate, true) {}
1131 void StartAsync() override { this->NotifyRestartRequired(); }
1133 ~RestartTestJob() override {}
1136 class CancelTestJob : public URLRequestTestJob {
1138 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1139 : URLRequestTestJob(request, network_delegate, true) {}
1141 void StartAsync() override { request_->Cancel(); }
1143 ~CancelTestJob() override {}
1146 class CancelThenRestartTestJob : public URLRequestTestJob {
1148 explicit CancelThenRestartTestJob(URLRequest* request,
1149 NetworkDelegate* network_delegate)
1150 : URLRequestTestJob(request, network_delegate, true) {
1153 void StartAsync() override {
1155 this->NotifyRestartRequired();
1158 ~CancelThenRestartTestJob() override {}
1161 // An Interceptor for use with interceptor tests
1162 class TestInterceptor : URLRequest::Interceptor {
1165 : intercept_main_request_(false), restart_main_request_(false),
1166 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1167 simulate_main_network_error_(false),
1168 intercept_redirect_(false), cancel_redirect_request_(false),
1169 intercept_final_response_(false), cancel_final_request_(false),
1170 did_intercept_main_(false), did_restart_main_(false),
1171 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1172 did_simulate_error_main_(false),
1173 did_intercept_redirect_(false), did_cancel_redirect_(false),
1174 did_intercept_final_(false), did_cancel_final_(false) {
1175 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1178 ~TestInterceptor() override {
1179 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1182 URLRequestJob* MaybeIntercept(URLRequest* request,
1183 NetworkDelegate* network_delegate) override {
1184 if (restart_main_request_) {
1185 restart_main_request_ = false;
1186 did_restart_main_ = true;
1187 return new RestartTestJob(request, network_delegate);
1189 if (cancel_main_request_) {
1190 cancel_main_request_ = false;
1191 did_cancel_main_ = true;
1192 return new CancelTestJob(request, network_delegate);
1194 if (cancel_then_restart_main_request_) {
1195 cancel_then_restart_main_request_ = false;
1196 did_cancel_then_restart_main_ = true;
1197 return new CancelThenRestartTestJob(request, network_delegate);
1199 if (simulate_main_network_error_) {
1200 simulate_main_network_error_ = false;
1201 did_simulate_error_main_ = true;
1202 // will error since the requeted url is not one of its canned urls
1203 return new URLRequestTestJob(request, network_delegate, true);
1205 if (!intercept_main_request_)
1207 intercept_main_request_ = false;
1208 did_intercept_main_ = true;
1209 URLRequestTestJob* job = new URLRequestTestJob(request,
1214 job->set_load_timing_info(main_request_load_timing_info_);
1218 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1219 NetworkDelegate* network_delegate,
1220 const GURL& location) override {
1221 if (cancel_redirect_request_) {
1222 cancel_redirect_request_ = false;
1223 did_cancel_redirect_ = true;
1224 return new CancelTestJob(request, network_delegate);
1226 if (!intercept_redirect_)
1228 intercept_redirect_ = false;
1229 did_intercept_redirect_ = true;
1230 return new URLRequestTestJob(request,
1237 URLRequestJob* MaybeInterceptResponse(
1238 URLRequest* request,
1239 NetworkDelegate* network_delegate) override {
1240 if (cancel_final_request_) {
1241 cancel_final_request_ = false;
1242 did_cancel_final_ = true;
1243 return new CancelTestJob(request, network_delegate);
1245 if (!intercept_final_response_)
1247 intercept_final_response_ = false;
1248 did_intercept_final_ = true;
1249 return new URLRequestTestJob(request,
1256 // Whether to intercept the main request, and if so the response to return and
1257 // the LoadTimingInfo to use.
1258 bool intercept_main_request_;
1259 std::string main_headers_;
1260 std::string main_data_;
1261 LoadTimingInfo main_request_load_timing_info_;
1263 // Other actions we take at MaybeIntercept time
1264 bool restart_main_request_;
1265 bool cancel_main_request_;
1266 bool cancel_then_restart_main_request_;
1267 bool simulate_main_network_error_;
1269 // Whether to intercept redirects, and if so the response to return.
1270 bool intercept_redirect_;
1271 std::string redirect_headers_;
1272 std::string redirect_data_;
1274 // Other actions we can take at MaybeInterceptRedirect time
1275 bool cancel_redirect_request_;
1277 // Whether to intercept final response, and if so the response to return.
1278 bool intercept_final_response_;
1279 std::string final_headers_;
1280 std::string final_data_;
1282 // Other actions we can take at MaybeInterceptResponse time
1283 bool cancel_final_request_;
1285 // If we did something or not
1286 bool did_intercept_main_;
1287 bool did_restart_main_;
1288 bool did_cancel_main_;
1289 bool did_cancel_then_restart_main_;
1290 bool did_simulate_error_main_;
1291 bool did_intercept_redirect_;
1292 bool did_cancel_redirect_;
1293 bool did_intercept_final_;
1294 bool did_cancel_final_;
1296 // Static getters for canned response header and data strings
1298 static std::string ok_data() {
1299 return URLRequestTestJob::test_data_1();
1302 static std::string ok_headers() {
1303 return URLRequestTestJob::test_headers();
1306 static std::string redirect_data() {
1307 return std::string();
1310 static std::string redirect_headers() {
1311 return URLRequestTestJob::test_redirect_headers();
1314 static std::string error_data() {
1315 return std::string("ohhh nooooo mr. bill!");
1318 static std::string error_headers() {
1319 return URLRequestTestJob::test_error_headers();
1323 TEST_F(URLRequestTest, Intercept) {
1324 TestInterceptor interceptor;
1326 // intercept the main request and respond with a simple response
1327 interceptor.intercept_main_request_ = true;
1328 interceptor.main_headers_ = TestInterceptor::ok_headers();
1329 interceptor.main_data_ = TestInterceptor::ok_data();
1332 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1333 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1334 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1335 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1336 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1337 req->SetUserData(NULL, user_data0);
1338 req->SetUserData(&user_data1, user_data1);
1339 req->SetUserData(&user_data2, user_data2);
1340 req->set_method("GET");
1342 base::RunLoop().Run();
1344 // Make sure we can retrieve our specific user data
1345 EXPECT_EQ(user_data0, req->GetUserData(NULL));
1346 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1347 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1349 // Check the interceptor got called as expected
1350 EXPECT_TRUE(interceptor.did_intercept_main_);
1352 // Check we got one good response
1353 EXPECT_TRUE(req->status().is_success());
1354 EXPECT_EQ(200, req->response_headers()->response_code());
1355 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1356 EXPECT_EQ(1, d.response_started_count());
1357 EXPECT_EQ(0, d.received_redirect_count());
1360 TEST_F(URLRequestTest, InterceptRedirect) {
1361 TestInterceptor interceptor;
1363 // intercept the main request and respond with a redirect
1364 interceptor.intercept_main_request_ = true;
1365 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1366 interceptor.main_data_ = TestInterceptor::redirect_data();
1368 // intercept that redirect and respond a final OK response
1369 interceptor.intercept_redirect_ = true;
1370 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1371 interceptor.redirect_data_ = TestInterceptor::ok_data();
1374 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1375 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1376 req->set_method("GET");
1378 base::RunLoop().Run();
1380 // Check the interceptor got called as expected
1381 EXPECT_TRUE(interceptor.did_intercept_main_);
1382 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1384 // Check we got one good response
1385 EXPECT_TRUE(req->status().is_success());
1386 if (req->status().is_success()) {
1387 EXPECT_EQ(200, req->response_headers()->response_code());
1389 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1390 EXPECT_EQ(1, d.response_started_count());
1391 EXPECT_EQ(0, d.received_redirect_count());
1394 TEST_F(URLRequestTest, InterceptServerError) {
1395 TestInterceptor interceptor;
1397 // intercept the main request to generate a server error response
1398 interceptor.intercept_main_request_ = true;
1399 interceptor.main_headers_ = TestInterceptor::error_headers();
1400 interceptor.main_data_ = TestInterceptor::error_data();
1402 // intercept that error and respond with an OK response
1403 interceptor.intercept_final_response_ = true;
1404 interceptor.final_headers_ = TestInterceptor::ok_headers();
1405 interceptor.final_data_ = TestInterceptor::ok_data();
1408 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1409 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1410 req->set_method("GET");
1412 base::RunLoop().Run();
1414 // Check the interceptor got called as expected
1415 EXPECT_TRUE(interceptor.did_intercept_main_);
1416 EXPECT_TRUE(interceptor.did_intercept_final_);
1418 // Check we got one good response
1419 EXPECT_TRUE(req->status().is_success());
1420 EXPECT_EQ(200, req->response_headers()->response_code());
1421 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1422 EXPECT_EQ(1, d.response_started_count());
1423 EXPECT_EQ(0, d.received_redirect_count());
1426 TEST_F(URLRequestTest, InterceptNetworkError) {
1427 TestInterceptor interceptor;
1429 // intercept the main request to simulate a network error
1430 interceptor.simulate_main_network_error_ = true;
1432 // intercept that error and respond with an OK response
1433 interceptor.intercept_final_response_ = true;
1434 interceptor.final_headers_ = TestInterceptor::ok_headers();
1435 interceptor.final_data_ = TestInterceptor::ok_data();
1438 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1439 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1440 req->set_method("GET");
1442 base::RunLoop().Run();
1444 // Check the interceptor got called as expected
1445 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1446 EXPECT_TRUE(interceptor.did_intercept_final_);
1448 // Check we received one good response
1449 EXPECT_TRUE(req->status().is_success());
1450 EXPECT_EQ(200, req->response_headers()->response_code());
1451 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1452 EXPECT_EQ(1, d.response_started_count());
1453 EXPECT_EQ(0, d.received_redirect_count());
1456 TEST_F(URLRequestTest, InterceptRestartRequired) {
1457 TestInterceptor interceptor;
1459 // restart the main request
1460 interceptor.restart_main_request_ = true;
1462 // then intercept the new main request and respond with an OK response
1463 interceptor.intercept_main_request_ = true;
1464 interceptor.main_headers_ = TestInterceptor::ok_headers();
1465 interceptor.main_data_ = TestInterceptor::ok_data();
1468 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1469 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1470 req->set_method("GET");
1472 base::RunLoop().Run();
1474 // Check the interceptor got called as expected
1475 EXPECT_TRUE(interceptor.did_restart_main_);
1476 EXPECT_TRUE(interceptor.did_intercept_main_);
1478 // Check we received one good response
1479 EXPECT_TRUE(req->status().is_success());
1480 if (req->status().is_success()) {
1481 EXPECT_EQ(200, req->response_headers()->response_code());
1483 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1484 EXPECT_EQ(1, d.response_started_count());
1485 EXPECT_EQ(0, d.received_redirect_count());
1488 TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1489 TestInterceptor interceptor;
1491 // intercept the main request and cancel from within the restarted job
1492 interceptor.cancel_main_request_ = true;
1494 // setup to intercept final response and override it with an OK response
1495 interceptor.intercept_final_response_ = true;
1496 interceptor.final_headers_ = TestInterceptor::ok_headers();
1497 interceptor.final_data_ = TestInterceptor::ok_data();
1500 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1501 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1502 req->set_method("GET");
1504 base::RunLoop().Run();
1506 // Check the interceptor got called as expected
1507 EXPECT_TRUE(interceptor.did_cancel_main_);
1508 EXPECT_FALSE(interceptor.did_intercept_final_);
1510 // Check we see a canceled request
1511 EXPECT_FALSE(req->status().is_success());
1512 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1515 TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1516 TestInterceptor interceptor;
1518 // intercept the main request and respond with a redirect
1519 interceptor.intercept_main_request_ = true;
1520 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1521 interceptor.main_data_ = TestInterceptor::redirect_data();
1523 // intercept the redirect and cancel from within that job
1524 interceptor.cancel_redirect_request_ = true;
1526 // setup to intercept final response and override it with an OK response
1527 interceptor.intercept_final_response_ = true;
1528 interceptor.final_headers_ = TestInterceptor::ok_headers();
1529 interceptor.final_data_ = TestInterceptor::ok_data();
1532 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1533 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1534 req->set_method("GET");
1536 base::RunLoop().Run();
1538 // Check the interceptor got called as expected
1539 EXPECT_TRUE(interceptor.did_intercept_main_);
1540 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1541 EXPECT_FALSE(interceptor.did_intercept_final_);
1543 // Check we see a canceled request
1544 EXPECT_FALSE(req->status().is_success());
1545 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1548 TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1549 TestInterceptor interceptor;
1551 // intercept the main request to simulate a network error
1552 interceptor.simulate_main_network_error_ = true;
1554 // setup to intercept final response and cancel from within that job
1555 interceptor.cancel_final_request_ = true;
1558 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1559 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1560 req->set_method("GET");
1562 base::RunLoop().Run();
1564 // Check the interceptor got called as expected
1565 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1566 EXPECT_TRUE(interceptor.did_cancel_final_);
1568 // Check we see a canceled request
1569 EXPECT_FALSE(req->status().is_success());
1570 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1573 TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1574 TestInterceptor interceptor;
1576 // intercept the main request and cancel then restart from within that job
1577 interceptor.cancel_then_restart_main_request_ = true;
1579 // setup to intercept final response and override it with an OK response
1580 interceptor.intercept_final_response_ = true;
1581 interceptor.final_headers_ = TestInterceptor::ok_headers();
1582 interceptor.final_data_ = TestInterceptor::ok_data();
1585 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1586 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1587 req->set_method("GET");
1589 base::RunLoop().Run();
1591 // Check the interceptor got called as expected
1592 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1593 EXPECT_FALSE(interceptor.did_intercept_final_);
1595 // Check we see a canceled request
1596 EXPECT_FALSE(req->status().is_success());
1597 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1600 // An Interceptor for use with interceptor tests.
1601 class MockURLRequestInterceptor : public URLRequestInterceptor {
1603 // Static getters for canned response header and data strings.
1604 static std::string ok_data() {
1605 return URLRequestTestJob::test_data_1();
1608 static std::string ok_headers() {
1609 return URLRequestTestJob::test_headers();
1612 static std::string redirect_data() {
1613 return std::string();
1616 static std::string redirect_headers() {
1617 return URLRequestTestJob::test_redirect_headers();
1620 static std::string error_data() {
1621 return std::string("ohhh nooooo mr. bill!");
1624 static std::string error_headers() {
1625 return URLRequestTestJob::test_error_headers();
1628 MockURLRequestInterceptor()
1629 : intercept_main_request_(false), restart_main_request_(false),
1630 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1631 simulate_main_network_error_(false),
1632 intercept_redirect_(false), cancel_redirect_request_(false),
1633 intercept_final_response_(false), cancel_final_request_(false),
1634 use_url_request_http_job_(false),
1635 did_intercept_main_(false), did_restart_main_(false),
1636 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1637 did_simulate_error_main_(false),
1638 did_intercept_redirect_(false), did_cancel_redirect_(false),
1639 did_intercept_final_(false), did_cancel_final_(false) {
1642 ~MockURLRequestInterceptor() override {
1645 // URLRequestInterceptor implementation:
1646 URLRequestJob* MaybeInterceptRequest(
1647 URLRequest* request,
1648 NetworkDelegate* network_delegate) const override {
1649 if (restart_main_request_) {
1650 restart_main_request_ = false;
1651 did_restart_main_ = true;
1652 return new RestartTestJob(request, network_delegate);
1654 if (cancel_main_request_) {
1655 cancel_main_request_ = false;
1656 did_cancel_main_ = true;
1657 return new CancelTestJob(request, network_delegate);
1659 if (cancel_then_restart_main_request_) {
1660 cancel_then_restart_main_request_ = false;
1661 did_cancel_then_restart_main_ = true;
1662 return new CancelThenRestartTestJob(request, network_delegate);
1664 if (simulate_main_network_error_) {
1665 simulate_main_network_error_ = false;
1666 did_simulate_error_main_ = true;
1667 if (use_url_request_http_job_) {
1668 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1670 // This job will result in error since the requested URL is not one of the
1671 // URLs supported by these tests.
1672 return new URLRequestTestJob(request, network_delegate, true);
1674 if (!intercept_main_request_)
1676 intercept_main_request_ = false;
1677 did_intercept_main_ = true;
1678 URLRequestTestJob* job = new URLRequestTestJob(request,
1683 job->set_load_timing_info(main_request_load_timing_info_);
1687 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1688 NetworkDelegate* network_delegate,
1689 const GURL& location) const override {
1690 if (cancel_redirect_request_) {
1691 cancel_redirect_request_ = false;
1692 did_cancel_redirect_ = true;
1693 return new CancelTestJob(request, network_delegate);
1695 if (!intercept_redirect_)
1697 intercept_redirect_ = false;
1698 did_intercept_redirect_ = true;
1699 if (use_url_request_http_job_) {
1700 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1702 return new URLRequestTestJob(request,
1709 URLRequestJob* MaybeInterceptResponse(
1710 URLRequest* request,
1711 NetworkDelegate* network_delegate) const override {
1712 if (cancel_final_request_) {
1713 cancel_final_request_ = false;
1714 did_cancel_final_ = true;
1715 return new CancelTestJob(request, network_delegate);
1717 if (!intercept_final_response_)
1719 intercept_final_response_ = false;
1720 did_intercept_final_ = true;
1721 if (use_url_request_http_job_) {
1722 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1724 return new URLRequestTestJob(request,
1731 void set_intercept_main_request(bool intercept_main_request) {
1732 intercept_main_request_ = intercept_main_request;
1735 void set_main_headers(const std::string& main_headers) {
1736 main_headers_ = main_headers;
1739 void set_main_data(const std::string& main_data) {
1740 main_data_ = main_data;
1743 void set_main_request_load_timing_info(
1744 const LoadTimingInfo& main_request_load_timing_info) {
1745 main_request_load_timing_info_ = main_request_load_timing_info;
1748 void set_restart_main_request(bool restart_main_request) {
1749 restart_main_request_ = restart_main_request;
1752 void set_cancel_main_request(bool cancel_main_request) {
1753 cancel_main_request_ = cancel_main_request;
1756 void set_cancel_then_restart_main_request(
1757 bool cancel_then_restart_main_request) {
1758 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1761 void set_simulate_main_network_error(bool simulate_main_network_error) {
1762 simulate_main_network_error_ = simulate_main_network_error;
1765 void set_intercept_redirect(bool intercept_redirect) {
1766 intercept_redirect_ = intercept_redirect;
1769 void set_redirect_headers(const std::string& redirect_headers) {
1770 redirect_headers_ = redirect_headers;
1773 void set_redirect_data(const std::string& redirect_data) {
1774 redirect_data_ = redirect_data;
1777 void set_cancel_redirect_request(bool cancel_redirect_request) {
1778 cancel_redirect_request_ = cancel_redirect_request;
1781 void set_intercept_final_response(bool intercept_final_response) {
1782 intercept_final_response_ = intercept_final_response;
1785 void set_final_headers(const std::string& final_headers) {
1786 final_headers_ = final_headers;
1789 void set_final_data(const std::string& final_data) {
1790 final_data_ = final_data;
1793 void set_cancel_final_request(bool cancel_final_request) {
1794 cancel_final_request_ = cancel_final_request;
1797 void set_use_url_request_http_job(bool use_url_request_http_job) {
1798 use_url_request_http_job_ = use_url_request_http_job;
1801 bool did_intercept_main() const {
1802 return did_intercept_main_;
1805 bool did_restart_main() const {
1806 return did_restart_main_;
1809 bool did_cancel_main() const {
1810 return did_cancel_main_;
1813 bool did_cancel_then_restart_main() const {
1814 return did_cancel_then_restart_main_;
1817 bool did_simulate_error_main() const {
1818 return did_simulate_error_main_;
1821 bool did_intercept_redirect() const {
1822 return did_intercept_redirect_;
1825 bool did_cancel_redirect() const {
1826 return did_cancel_redirect_;
1829 bool did_intercept_final() const {
1830 return did_intercept_final_;
1833 bool did_cancel_final() const {
1834 return did_cancel_final_;
1838 // Indicate whether to intercept the main request, and if so specify the
1839 // response to return and the LoadTimingInfo to use.
1840 mutable bool intercept_main_request_;
1841 mutable std::string main_headers_;
1842 mutable std::string main_data_;
1843 mutable LoadTimingInfo main_request_load_timing_info_;
1845 // These indicate actions that can be taken within MaybeInterceptRequest.
1846 mutable bool restart_main_request_;
1847 mutable bool cancel_main_request_;
1848 mutable bool cancel_then_restart_main_request_;
1849 mutable bool simulate_main_network_error_;
1851 // Indicate whether to intercept redirects, and if so specify the response to
1853 mutable bool intercept_redirect_;
1854 mutable std::string redirect_headers_;
1855 mutable std::string redirect_data_;
1857 // Cancel the request within MaybeInterceptRedirect.
1858 mutable bool cancel_redirect_request_;
1860 // Indicate whether to intercept the final response, and if so specify the
1861 // response to return.
1862 mutable bool intercept_final_response_;
1863 mutable std::string final_headers_;
1864 mutable std::string final_data_;
1866 // Cancel the final request within MaybeInterceptResponse.
1867 mutable bool cancel_final_request_;
1869 // Instruct the interceptor to use a real URLRequestHTTPJob.
1870 mutable bool use_url_request_http_job_;
1872 // These indicate if the interceptor did something or not.
1873 mutable bool did_intercept_main_;
1874 mutable bool did_restart_main_;
1875 mutable bool did_cancel_main_;
1876 mutable bool did_cancel_then_restart_main_;
1877 mutable bool did_simulate_error_main_;
1878 mutable bool did_intercept_redirect_;
1879 mutable bool did_cancel_redirect_;
1880 mutable bool did_intercept_final_;
1881 mutable bool did_cancel_final_;
1884 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1885 class URLRequestInterceptorTest : public URLRequestTest {
1887 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1890 ~URLRequestInterceptorTest() override {
1891 // URLRequestJobs may post clean-up tasks on destruction.
1892 base::RunLoop().RunUntilIdle();
1895 void SetUpFactory() override {
1896 interceptor_ = new MockURLRequestInterceptor();
1897 job_factory_.reset(new URLRequestInterceptingJobFactory(
1898 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1901 MockURLRequestInterceptor* interceptor() const {
1902 return interceptor_;
1906 MockURLRequestInterceptor* interceptor_;
1909 TEST_F(URLRequestInterceptorTest, Intercept) {
1910 // Intercept the main request and respond with a simple response.
1911 interceptor()->set_intercept_main_request(true);
1912 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1913 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1915 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1916 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1917 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1918 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1919 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1920 req->SetUserData(nullptr, user_data0);
1921 req->SetUserData(&user_data1, user_data1);
1922 req->SetUserData(&user_data2, user_data2);
1923 req->set_method("GET");
1925 base::RunLoop().Run();
1927 // Make sure we can retrieve our specific user data.
1928 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1929 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1930 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1932 // Check that we got one good response.
1933 EXPECT_TRUE(req->status().is_success());
1934 EXPECT_EQ(200, req->response_headers()->response_code());
1935 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1936 EXPECT_EQ(1, d.response_started_count());
1937 EXPECT_EQ(0, d.received_redirect_count());
1940 TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1941 // Intercept the main request and respond with a redirect.
1942 interceptor()->set_intercept_main_request(true);
1943 interceptor()->set_main_headers(
1944 MockURLRequestInterceptor::redirect_headers());
1945 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1947 // Intercept that redirect and respond with a final OK response.
1948 interceptor()->set_intercept_redirect(true);
1949 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1950 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1953 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1954 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1955 req->set_method("GET");
1957 base::RunLoop().Run();
1959 // Check that the interceptor got called as expected.
1960 EXPECT_TRUE(interceptor()->did_intercept_main());
1961 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1963 // Check that we got one good response.
1964 EXPECT_TRUE(req->status().is_success());
1965 if (req->status().is_success())
1966 EXPECT_EQ(200, req->response_headers()->response_code());
1968 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1969 EXPECT_EQ(1, d.response_started_count());
1970 EXPECT_EQ(0, d.received_redirect_count());
1973 TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1974 // Intercept the main request to generate a server error response.
1975 interceptor()->set_intercept_main_request(true);
1976 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1977 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1979 // Intercept that error and respond with an OK response.
1980 interceptor()->set_intercept_final_response(true);
1981 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1982 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1985 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1986 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1987 req->set_method("GET");
1989 base::RunLoop().Run();
1991 // Check that the interceptor got called as expected.
1992 EXPECT_TRUE(interceptor()->did_intercept_main());
1993 EXPECT_TRUE(interceptor()->did_intercept_final());
1995 // Check that we got one good response.
1996 EXPECT_TRUE(req->status().is_success());
1997 EXPECT_EQ(200, req->response_headers()->response_code());
1998 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1999 EXPECT_EQ(1, d.response_started_count());
2000 EXPECT_EQ(0, d.received_redirect_count());
2003 TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
2004 // Intercept the main request to simulate a network error.
2005 interceptor()->set_simulate_main_network_error(true);
2007 // Intercept that error and respond with an OK response.
2008 interceptor()->set_intercept_final_response(true);
2009 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2010 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2013 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2014 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2015 req->set_method("GET");
2017 base::RunLoop().Run();
2019 // Check that the interceptor got called as expected.
2020 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2021 EXPECT_TRUE(interceptor()->did_intercept_final());
2023 // Check that we received one good response.
2024 EXPECT_TRUE(req->status().is_success());
2025 EXPECT_EQ(200, req->response_headers()->response_code());
2026 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2027 EXPECT_EQ(1, d.response_started_count());
2028 EXPECT_EQ(0, d.received_redirect_count());
2031 TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
2032 // Restart the main request.
2033 interceptor()->set_restart_main_request(true);
2035 // then intercept the new main request and respond with an OK response
2036 interceptor()->set_intercept_main_request(true);
2037 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
2038 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
2041 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2042 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2043 req->set_method("GET");
2045 base::RunLoop().Run();
2047 // Check that the interceptor got called as expected.
2048 EXPECT_TRUE(interceptor()->did_restart_main());
2049 EXPECT_TRUE(interceptor()->did_intercept_main());
2051 // Check that we received one good response.
2052 EXPECT_TRUE(req->status().is_success());
2053 if (req->status().is_success())
2054 EXPECT_EQ(200, req->response_headers()->response_code());
2056 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2057 EXPECT_EQ(1, d.response_started_count());
2058 EXPECT_EQ(0, d.received_redirect_count());
2061 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2062 // Intercept the main request and cancel from within the restarted job.
2063 interceptor()->set_cancel_main_request(true);
2065 // Set up to intercept the final response and override it with an OK response.
2066 interceptor()->set_intercept_final_response(true);
2067 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2068 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2071 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2072 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2073 req->set_method("GET");
2075 base::RunLoop().Run();
2077 // Check that the interceptor got called as expected.
2078 EXPECT_TRUE(interceptor()->did_cancel_main());
2079 EXPECT_FALSE(interceptor()->did_intercept_final());
2081 // Check that we see a canceled request.
2082 EXPECT_FALSE(req->status().is_success());
2083 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2086 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2087 // Intercept the main request and respond with a redirect.
2088 interceptor()->set_intercept_main_request(true);
2089 interceptor()->set_main_headers(
2090 MockURLRequestInterceptor::redirect_headers());
2091 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2093 // Intercept the redirect and cancel from within that job.
2094 interceptor()->set_cancel_redirect_request(true);
2096 // Set up to intercept the final response and override it with an OK response.
2097 interceptor()->set_intercept_final_response(true);
2098 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2099 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2102 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2103 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2104 req->set_method("GET");
2106 base::RunLoop().Run();
2108 // Check that the interceptor got called as expected.
2109 EXPECT_TRUE(interceptor()->did_intercept_main());
2110 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2111 EXPECT_FALSE(interceptor()->did_intercept_final());
2113 // Check that we see a canceled request.
2114 EXPECT_FALSE(req->status().is_success());
2115 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2118 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2119 // Intercept the main request to simulate a network error.
2120 interceptor()->set_simulate_main_network_error(true);
2122 // Set up to intercept final the response and cancel from within that job.
2123 interceptor()->set_cancel_final_request(true);
2126 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2127 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2128 req->set_method("GET");
2130 base::RunLoop().Run();
2132 // Check that the interceptor got called as expected.
2133 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2134 EXPECT_TRUE(interceptor()->did_cancel_final());
2136 // Check that we see a canceled request.
2137 EXPECT_FALSE(req->status().is_success());
2138 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2141 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2142 // Intercept the main request and cancel then restart from within that job.
2143 interceptor()->set_cancel_then_restart_main_request(true);
2145 // Set up to intercept the final response and override it with an OK response.
2146 interceptor()->set_intercept_final_response(true);
2147 interceptor()->set_final_headers(TestInterceptor::ok_headers());
2148 interceptor()->set_final_data(TestInterceptor::ok_data());
2151 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2152 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2153 req->set_method("GET");
2155 base::RunLoop().Run();
2157 // Check that the interceptor got called as expected.
2158 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2159 EXPECT_FALSE(interceptor()->did_intercept_final());
2161 // Check that we see a canceled request.
2162 EXPECT_FALSE(req->status().is_success());
2163 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2166 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2167 // reused. |connect_time_flags| is used to indicate if there should be dns
2168 // or SSL times, and |used_proxy| is used for proxy times.
2169 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2170 int connect_time_flags,
2172 LoadTimingInfo load_timing;
2173 load_timing.socket_log_id = 1;
2176 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2177 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2180 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2181 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2182 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2183 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2185 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2186 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2187 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2188 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2190 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2192 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2193 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2194 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2198 // Same as above, but in the case of a reused socket.
2199 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2201 LoadTimingInfo load_timing;
2202 load_timing.socket_log_id = 1;
2203 load_timing.socket_reused = true;
2206 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2207 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2210 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2211 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2212 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2216 LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2217 const LoadTimingInfo& job_load_timing,
2218 const URLRequestContext& context,
2219 MockURLRequestInterceptor* interceptor) {
2220 interceptor->set_intercept_main_request(true);
2221 interceptor->set_main_request_load_timing_info(job_load_timing);
2223 scoped_ptr<URLRequest> req(context.CreateRequest(
2224 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2226 base::RunLoop().Run();
2228 LoadTimingInfo resulting_load_timing;
2229 req->GetLoadTimingInfo(&resulting_load_timing);
2231 // None of these should be modified by the URLRequest.
2232 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2233 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2234 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2235 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2236 EXPECT_EQ(job_load_timing.receive_headers_end,
2237 resulting_load_timing.receive_headers_end);
2239 return resulting_load_timing;
2242 // Basic test that the intercept + load timing tests work.
2243 TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
2244 base::TimeTicks now = base::TimeTicks::Now();
2245 LoadTimingInfo job_load_timing =
2246 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2248 LoadTimingInfo load_timing_result =
2249 RunURLRequestInterceptorLoadTimingTest(
2250 job_load_timing, default_context(), interceptor());
2252 // Nothing should have been changed by the URLRequest.
2253 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2254 load_timing_result.proxy_resolve_start);
2255 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2256 load_timing_result.proxy_resolve_end);
2257 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2258 load_timing_result.connect_timing.dns_start);
2259 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2260 load_timing_result.connect_timing.dns_end);
2261 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2262 load_timing_result.connect_timing.connect_start);
2263 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2264 load_timing_result.connect_timing.connect_end);
2265 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2266 load_timing_result.connect_timing.ssl_start);
2267 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2268 load_timing_result.connect_timing.ssl_end);
2270 // Redundant sanity check.
2271 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2274 // Another basic test, with proxy and SSL times, but no DNS times.
2275 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
2276 base::TimeTicks now = base::TimeTicks::Now();
2277 LoadTimingInfo job_load_timing =
2278 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2280 LoadTimingInfo load_timing_result =
2281 RunURLRequestInterceptorLoadTimingTest(
2282 job_load_timing, default_context(), interceptor());
2284 // Nothing should have been changed by the URLRequest.
2285 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2286 load_timing_result.proxy_resolve_start);
2287 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2288 load_timing_result.proxy_resolve_end);
2289 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2290 load_timing_result.connect_timing.dns_start);
2291 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2292 load_timing_result.connect_timing.dns_end);
2293 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2294 load_timing_result.connect_timing.connect_start);
2295 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2296 load_timing_result.connect_timing.connect_end);
2297 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2298 load_timing_result.connect_timing.ssl_start);
2299 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2300 load_timing_result.connect_timing.ssl_end);
2302 // Redundant sanity check.
2303 TestLoadTimingNotReusedWithProxy(load_timing_result,
2304 CONNECT_TIMING_HAS_SSL_TIMES);
2307 // Make sure that URLRequest correctly adjusts proxy times when they're before
2308 // |request_start|, due to already having a connected socket. This happens in
2309 // the case of reusing a SPDY session. The connected socket is not considered
2310 // reused in this test (May be a preconnect).
2312 // To mix things up from the test above, assumes DNS times but no SSL times.
2313 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
2314 base::TimeTicks now = base::TimeTicks::Now();
2315 LoadTimingInfo job_load_timing =
2316 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2317 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2318 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2319 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2320 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2321 job_load_timing.connect_timing.connect_start =
2322 now - base::TimeDelta::FromDays(2);
2323 job_load_timing.connect_timing.connect_end =
2324 now - base::TimeDelta::FromDays(1);
2326 LoadTimingInfo load_timing_result =
2327 RunURLRequestInterceptorLoadTimingTest(
2328 job_load_timing, default_context(), interceptor());
2330 // Proxy times, connect times, and DNS times should all be replaced with
2332 EXPECT_EQ(load_timing_result.request_start,
2333 load_timing_result.proxy_resolve_start);
2334 EXPECT_EQ(load_timing_result.request_start,
2335 load_timing_result.proxy_resolve_end);
2336 EXPECT_EQ(load_timing_result.request_start,
2337 load_timing_result.connect_timing.dns_start);
2338 EXPECT_EQ(load_timing_result.request_start,
2339 load_timing_result.connect_timing.dns_end);
2340 EXPECT_EQ(load_timing_result.request_start,
2341 load_timing_result.connect_timing.connect_start);
2342 EXPECT_EQ(load_timing_result.request_start,
2343 load_timing_result.connect_timing.connect_end);
2345 // Other times should have been left null.
2346 TestLoadTimingNotReusedWithProxy(load_timing_result,
2347 CONNECT_TIMING_HAS_DNS_TIMES);
2350 // Same as above, but in the reused case.
2351 TEST_F(URLRequestInterceptorTest,
2352 InterceptLoadTimingEarlyProxyResolutionReused) {
2353 base::TimeTicks now = base::TimeTicks::Now();
2354 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2355 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2356 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2358 LoadTimingInfo load_timing_result =
2359 RunURLRequestInterceptorLoadTimingTest(
2360 job_load_timing, default_context(), interceptor());
2362 // Proxy times and connect times should all be replaced with request_start.
2363 EXPECT_EQ(load_timing_result.request_start,
2364 load_timing_result.proxy_resolve_start);
2365 EXPECT_EQ(load_timing_result.request_start,
2366 load_timing_result.proxy_resolve_end);
2368 // Other times should have been left null.
2369 TestLoadTimingReusedWithProxy(load_timing_result);
2372 // Make sure that URLRequest correctly adjusts connect times when they're before
2373 // |request_start|, due to reusing a connected socket. The connected socket is
2374 // not considered reused in this test (May be a preconnect).
2376 // To mix things up, the request has SSL times, but no DNS times.
2377 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
2378 base::TimeTicks now = base::TimeTicks::Now();
2379 LoadTimingInfo job_load_timing =
2380 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2381 job_load_timing.connect_timing.connect_start =
2382 now - base::TimeDelta::FromDays(1);
2383 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2384 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2385 job_load_timing.connect_timing.connect_end =
2386 now - base::TimeDelta::FromDays(4);
2388 LoadTimingInfo load_timing_result =
2389 RunURLRequestInterceptorLoadTimingTest(
2390 job_load_timing, default_context(), interceptor());
2392 // Connect times, and SSL times should be replaced with request_start.
2393 EXPECT_EQ(load_timing_result.request_start,
2394 load_timing_result.connect_timing.connect_start);
2395 EXPECT_EQ(load_timing_result.request_start,
2396 load_timing_result.connect_timing.ssl_start);
2397 EXPECT_EQ(load_timing_result.request_start,
2398 load_timing_result.connect_timing.ssl_end);
2399 EXPECT_EQ(load_timing_result.request_start,
2400 load_timing_result.connect_timing.connect_end);
2402 // Other times should have been left null.
2403 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2406 // Make sure that URLRequest correctly adjusts connect times when they're before
2407 // |request_start|, due to reusing a connected socket in the case that there
2408 // are also proxy times. The connected socket is not considered reused in this
2409 // test (May be a preconnect).
2411 // In this test, there are no SSL or DNS times.
2412 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
2413 base::TimeTicks now = base::TimeTicks::Now();
2414 LoadTimingInfo job_load_timing =
2415 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2416 job_load_timing.connect_timing.connect_start =
2417 now - base::TimeDelta::FromDays(1);
2418 job_load_timing.connect_timing.connect_end =
2419 now - base::TimeDelta::FromDays(2);
2421 LoadTimingInfo load_timing_result =
2422 RunURLRequestInterceptorLoadTimingTest(
2423 job_load_timing, default_context(), interceptor());
2425 // Connect times should be replaced with proxy_resolve_end.
2426 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2427 load_timing_result.connect_timing.connect_start);
2428 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2429 load_timing_result.connect_timing.connect_end);
2431 // Other times should have been left null.
2432 TestLoadTimingNotReusedWithProxy(load_timing_result,
2433 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2436 // Check that two different URL requests have different identifiers.
2437 TEST_F(URLRequestTest, Identifiers) {
2439 TestURLRequestContext context;
2440 scoped_ptr<URLRequest> req(context.CreateRequest(
2441 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2442 scoped_ptr<URLRequest> other_req(context.CreateRequest(
2443 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2445 ASSERT_NE(req->identifier(), other_req->identifier());
2448 // Check that a failure to connect to the proxy is reported to the network
2450 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2451 MockHostResolver host_resolver;
2452 host_resolver.rules()->AddSimulatedFailure("*");
2454 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
2455 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2458 scoped_ptr<URLRequest> req(context.CreateRequest(
2459 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2460 req->set_method("GET");
2463 base::RunLoop().Run();
2465 // Check we see a failed request.
2466 EXPECT_FALSE(req->status().is_success());
2467 // The proxy server is not set before failure.
2468 EXPECT_TRUE(req->proxy_server().IsEmpty());
2469 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2470 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
2472 EXPECT_EQ(1, network_delegate.error_count());
2473 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2474 EXPECT_EQ(1, network_delegate.completed_requests());
2477 // Make sure that NetworkDelegate::NotifyCompleted is called if
2478 // content is empty.
2479 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2481 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2482 GURL("data:,"), DEFAULT_PRIORITY, &d, NULL));
2484 base::RunLoop().Run();
2485 EXPECT_EQ("", d.data_received());
2486 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2489 // Make sure that SetPriority actually sets the URLRequest's priority
2490 // correctly, both before and after start.
2491 TEST_F(URLRequestTest, SetPriorityBasic) {
2493 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2494 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2495 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
2497 req->SetPriority(LOW);
2498 EXPECT_EQ(LOW, req->priority());
2501 EXPECT_EQ(LOW, req->priority());
2503 req->SetPriority(MEDIUM);
2504 EXPECT_EQ(MEDIUM, req->priority());
2507 // Make sure that URLRequest calls SetPriority on a job before calling
2509 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2511 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2512 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2513 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
2515 scoped_refptr<URLRequestTestJob> job =
2516 new URLRequestTestJob(req.get(), &default_network_delegate_);
2517 AddTestInterceptor()->set_main_intercept_job(job.get());
2518 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2520 req->SetPriority(LOW);
2523 EXPECT_EQ(LOW, job->priority());
2526 // Make sure that URLRequest passes on its priority updates to its
2528 TEST_F(URLRequestTest, SetJobPriority) {
2530 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2531 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2533 scoped_refptr<URLRequestTestJob> job =
2534 new URLRequestTestJob(req.get(), &default_network_delegate_);
2535 AddTestInterceptor()->set_main_intercept_job(job.get());
2537 req->SetPriority(LOW);
2539 EXPECT_EQ(LOW, job->priority());
2541 req->SetPriority(MEDIUM);
2542 EXPECT_EQ(MEDIUM, req->priority());
2543 EXPECT_EQ(MEDIUM, job->priority());
2546 // Setting the IGNORE_LIMITS load flag should be okay if the priority
2547 // is MAXIMUM_PRIORITY.
2548 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2550 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2551 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d, NULL));
2552 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2554 scoped_refptr<URLRequestTestJob> job =
2555 new URLRequestTestJob(req.get(), &default_network_delegate_);
2556 AddTestInterceptor()->set_main_intercept_job(job.get());
2558 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2559 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2561 req->SetPriority(MAXIMUM_PRIORITY);
2562 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2565 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2566 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2569 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
2570 #if !defined(OS_IOS)
2571 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
2572 // This is to work around mysterious failures in chrome_frame_net_tests. See:
2573 // http://crbug.com/114369
2574 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
2575 class LocalHttpTestServer : public SpawnedTestServer {
2577 explicit LocalHttpTestServer(const base::FilePath& document_root)
2578 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2579 ScopedCustomUrlRequestTestHttpHost::value(),
2581 LocalHttpTestServer()
2582 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2583 ScopedCustomUrlRequestTestHttpHost::value(),
2584 base::FilePath()) {}
2587 TEST_F(URLRequestTest, DelayedCookieCallback) {
2588 LocalHttpTestServer test_server;
2589 ASSERT_TRUE(test_server.Start());
2591 TestURLRequestContext context;
2592 scoped_refptr<DelayedCookieMonster> delayed_cm =
2593 new DelayedCookieMonster();
2594 scoped_refptr<CookieStore> cookie_store = delayed_cm;
2595 context.set_cookie_store(delayed_cm.get());
2599 TestNetworkDelegate network_delegate;
2600 context.set_network_delegate(&network_delegate);
2602 scoped_ptr<URLRequest> req(context.CreateRequest(
2603 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2606 base::RunLoop().Run();
2607 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2608 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2609 EXPECT_EQ(1, network_delegate.set_cookie_count());
2612 // Verify that the cookie is set.
2614 TestNetworkDelegate network_delegate;
2615 context.set_network_delegate(&network_delegate);
2617 scoped_ptr<URLRequest> req(context.CreateRequest(
2618 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2620 base::RunLoop().Run();
2622 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2623 != std::string::npos);
2624 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2625 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2629 TEST_F(URLRequestTest, DoNotSendCookies) {
2630 LocalHttpTestServer test_server;
2631 ASSERT_TRUE(test_server.Start());
2635 TestNetworkDelegate network_delegate;
2636 default_context_.set_network_delegate(&network_delegate);
2638 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2639 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2642 base::RunLoop().Run();
2643 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2644 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2647 // Verify that the cookie is set.
2649 TestNetworkDelegate network_delegate;
2650 default_context_.set_network_delegate(&network_delegate);
2652 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2653 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2655 base::RunLoop().Run();
2657 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2658 != std::string::npos);
2659 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2660 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2663 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2665 TestNetworkDelegate network_delegate;
2666 default_context_.set_network_delegate(&network_delegate);
2668 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2669 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2670 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2672 base::RunLoop().Run();
2674 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2675 == std::string::npos);
2677 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2678 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2679 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2683 TEST_F(URLRequestTest, DoNotSaveCookies) {
2684 LocalHttpTestServer test_server;
2685 ASSERT_TRUE(test_server.Start());
2689 TestNetworkDelegate network_delegate;
2690 default_context_.set_network_delegate(&network_delegate);
2692 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2693 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2696 base::RunLoop().Run();
2698 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2699 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2700 EXPECT_EQ(1, network_delegate.set_cookie_count());
2703 // Try to set-up another cookie and update the previous cookie.
2705 TestNetworkDelegate network_delegate;
2706 default_context_.set_network_delegate(&network_delegate);
2708 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2709 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2710 DEFAULT_PRIORITY, &d, NULL));
2711 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2714 base::RunLoop().Run();
2716 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2717 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2718 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2719 EXPECT_EQ(0, network_delegate.set_cookie_count());
2722 // Verify the cookies weren't saved or updated.
2724 TestNetworkDelegate network_delegate;
2725 default_context_.set_network_delegate(&network_delegate);
2727 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2728 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2730 base::RunLoop().Run();
2732 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2733 == std::string::npos);
2734 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2735 != std::string::npos);
2737 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2738 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2739 EXPECT_EQ(0, network_delegate.set_cookie_count());
2743 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2744 LocalHttpTestServer test_server;
2745 ASSERT_TRUE(test_server.Start());
2749 TestNetworkDelegate network_delegate;
2750 default_context_.set_network_delegate(&network_delegate);
2752 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2753 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2756 base::RunLoop().Run();
2758 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2759 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2762 // Verify that the cookie is set.
2764 TestNetworkDelegate network_delegate;
2765 default_context_.set_network_delegate(&network_delegate);
2767 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2768 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2770 base::RunLoop().Run();
2772 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2773 != std::string::npos);
2775 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2776 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2779 // Verify that the cookie isn't sent.
2781 TestNetworkDelegate network_delegate;
2782 default_context_.set_network_delegate(&network_delegate);
2784 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2785 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2786 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2788 base::RunLoop().Run();
2790 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2791 == std::string::npos);
2793 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2794 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2798 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2799 LocalHttpTestServer test_server;
2800 ASSERT_TRUE(test_server.Start());
2804 TestNetworkDelegate network_delegate;
2805 default_context_.set_network_delegate(&network_delegate);
2807 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2808 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2811 base::RunLoop().Run();
2813 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2814 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2817 // Try to set-up another cookie and update the previous cookie.
2819 TestNetworkDelegate network_delegate;
2820 default_context_.set_network_delegate(&network_delegate);
2822 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2823 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2824 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2825 DEFAULT_PRIORITY, &d, NULL));
2828 base::RunLoop().Run();
2830 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2831 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2834 // Verify the cookies weren't saved or updated.
2836 TestNetworkDelegate network_delegate;
2837 default_context_.set_network_delegate(&network_delegate);
2839 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2840 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2842 base::RunLoop().Run();
2844 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2845 == std::string::npos);
2846 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2847 != std::string::npos);
2849 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2850 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2854 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2855 LocalHttpTestServer test_server;
2856 ASSERT_TRUE(test_server.Start());
2858 // Set up an empty cookie.
2860 TestNetworkDelegate network_delegate;
2861 default_context_.set_network_delegate(&network_delegate);
2863 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2864 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d, NULL));
2866 base::RunLoop().Run();
2868 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2869 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2870 EXPECT_EQ(0, network_delegate.set_cookie_count());
2874 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2875 LocalHttpTestServer test_server;
2876 ASSERT_TRUE(test_server.Start());
2880 TestNetworkDelegate network_delegate;
2881 default_context_.set_network_delegate(&network_delegate);
2883 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2884 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2887 base::RunLoop().Run();
2889 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2890 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2893 // Verify that the cookie is set.
2895 TestNetworkDelegate network_delegate;
2896 default_context_.set_network_delegate(&network_delegate);
2898 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2899 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2901 base::RunLoop().Run();
2903 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2904 != std::string::npos);
2906 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2907 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2910 // Verify that the cookie isn't sent.
2912 TestNetworkDelegate network_delegate;
2913 default_context_.set_network_delegate(&network_delegate);
2915 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2916 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2917 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2919 base::RunLoop().Run();
2921 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2922 == std::string::npos);
2924 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2925 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2929 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2930 LocalHttpTestServer test_server;
2931 ASSERT_TRUE(test_server.Start());
2935 TestNetworkDelegate network_delegate;
2936 default_context_.set_network_delegate(&network_delegate);
2938 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2939 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2942 base::RunLoop().Run();
2944 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2945 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2948 // Try to set-up another cookie and update the previous cookie.
2950 TestNetworkDelegate network_delegate;
2951 default_context_.set_network_delegate(&network_delegate);
2953 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2954 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2955 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2956 DEFAULT_PRIORITY, &d, NULL));
2959 base::RunLoop().Run();
2961 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2962 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2965 // Verify the cookies weren't saved or updated.
2967 TestNetworkDelegate network_delegate;
2968 default_context_.set_network_delegate(&network_delegate);
2970 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2971 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2973 base::RunLoop().Run();
2975 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2976 == std::string::npos);
2977 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2978 != std::string::npos);
2980 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2981 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2985 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2986 // value for the |fixed_date| argument given to the constructor.
2987 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2989 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2990 : fixed_date_(fixed_date) {}
2991 ~FixedDateNetworkDelegate() override {}
2993 // NetworkDelegate implementation
2994 int OnHeadersReceived(
2995 URLRequest* request,
2996 const CompletionCallback& callback,
2997 const HttpResponseHeaders* original_response_headers,
2998 scoped_refptr<HttpResponseHeaders>* override_response_headers,
2999 GURL* allowed_unsafe_redirect_url) override;
3002 std::string fixed_date_;
3004 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3007 int FixedDateNetworkDelegate::OnHeadersReceived(
3008 URLRequest* request,
3009 const CompletionCallback& callback,
3010 const HttpResponseHeaders* original_response_headers,
3011 scoped_refptr<HttpResponseHeaders>* override_response_headers,
3012 GURL* allowed_unsafe_redirect_url) {
3013 HttpResponseHeaders* new_response_headers =
3014 new HttpResponseHeaders(original_response_headers->raw_headers());
3016 new_response_headers->RemoveHeader("Date");
3017 new_response_headers->AddHeader("Date: " + fixed_date_);
3019 *override_response_headers = new_response_headers;
3020 return TestNetworkDelegate::OnHeadersReceived(request,
3022 original_response_headers,
3023 override_response_headers,
3024 allowed_unsafe_redirect_url);
3027 // Test that cookie expiration times are adjusted for server/client clock
3028 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3029 // headers by defaulting to GMT. (crbug.com/135131)
3030 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3031 LocalHttpTestServer test_server;
3032 ASSERT_TRUE(test_server.Start());
3034 // Set up an expired cookie.
3036 TestNetworkDelegate network_delegate;
3037 default_context_.set_network_delegate(&network_delegate);
3039 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3041 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
3042 DEFAULT_PRIORITY, &d, NULL));
3044 base::RunLoop().Run();
3046 // Verify that the cookie is not set.
3048 TestNetworkDelegate network_delegate;
3049 default_context_.set_network_delegate(&network_delegate);
3051 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3052 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
3054 base::RunLoop().Run();
3056 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3058 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3060 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3061 default_context_.set_network_delegate(&network_delegate);
3063 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3065 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
3066 DEFAULT_PRIORITY, &d, NULL));
3068 base::RunLoop().Run();
3070 // Verify that the cookie is set.
3072 TestNetworkDelegate network_delegate;
3073 default_context_.set_network_delegate(&network_delegate);
3075 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3076 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
3078 base::RunLoop().Run();
3080 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3085 // Check that it is impossible to change the referrer in the extra headers of
3087 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3088 LocalHttpTestServer test_server;
3089 ASSERT_TRUE(test_server.Start());
3091 // If extra headers contain referer and the request contains a referer,
3092 // only the latter shall be respected.
3095 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3096 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
3097 req->SetReferrer("http://foo.com/");
3099 HttpRequestHeaders headers;
3100 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
3101 req->SetExtraRequestHeaders(headers);
3104 base::RunLoop().Run();
3106 EXPECT_EQ("http://foo.com/", d.data_received());
3109 // If extra headers contain a referer but the request does not, no referer
3110 // shall be sent in the header.
3113 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3114 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
3116 HttpRequestHeaders headers;
3117 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
3118 req->SetExtraRequestHeaders(headers);
3119 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
3122 base::RunLoop().Run();
3124 EXPECT_EQ("None", d.data_received());
3128 class URLRequestTestHTTP : public URLRequestTest {
3130 URLRequestTestHTTP()
3131 : test_server_(base::FilePath(FILE_PATH_LITERAL(
3132 "net/data/url_request_unittest"))) {
3136 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3137 // |request_method| is the method to use for the initial request.
3138 // |redirect_method| is the method that is expected to be used for the second
3139 // request, after redirection.
3140 // If |include_data| is true, data is uploaded with the request. The
3141 // response body is expected to match it exactly, if and only if
3142 // |request_method| == |redirect_method|.
3143 void HTTPRedirectMethodTest(const GURL& redirect_url,
3144 const std::string& request_method,
3145 const std::string& redirect_method,
3146 bool include_data) {
3147 static const char kData[] = "hello world";
3149 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3150 redirect_url, DEFAULT_PRIORITY, &d, NULL));
3151 req->set_method(request_method);
3153 req->set_upload(CreateSimpleUploadData(kData));
3154 HttpRequestHeaders headers;
3155 headers.SetHeader(HttpRequestHeaders::kContentLength,
3156 base::UintToString(arraysize(kData) - 1));
3157 req->SetExtraRequestHeaders(headers);
3160 base::RunLoop().Run();
3161 EXPECT_EQ(redirect_method, req->method());
3162 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3163 EXPECT_EQ(OK, req->status().error());
3165 if (request_method == redirect_method) {
3166 EXPECT_EQ(kData, d.data_received());
3168 EXPECT_NE(kData, d.data_received());
3172 LOG(WARNING) << "Request method was: " << request_method;
3175 void HTTPUploadDataOperationTest(const std::string& method) {
3176 const int kMsgSize = 20000; // multiple of 10
3177 const int kIterations = 50;
3178 char* uploadBytes = new char[kMsgSize+1];
3179 char* ptr = uploadBytes;
3181 for (int idx = 0; idx < kMsgSize/10; idx++) {
3182 memcpy(ptr, "----------", 10);
3184 if (idx % 100 == 0) {
3191 uploadBytes[kMsgSize] = '\0';
3193 for (int i = 0; i < kIterations; ++i) {
3195 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3196 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
3197 r->set_method(method.c_str());
3199 r->set_upload(CreateSimpleUploadData(uploadBytes));
3202 EXPECT_TRUE(r->is_pending());
3204 base::RunLoop().Run();
3206 ASSERT_EQ(1, d.response_started_count())
3207 << "request failed: " << r->status().status()
3208 << ", os error: " << r->status().error();
3210 EXPECT_FALSE(d.received_data_before_response());
3211 EXPECT_EQ(uploadBytes, d.data_received());
3213 delete[] uploadBytes;
3216 void AddChunksToUpload(URLRequest* r) {
3217 r->AppendChunkToUpload("a", 1, false);
3218 r->AppendChunkToUpload("bcd", 3, false);
3219 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3220 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3221 r->AppendChunkToUpload("0", 1, false);
3222 r->AppendChunkToUpload("2323", 4, true);
3225 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
3226 // This should match the chunks sent by AddChunksToUpload().
3227 const std::string expected_data =
3228 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3230 ASSERT_EQ(1, d->response_started_count())
3231 << "request failed: " << r->status().status()
3232 << ", os error: " << r->status().error();
3234 EXPECT_FALSE(d->received_data_before_response());
3236 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3237 EXPECT_EQ(expected_data, d->data_received());
3240 bool DoManyCookiesRequest(int num_cookies) {
3242 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3243 test_server_.GetURL("set-many-cookies?" +
3244 base::IntToString(num_cookies)),
3245 DEFAULT_PRIORITY, &d, NULL));
3248 EXPECT_TRUE(r->is_pending());
3250 base::RunLoop().Run();
3252 bool is_success = r->status().is_success();
3255 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
3256 // The test server appears to be unable to handle subsequent requests
3257 // after this error is triggered. Force it to restart.
3258 EXPECT_TRUE(test_server_.Stop());
3259 EXPECT_TRUE(test_server_.Start());
3265 LocalHttpTestServer* test_server() {
3266 return &test_server_;
3270 LocalHttpTestServer test_server_;
3273 // In this unit test, we're using the HTTPTestServer as a proxy server and
3274 // issuing a CONNECT request with the magic host name "www.redirect.com".
3275 // The HTTPTestServer will return a 302 response, which we should not
3277 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
3278 ASSERT_TRUE(test_server_.Start());
3280 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3281 TestURLRequestContextWithProxy context(
3282 test_server_.host_port_pair().ToString(), &network_delegate);
3286 scoped_ptr<URLRequest> r(context.CreateRequest(
3287 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
3289 EXPECT_TRUE(r->is_pending());
3291 base::RunLoop().Run();
3293 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3294 // The proxy server is not set before failure.
3295 EXPECT_TRUE(r->proxy_server().IsEmpty());
3296 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3297 EXPECT_EQ(1, d.response_started_count());
3298 // We should not have followed the redirect.
3299 EXPECT_EQ(0, d.received_redirect_count());
3303 // This is the same as the previous test, but checks that the network delegate
3304 // registers the error.
3305 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
3306 ASSERT_TRUE(test_server_.Start());
3308 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3309 TestURLRequestContextWithProxy context(
3310 test_server_.host_port_pair().ToString(), &network_delegate);
3314 scoped_ptr<URLRequest> r(context.CreateRequest(
3315 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
3317 EXPECT_TRUE(r->is_pending());
3319 base::RunLoop().Run();
3321 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3322 // The proxy server is not set before failure.
3323 EXPECT_TRUE(r->proxy_server().IsEmpty());
3324 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3325 EXPECT_EQ(1, d.response_started_count());
3326 // We should not have followed the redirect.
3327 EXPECT_EQ(0, d.received_redirect_count());
3329 EXPECT_EQ(1, network_delegate.error_count());
3330 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
3334 // Tests that we can block and asynchronously return OK in various stages.
3335 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3336 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3337 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3338 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3339 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3341 static const size_t blocking_stages_length = arraysize(blocking_stages);
3343 ASSERT_TRUE(test_server_.Start());
3346 BlockingNetworkDelegate network_delegate(
3347 BlockingNetworkDelegate::USER_CALLBACK);
3348 network_delegate.set_block_on(
3349 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3350 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3351 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3353 TestURLRequestContext context(true);
3354 context.set_network_delegate(&network_delegate);
3358 scoped_ptr<URLRequest> r(context.CreateRequest(
3359 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
3362 for (size_t i = 0; i < blocking_stages_length; ++i) {
3363 base::RunLoop().Run();
3364 EXPECT_EQ(blocking_stages[i],
3365 network_delegate.stage_blocked_for_callback());
3366 network_delegate.DoCallback(OK);
3368 base::RunLoop().Run();
3369 EXPECT_EQ(200, r->GetResponseCode());
3370 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3371 EXPECT_EQ(1, network_delegate.created_requests());
3372 EXPECT_EQ(0, network_delegate.destroyed_requests());
3374 EXPECT_EQ(1, network_delegate.destroyed_requests());
3377 // Tests that the network delegate can block and cancel a request.
3378 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3379 ASSERT_TRUE(test_server_.Start());
3382 BlockingNetworkDelegate network_delegate(
3383 BlockingNetworkDelegate::AUTO_CALLBACK);
3384 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3385 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
3387 TestURLRequestContextWithProxy context(
3388 test_server_.host_port_pair().ToString(), &network_delegate);
3391 scoped_ptr<URLRequest> r(context.CreateRequest(
3392 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3395 base::RunLoop().Run();
3397 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3398 // The proxy server is not set before cancellation.
3399 EXPECT_TRUE(r->proxy_server().IsEmpty());
3400 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
3401 EXPECT_EQ(1, network_delegate.created_requests());
3402 EXPECT_EQ(0, network_delegate.destroyed_requests());
3404 EXPECT_EQ(1, network_delegate.destroyed_requests());
3407 // Helper function for NetworkDelegateCancelRequestAsynchronously and
3408 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3409 // delegate operating in |block_mode| and a request for |url|. It blocks the
3410 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3411 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3412 BlockingNetworkDelegate::Stage stage,
3415 BlockingNetworkDelegate network_delegate(block_mode);
3416 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3417 network_delegate.set_block_on(stage);
3419 TestURLRequestContext context(true);
3420 context.set_network_delegate(&network_delegate);
3424 scoped_ptr<URLRequest> r(context.CreateRequest(
3425 url, DEFAULT_PRIORITY, &d, NULL));
3428 base::RunLoop().Run();
3430 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3431 // The proxy server is not set before cancellation.
3432 EXPECT_TRUE(r->proxy_server().IsEmpty());
3433 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
3434 EXPECT_EQ(1, network_delegate.created_requests());
3435 EXPECT_EQ(0, network_delegate.destroyed_requests());
3437 EXPECT_EQ(1, network_delegate.destroyed_requests());
3440 // The following 3 tests check that the network delegate can cancel a request
3441 // synchronously in various stages of the request.
3442 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3443 ASSERT_TRUE(test_server_.Start());
3444 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3445 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3446 test_server_.GetURL(std::string()));
3449 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3450 ASSERT_TRUE(test_server_.Start());
3451 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3452 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3453 test_server_.GetURL(std::string()));
3456 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3457 ASSERT_TRUE(test_server_.Start());
3458 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3459 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3460 test_server_.GetURL(std::string()));
3463 // The following 3 tests check that the network delegate can cancel a request
3464 // asynchronously in various stages of the request.
3465 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3466 ASSERT_TRUE(test_server_.Start());
3467 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3468 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3469 test_server_.GetURL(std::string()));
3472 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3473 ASSERT_TRUE(test_server_.Start());
3474 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3475 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3476 test_server_.GetURL(std::string()));
3479 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3480 ASSERT_TRUE(test_server_.Start());
3481 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3482 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3483 test_server_.GetURL(std::string()));
3486 // Tests that the network delegate can block and redirect a request to a new
3488 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3489 ASSERT_TRUE(test_server_.Start());
3492 BlockingNetworkDelegate network_delegate(
3493 BlockingNetworkDelegate::AUTO_CALLBACK);
3494 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3495 GURL redirect_url(test_server_.GetURL("simple.html"));
3496 network_delegate.set_redirect_url(redirect_url);
3498 TestURLRequestContextWithProxy context(
3499 test_server_.host_port_pair().ToString(), &network_delegate);
3502 GURL original_url(test_server_.GetURL("empty.html"));
3503 scoped_ptr<URLRequest> r(context.CreateRequest(
3504 original_url, DEFAULT_PRIORITY, &d, NULL));
3506 // Quit after hitting the redirect, so can check the headers.
3507 d.set_quit_on_redirect(true);
3509 base::RunLoop().Run();
3511 // Check headers from URLRequestJob.
3512 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3513 EXPECT_EQ(307, r->GetResponseCode());
3514 EXPECT_EQ(307, r->response_headers()->response_code());
3515 std::string location;
3516 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3518 EXPECT_EQ(redirect_url, GURL(location));
3520 // Let the request finish.
3521 r->FollowDeferredRedirect();
3522 base::RunLoop().Run();
3523 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3524 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3526 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3528 network_delegate.last_observed_proxy().Equals(
3529 test_server_.host_port_pair()));
3531 EXPECT_EQ(0, r->status().error());
3532 EXPECT_EQ(redirect_url, r->url());
3533 EXPECT_EQ(original_url, r->original_url());
3534 EXPECT_EQ(2U, r->url_chain().size());
3535 EXPECT_EQ(1, network_delegate.created_requests());
3536 EXPECT_EQ(0, network_delegate.destroyed_requests());
3538 EXPECT_EQ(1, network_delegate.destroyed_requests());
3541 // Tests that the network delegate can block and redirect a request to a new
3542 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3543 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3544 ASSERT_TRUE(test_server_.Start());
3547 BlockingNetworkDelegate network_delegate(
3548 BlockingNetworkDelegate::SYNCHRONOUS);
3549 GURL redirect_url(test_server_.GetURL("simple.html"));
3550 network_delegate.set_redirect_url(redirect_url);
3552 TestURLRequestContextWithProxy context(
3553 test_server_.host_port_pair().ToString(), &network_delegate);
3556 GURL original_url(test_server_.GetURL("empty.html"));
3557 scoped_ptr<URLRequest> r(context.CreateRequest(
3558 original_url, DEFAULT_PRIORITY, &d, NULL));
3560 // Quit after hitting the redirect, so can check the headers.
3561 d.set_quit_on_redirect(true);
3563 base::RunLoop().Run();
3565 // Check headers from URLRequestJob.
3566 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3567 EXPECT_EQ(307, r->GetResponseCode());
3568 EXPECT_EQ(307, r->response_headers()->response_code());
3569 std::string location;
3570 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3572 EXPECT_EQ(redirect_url, GURL(location));
3574 // Let the request finish.
3575 r->FollowDeferredRedirect();
3576 base::RunLoop().Run();
3578 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3579 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3581 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3583 network_delegate.last_observed_proxy().Equals(
3584 test_server_.host_port_pair()));
3585 EXPECT_EQ(0, r->status().error());
3586 EXPECT_EQ(redirect_url, r->url());
3587 EXPECT_EQ(original_url, r->original_url());
3588 EXPECT_EQ(2U, r->url_chain().size());
3589 EXPECT_EQ(1, network_delegate.created_requests());
3590 EXPECT_EQ(0, network_delegate.destroyed_requests());
3592 EXPECT_EQ(1, network_delegate.destroyed_requests());
3595 // Tests that redirects caused by the network delegate preserve POST data.
3596 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3597 ASSERT_TRUE(test_server_.Start());
3599 const char kData[] = "hello world";
3602 BlockingNetworkDelegate network_delegate(
3603 BlockingNetworkDelegate::AUTO_CALLBACK);
3604 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3605 GURL redirect_url(test_server_.GetURL("echo"));
3606 network_delegate.set_redirect_url(redirect_url);
3608 TestURLRequestContext context(true);
3609 context.set_network_delegate(&network_delegate);
3613 GURL original_url(test_server_.GetURL("empty.html"));
3614 scoped_ptr<URLRequest> r(context.CreateRequest(
3615 original_url, DEFAULT_PRIORITY, &d, NULL));
3616 r->set_method("POST");
3617 r->set_upload(CreateSimpleUploadData(kData));
3618 HttpRequestHeaders headers;
3619 headers.SetHeader(HttpRequestHeaders::kContentLength,
3620 base::UintToString(arraysize(kData) - 1));
3621 r->SetExtraRequestHeaders(headers);
3623 // Quit after hitting the redirect, so can check the headers.
3624 d.set_quit_on_redirect(true);
3626 base::RunLoop().Run();
3628 // Check headers from URLRequestJob.
3629 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3630 EXPECT_EQ(307, r->GetResponseCode());
3631 EXPECT_EQ(307, r->response_headers()->response_code());
3632 std::string location;
3633 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3635 EXPECT_EQ(redirect_url, GURL(location));
3637 // Let the request finish.
3638 r->FollowDeferredRedirect();
3639 base::RunLoop().Run();
3641 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3642 EXPECT_EQ(0, r->status().error());
3643 EXPECT_EQ(redirect_url, r->url());
3644 EXPECT_EQ(original_url, r->original_url());
3645 EXPECT_EQ(2U, r->url_chain().size());
3646 EXPECT_EQ(1, network_delegate.created_requests());
3647 EXPECT_EQ(0, network_delegate.destroyed_requests());
3648 EXPECT_EQ("POST", r->method());
3649 EXPECT_EQ(kData, d.data_received());
3651 EXPECT_EQ(1, network_delegate.destroyed_requests());
3654 // Tests that the network delegate can block and redirect a request to a new
3655 // URL during OnHeadersReceived.
3656 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3657 ASSERT_TRUE(test_server_.Start());
3660 BlockingNetworkDelegate network_delegate(
3661 BlockingNetworkDelegate::AUTO_CALLBACK);
3662 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3663 GURL redirect_url(test_server_.GetURL("simple.html"));
3664 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3666 TestURLRequestContextWithProxy context(
3667 test_server_.host_port_pair().ToString(), &network_delegate);
3670 GURL original_url(test_server_.GetURL("empty.html"));
3671 scoped_ptr<URLRequest> r(context.CreateRequest(
3672 original_url, DEFAULT_PRIORITY, &d, NULL));
3675 base::RunLoop().Run();
3677 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3678 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3680 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3682 network_delegate.last_observed_proxy().Equals(
3683 test_server_.host_port_pair()));
3685 EXPECT_EQ(OK, r->status().error());
3686 EXPECT_EQ(redirect_url, r->url());
3687 EXPECT_EQ(original_url, r->original_url());
3688 EXPECT_EQ(2U, r->url_chain().size());
3689 EXPECT_EQ(2, network_delegate.created_requests());
3690 EXPECT_EQ(0, network_delegate.destroyed_requests());
3692 EXPECT_EQ(1, network_delegate.destroyed_requests());
3695 // Tests that the network delegate can synchronously complete OnAuthRequired
3696 // by taking no action. This indicates that the NetworkDelegate does not want to
3697 // handle the challenge, and is passing the buck along to the
3698 // URLRequest::Delegate.
3699 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3700 ASSERT_TRUE(test_server_.Start());
3703 BlockingNetworkDelegate network_delegate(
3704 BlockingNetworkDelegate::SYNCHRONOUS);
3706 TestURLRequestContext context(true);
3707 context.set_network_delegate(&network_delegate);
3710 d.set_credentials(AuthCredentials(kUser, kSecret));
3713 GURL url(test_server_.GetURL("auth-basic"));
3714 scoped_ptr<URLRequest> r(context.CreateRequest(
3715 url, DEFAULT_PRIORITY, &d, NULL));
3718 base::RunLoop().Run();
3720 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3721 EXPECT_EQ(0, r->status().error());
3722 EXPECT_EQ(200, r->GetResponseCode());
3723 EXPECT_TRUE(d.auth_required_called());
3724 EXPECT_EQ(1, network_delegate.created_requests());
3725 EXPECT_EQ(0, network_delegate.destroyed_requests());
3727 EXPECT_EQ(1, network_delegate.destroyed_requests());
3730 TEST_F(URLRequestTestHTTP,
3731 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3732 ASSERT_TRUE(test_server_.Start());
3735 BlockingNetworkDelegate network_delegate(
3736 BlockingNetworkDelegate::SYNCHRONOUS);
3738 TestURLRequestContext context(true);
3739 context.set_network_delegate(&network_delegate);
3742 d.set_credentials(AuthCredentials(kUser, kSecret));
3745 GURL url(test_server_.GetURL("auth-basic"));
3746 scoped_ptr<URLRequest> r(context.CreateRequest(
3747 url, DEFAULT_PRIORITY, &d, NULL));
3751 HttpRequestHeaders headers;
3752 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3753 EXPECT_FALSE(headers.HasHeader("Authorization"));
3756 base::RunLoop().Run();
3758 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3759 EXPECT_EQ(0, r->status().error());
3760 EXPECT_EQ(200, r->GetResponseCode());
3761 EXPECT_TRUE(d.auth_required_called());
3762 EXPECT_EQ(1, network_delegate.created_requests());
3763 EXPECT_EQ(0, network_delegate.destroyed_requests());
3765 EXPECT_EQ(1, network_delegate.destroyed_requests());
3768 // Tests that the network delegate can synchronously complete OnAuthRequired
3769 // by setting credentials.
3770 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3771 ASSERT_TRUE(test_server_.Start());
3774 BlockingNetworkDelegate network_delegate(
3775 BlockingNetworkDelegate::SYNCHRONOUS);
3776 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3777 network_delegate.set_auth_retval(
3778 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3780 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3782 TestURLRequestContext context(true);
3783 context.set_network_delegate(&network_delegate);
3787 GURL url(test_server_.GetURL("auth-basic"));
3788 scoped_ptr<URLRequest> r(context.CreateRequest(
3789 url, DEFAULT_PRIORITY, &d, NULL));
3791 base::RunLoop().Run();
3793 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3794 EXPECT_EQ(0, r->status().error());
3795 EXPECT_EQ(200, r->GetResponseCode());
3796 EXPECT_FALSE(d.auth_required_called());
3797 EXPECT_EQ(1, network_delegate.created_requests());
3798 EXPECT_EQ(0, network_delegate.destroyed_requests());
3800 EXPECT_EQ(1, network_delegate.destroyed_requests());
3803 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3804 // headers (for the first or second request) when called at the proper times.
3805 TEST_F(URLRequestTestHTTP,
3806 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3807 ASSERT_TRUE(test_server_.Start());
3810 BlockingNetworkDelegate network_delegate(
3811 BlockingNetworkDelegate::SYNCHRONOUS);
3812 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3813 network_delegate.set_auth_retval(
3814 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3816 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3818 TestURLRequestContext context(true);
3819 context.set_network_delegate(&network_delegate);
3823 GURL url(test_server_.GetURL("auth-basic"));
3824 scoped_ptr<URLRequest> r(context.CreateRequest(
3825 url, DEFAULT_PRIORITY, &d, NULL));
3827 base::RunLoop().Run();
3829 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3830 EXPECT_EQ(0, r->status().error());
3831 EXPECT_EQ(200, r->GetResponseCode());
3832 EXPECT_FALSE(d.auth_required_called());
3833 EXPECT_EQ(1, network_delegate.created_requests());
3834 EXPECT_EQ(0, network_delegate.destroyed_requests());
3837 HttpRequestHeaders headers;
3838 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3839 EXPECT_TRUE(headers.HasHeader("Authorization"));
3842 EXPECT_EQ(1, network_delegate.destroyed_requests());
3845 // Tests that the network delegate can synchronously complete OnAuthRequired
3846 // by cancelling authentication.
3847 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3848 ASSERT_TRUE(test_server_.Start());
3851 BlockingNetworkDelegate network_delegate(
3852 BlockingNetworkDelegate::SYNCHRONOUS);
3853 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3854 network_delegate.set_auth_retval(
3855 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3857 TestURLRequestContext context(true);
3858 context.set_network_delegate(&network_delegate);
3862 GURL url(test_server_.GetURL("auth-basic"));
3863 scoped_ptr<URLRequest> r(context.CreateRequest(
3864 url, DEFAULT_PRIORITY, &d, NULL));
3866 base::RunLoop().Run();
3868 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3869 EXPECT_EQ(OK, r->status().error());
3870 EXPECT_EQ(401, r->GetResponseCode());
3871 EXPECT_FALSE(d.auth_required_called());
3872 EXPECT_EQ(1, network_delegate.created_requests());
3873 EXPECT_EQ(0, network_delegate.destroyed_requests());
3875 EXPECT_EQ(1, network_delegate.destroyed_requests());
3878 // Tests that the network delegate can asynchronously complete OnAuthRequired
3879 // by taking no action. This indicates that the NetworkDelegate does not want
3880 // to handle the challenge, and is passing the buck along to the
3881 // URLRequest::Delegate.
3882 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3883 ASSERT_TRUE(test_server_.Start());
3886 BlockingNetworkDelegate network_delegate(
3887 BlockingNetworkDelegate::AUTO_CALLBACK);
3888 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3890 TestURLRequestContext context(true);
3891 context.set_network_delegate(&network_delegate);
3894 d.set_credentials(AuthCredentials(kUser, kSecret));
3897 GURL url(test_server_.GetURL("auth-basic"));
3898 scoped_ptr<URLRequest> r(context.CreateRequest(
3899 url, DEFAULT_PRIORITY, &d, NULL));
3901 base::RunLoop().Run();
3903 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3904 EXPECT_EQ(0, r->status().error());
3905 EXPECT_EQ(200, r->GetResponseCode());
3906 EXPECT_TRUE(d.auth_required_called());
3907 EXPECT_EQ(1, network_delegate.created_requests());
3908 EXPECT_EQ(0, network_delegate.destroyed_requests());
3910 EXPECT_EQ(1, network_delegate.destroyed_requests());
3913 // Tests that the network delegate can asynchronously complete OnAuthRequired
3914 // by setting credentials.
3915 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3916 ASSERT_TRUE(test_server_.Start());
3919 BlockingNetworkDelegate network_delegate(
3920 BlockingNetworkDelegate::AUTO_CALLBACK);
3921 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3922 network_delegate.set_auth_retval(
3923 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3925 AuthCredentials auth_credentials(kUser, kSecret);
3926 network_delegate.set_auth_credentials(auth_credentials);
3928 TestURLRequestContext context(true);
3929 context.set_network_delegate(&network_delegate);
3933 GURL url(test_server_.GetURL("auth-basic"));
3934 scoped_ptr<URLRequest> r(context.CreateRequest(
3935 url, DEFAULT_PRIORITY, &d, NULL));
3937 base::RunLoop().Run();
3939 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3940 EXPECT_EQ(0, r->status().error());
3942 EXPECT_EQ(200, r->GetResponseCode());
3943 EXPECT_FALSE(d.auth_required_called());
3944 EXPECT_EQ(1, network_delegate.created_requests());
3945 EXPECT_EQ(0, network_delegate.destroyed_requests());
3947 EXPECT_EQ(1, network_delegate.destroyed_requests());
3950 // Tests that the network delegate can asynchronously complete OnAuthRequired
3951 // by cancelling authentication.
3952 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3953 ASSERT_TRUE(test_server_.Start());
3956 BlockingNetworkDelegate network_delegate(
3957 BlockingNetworkDelegate::AUTO_CALLBACK);
3958 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3959 network_delegate.set_auth_retval(
3960 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3962 TestURLRequestContext context(true);
3963 context.set_network_delegate(&network_delegate);
3967 GURL url(test_server_.GetURL("auth-basic"));
3968 scoped_ptr<URLRequest> r(context.CreateRequest(
3969 url, DEFAULT_PRIORITY, &d, NULL));
3971 base::RunLoop().Run();
3973 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3974 EXPECT_EQ(OK, r->status().error());
3975 EXPECT_EQ(401, r->GetResponseCode());
3976 EXPECT_FALSE(d.auth_required_called());
3977 EXPECT_EQ(1, network_delegate.created_requests());
3978 EXPECT_EQ(0, network_delegate.destroyed_requests());
3980 EXPECT_EQ(1, network_delegate.destroyed_requests());
3983 // Tests that we can handle when a network request was canceled while we were
3984 // waiting for the network delegate.
3985 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3986 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3987 ASSERT_TRUE(test_server_.Start());
3990 BlockingNetworkDelegate network_delegate(
3991 BlockingNetworkDelegate::USER_CALLBACK);
3992 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3994 TestURLRequestContext context(true);
3995 context.set_network_delegate(&network_delegate);
3999 scoped_ptr<URLRequest> r(context.CreateRequest(
4000 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4003 base::RunLoop().Run();
4004 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4005 network_delegate.stage_blocked_for_callback());
4006 EXPECT_EQ(0, network_delegate.completed_requests());
4007 // Cancel before callback.
4009 // Ensure that network delegate is notified.
4010 EXPECT_EQ(1, network_delegate.completed_requests());
4011 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4012 EXPECT_EQ(ERR_ABORTED, r->status().error());
4013 EXPECT_EQ(1, network_delegate.created_requests());
4014 EXPECT_EQ(0, network_delegate.destroyed_requests());
4016 EXPECT_EQ(1, network_delegate.destroyed_requests());
4019 // Tests that we can handle when a network request was canceled while we were
4020 // waiting for the network delegate.
4021 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4022 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
4023 ASSERT_TRUE(test_server_.Start());
4026 BlockingNetworkDelegate network_delegate(
4027 BlockingNetworkDelegate::USER_CALLBACK);
4028 network_delegate.set_block_on(
4029 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
4031 TestURLRequestContext context(true);
4032 context.set_network_delegate(&network_delegate);
4036 scoped_ptr<URLRequest> r(context.CreateRequest(
4037 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4040 base::RunLoop().Run();
4041 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4042 network_delegate.stage_blocked_for_callback());
4043 EXPECT_EQ(0, network_delegate.completed_requests());
4044 // Cancel before callback.
4046 // Ensure that network delegate is notified.
4047 EXPECT_EQ(1, network_delegate.completed_requests());
4048 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4049 EXPECT_EQ(ERR_ABORTED, r->status().error());
4050 EXPECT_EQ(1, network_delegate.created_requests());
4051 EXPECT_EQ(0, network_delegate.destroyed_requests());
4053 EXPECT_EQ(1, network_delegate.destroyed_requests());
4056 // Tests that we can handle when a network request was canceled while we were
4057 // waiting for the network delegate.
4058 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4059 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
4060 ASSERT_TRUE(test_server_.Start());
4063 BlockingNetworkDelegate network_delegate(
4064 BlockingNetworkDelegate::USER_CALLBACK);
4065 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4067 TestURLRequestContext context(true);
4068 context.set_network_delegate(&network_delegate);
4072 scoped_ptr<URLRequest> r(context.CreateRequest(
4073 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4076 base::RunLoop().Run();
4077 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4078 network_delegate.stage_blocked_for_callback());
4079 EXPECT_EQ(0, network_delegate.completed_requests());
4080 // Cancel before callback.
4082 // Ensure that network delegate is notified.
4083 EXPECT_EQ(1, network_delegate.completed_requests());
4084 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4085 EXPECT_EQ(ERR_ABORTED, r->status().error());
4086 EXPECT_EQ(1, network_delegate.created_requests());
4087 EXPECT_EQ(0, network_delegate.destroyed_requests());
4089 EXPECT_EQ(1, network_delegate.destroyed_requests());
4092 // Tests that we can handle when a network request was canceled while we were
4093 // waiting for the network delegate.
4094 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
4095 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
4096 ASSERT_TRUE(test_server_.Start());
4099 BlockingNetworkDelegate network_delegate(
4100 BlockingNetworkDelegate::USER_CALLBACK);
4101 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4103 TestURLRequestContext context(true);
4104 context.set_network_delegate(&network_delegate);
4108 scoped_ptr<URLRequest> r(context.CreateRequest(
4109 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
4112 base::RunLoop().Run();
4113 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4114 network_delegate.stage_blocked_for_callback());
4115 EXPECT_EQ(0, network_delegate.completed_requests());
4116 // Cancel before callback.
4118 // Ensure that network delegate is notified.
4119 EXPECT_EQ(1, network_delegate.completed_requests());
4120 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4121 EXPECT_EQ(ERR_ABORTED, r->status().error());
4122 EXPECT_EQ(1, network_delegate.created_requests());
4123 EXPECT_EQ(0, network_delegate.destroyed_requests());
4125 EXPECT_EQ(1, network_delegate.destroyed_requests());
4128 // In this unit test, we're using the HTTPTestServer as a proxy server and
4129 // issuing a CONNECT request with the magic host name "www.server-auth.com".
4130 // The HTTPTestServer will return a 401 response, which we should balk at.
4131 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
4132 ASSERT_TRUE(test_server_.Start());
4134 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4135 TestURLRequestContextWithProxy context(
4136 test_server_.host_port_pair().ToString(), &network_delegate);
4140 scoped_ptr<URLRequest> r(context.CreateRequest(
4141 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, NULL));
4144 EXPECT_TRUE(r->is_pending());
4146 base::RunLoop().Run();
4148 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4149 // The proxy server is not set before failure.
4150 EXPECT_TRUE(r->proxy_server().IsEmpty());
4151 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
4155 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
4156 ASSERT_TRUE(test_server_.Start());
4160 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4161 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4164 EXPECT_TRUE(r->is_pending());
4166 base::RunLoop().Run();
4168 EXPECT_EQ(1, d.response_started_count());
4169 EXPECT_FALSE(d.received_data_before_response());
4170 EXPECT_NE(0, d.bytes_received());
4171 EXPECT_EQ(test_server_.host_port_pair().host(),
4172 r->GetSocketAddress().host());
4173 EXPECT_EQ(test_server_.host_port_pair().port(),
4174 r->GetSocketAddress().port());
4176 // TODO(eroman): Add back the NetLog tests...
4180 // This test has the server send a large number of cookies to the client.
4181 // To ensure that no number of cookies causes a crash, a galloping binary
4182 // search is used to estimate that maximum number of cookies that are accepted
4183 // by the browser. Beyond the maximum number, the request will fail with
4184 // ERR_RESPONSE_HEADERS_TOO_BIG.
4186 // http://crbug.com/177916
4187 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4189 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4190 #endif // defined(OS_WIN)
4191 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
4192 ASSERT_TRUE(test_server_.Start());
4194 int lower_bound = 0;
4195 int upper_bound = 1;
4197 // Double the number of cookies until the response header limits are
4199 while (DoManyCookiesRequest(upper_bound)) {
4200 lower_bound = upper_bound;
4202 ASSERT_LT(upper_bound, 1000000);
4205 int tolerance = upper_bound * 0.005;
4209 // Perform a binary search to find the highest possible number of cookies,
4210 // within the desired tolerance.
4211 while (upper_bound - lower_bound >= tolerance) {
4212 int num_cookies = (lower_bound + upper_bound) / 2;
4214 if (DoManyCookiesRequest(num_cookies))
4215 lower_bound = num_cookies;
4217 upper_bound = num_cookies;
4219 // Success: the test did not crash.
4222 TEST_F(URLRequestTestHTTP, GetTest) {
4223 ASSERT_TRUE(test_server_.Start());
4227 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4228 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4231 EXPECT_TRUE(r->is_pending());
4233 base::RunLoop().Run();
4235 EXPECT_EQ(1, d.response_started_count());
4236 EXPECT_FALSE(d.received_data_before_response());
4237 EXPECT_NE(0, d.bytes_received());
4238 EXPECT_EQ(test_server_.host_port_pair().host(),
4239 r->GetSocketAddress().host());
4240 EXPECT_EQ(test_server_.host_port_pair().port(),
4241 r->GetSocketAddress().port());
4245 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
4246 ASSERT_TRUE(test_server_.Start());
4250 GURL test_url(test_server_.GetURL(std::string()));
4251 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4252 test_url, DEFAULT_PRIORITY, &d, NULL));
4254 HttpRequestHeaders headers;
4255 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
4258 EXPECT_TRUE(r->is_pending());
4260 base::RunLoop().Run();
4262 EXPECT_EQ(1, d.response_started_count());
4263 EXPECT_FALSE(d.received_data_before_response());
4264 EXPECT_NE(0, d.bytes_received());
4265 EXPECT_EQ(test_server_.host_port_pair().host(),
4266 r->GetSocketAddress().host());
4267 EXPECT_EQ(test_server_.host_port_pair().port(),
4268 r->GetSocketAddress().port());
4270 EXPECT_TRUE(d.have_full_request_headers());
4271 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4275 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
4276 ASSERT_TRUE(test_server_.Start());
4280 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4281 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4284 EXPECT_TRUE(r->is_pending());
4286 base::RunLoop().Run();
4288 LoadTimingInfo load_timing_info;
4289 r->GetLoadTimingInfo(&load_timing_info);
4290 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4292 EXPECT_EQ(1, d.response_started_count());
4293 EXPECT_FALSE(d.received_data_before_response());
4294 EXPECT_NE(0, d.bytes_received());
4295 EXPECT_EQ(test_server_.host_port_pair().host(),
4296 r->GetSocketAddress().host());
4297 EXPECT_EQ(test_server_.host_port_pair().port(),
4298 r->GetSocketAddress().port());
4302 TEST_F(URLRequestTestHTTP, GetZippedTest) {
4303 ASSERT_TRUE(test_server_.Start());
4305 // Parameter that specifies the Content-Length field in the response:
4306 // C - Compressed length.
4307 // U - Uncompressed length.
4308 // L - Large length (larger than both C & U).
4309 // M - Medium length (between C & U).
4310 // S - Small length (smaller than both C & U).
4311 const char test_parameters[] = "CULMS";
4312 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4313 // C & U should be OK.
4314 // L & M are larger than the data sent, and show an error.
4315 // S has too little data, but we seem to accept it.
4316 const bool test_expect_success[num_tests] =
4317 { true, true, false, false, true };
4319 for (int i = 0; i < num_tests ; i++) {
4322 std::string test_file =
4323 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4324 test_parameters[i]);
4326 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4327 TestURLRequestContext context(true);
4328 context.set_network_delegate(&network_delegate);
4331 scoped_ptr<URLRequest> r(context.CreateRequest(
4332 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, NULL));
4334 EXPECT_TRUE(r->is_pending());
4336 base::RunLoop().Run();
4338 EXPECT_EQ(1, d.response_started_count());
4339 EXPECT_FALSE(d.received_data_before_response());
4340 VLOG(1) << " Received " << d.bytes_received() << " bytes"
4341 << " status = " << r->status().status()
4342 << " error = " << r->status().error();
4343 if (test_expect_success[i]) {
4344 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
4345 << " Parameter = \"" << test_file << "\"";
4347 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4348 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
4349 << " Parameter = \"" << test_file << "\"";
4355 TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
4356 ASSERT_TRUE(test_server_.Start());
4358 SpawnedTestServer https_test_server(
4359 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
4360 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
4361 ASSERT_TRUE(https_test_server.Start());
4363 // An https server is sent a request with an https referer,
4364 // and responds with a redirect to an http url. The http
4365 // server should not be sent the referer.
4366 GURL http_destination = test_server_.GetURL(std::string());
4368 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4369 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
4370 DEFAULT_PRIORITY, &d, NULL));
4371 req->SetReferrer("https://www.referrer.com/");
4373 base::RunLoop().Run();
4375 EXPECT_EQ(1, d.response_started_count());
4376 EXPECT_EQ(1, d.received_redirect_count());
4377 EXPECT_EQ(http_destination, req->url());
4378 EXPECT_EQ(std::string(), req->referrer());
4381 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4382 ASSERT_TRUE(test_server_.Start());
4384 GURL destination_url = test_server_.GetURL(std::string());
4386 test_server_.GetURL("server-redirect?" + destination_url.spec());
4388 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4389 original_url, DEFAULT_PRIORITY, &d, NULL));
4391 base::RunLoop().Run();
4393 EXPECT_EQ(1, d.response_started_count());
4394 EXPECT_EQ(1, d.received_redirect_count());
4395 EXPECT_EQ(destination_url, req->url());
4396 EXPECT_EQ(original_url, req->original_url());
4397 ASSERT_EQ(2U, req->url_chain().size());
4398 EXPECT_EQ(original_url, req->url_chain()[0]);
4399 EXPECT_EQ(destination_url, req->url_chain()[1]);
4401 LoadTimingInfo load_timing_info_before_redirect;
4402 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4403 &load_timing_info_before_redirect));
4404 TestLoadTimingNotReused(load_timing_info_before_redirect,
4405 CONNECT_TIMING_HAS_DNS_TIMES);
4407 LoadTimingInfo load_timing_info;
4408 req->GetLoadTimingInfo(&load_timing_info);
4409 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4411 // Check that a new socket was used on redirect, since the server does not
4412 // supposed keep-alive sockets, and that the times before the redirect are
4413 // before the ones recorded for the second request.
4414 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4415 load_timing_info.socket_log_id);
4416 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4417 load_timing_info.connect_timing.connect_start);
4420 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4421 ASSERT_TRUE(test_server_.Start());
4423 GURL destination_url = test_server_.GetURL(std::string());
4424 GURL middle_redirect_url =
4425 test_server_.GetURL("server-redirect?" + destination_url.spec());
4426 GURL original_url = test_server_.GetURL(
4427 "server-redirect?" + middle_redirect_url.spec());
4429 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4430 original_url, DEFAULT_PRIORITY, &d, NULL));
4432 base::RunLoop().Run();
4434 EXPECT_EQ(1, d.response_started_count());
4435 EXPECT_EQ(2, d.received_redirect_count());
4436 EXPECT_EQ(destination_url, req->url());
4437 EXPECT_EQ(original_url, req->original_url());
4438 ASSERT_EQ(3U, req->url_chain().size());
4439 EXPECT_EQ(original_url, req->url_chain()[0]);
4440 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4441 EXPECT_EQ(destination_url, req->url_chain()[2]);
4444 // First and second pieces of information logged by delegates to URLRequests.
4445 const char kFirstDelegateInfo[] = "Wonderful delegate";
4446 const char kSecondDelegateInfo[] = "Exciting delegate";
4448 // Logs delegate information to a URLRequest. The first string is logged
4449 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4450 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4451 // another asynchronous call is used to clear the delegate information
4452 // before calling a callback. The object then deletes itself.
4453 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4455 typedef base::Callback<void()> Callback;
4457 // Each time delegate information is added to the URLRequest, the resulting
4458 // load state is checked. The expected load state after each request is
4459 // passed in as an argument.
4460 static void Run(URLRequest* url_request,
4461 LoadState expected_first_load_state,
4462 LoadState expected_second_load_state,
4463 LoadState expected_third_load_state,
4464 const Callback& callback) {
4465 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4467 expected_first_load_state,
4468 expected_second_load_state,
4469 expected_third_load_state,
4474 // Checks that the log entries, starting with log_position, contain the
4475 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4476 // recorded. Returns the index of entry after the expected number of
4477 // events this logged, or entries.size() if there aren't enough entries.
4478 static size_t CheckDelegateInfo(
4479 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
4480 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4481 if (log_position + 3 >= entries.size()) {
4482 ADD_FAILURE() << "Not enough log entries";
4483 return entries.size();
4485 std::string delegate_info;
4486 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4487 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4488 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4490 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4493 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4494 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4497 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4498 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4499 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4501 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4504 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4505 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4507 return log_position + 1;
4510 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4511 // Returns the position of the end message.
4512 static size_t ExpectBeforeNetworkEvents(
4513 const CapturingNetLog::CapturedEntryList& entries,
4514 size_t log_position) {
4516 ExpectLogContainsSomewhereAfter(entries,
4518 NetLog::TYPE_URL_REQUEST_DELEGATE,
4519 NetLog::PHASE_BEGIN);
4520 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4521 entries[log_position + 1].type);
4522 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4523 return log_position + 1;
4527 friend class base::RefCounted<AsyncDelegateLogger>;
4529 AsyncDelegateLogger(URLRequest* url_request,
4530 LoadState expected_first_load_state,
4531 LoadState expected_second_load_state,
4532 LoadState expected_third_load_state,
4533 const Callback& callback)
4534 : url_request_(url_request),
4535 expected_first_load_state_(expected_first_load_state),
4536 expected_second_load_state_(expected_second_load_state),
4537 expected_third_load_state_(expected_third_load_state),
4538 callback_(callback) {
4541 ~AsyncDelegateLogger() {}
4544 url_request_->LogBlockedBy(kFirstDelegateInfo);
4545 LoadStateWithParam load_state = url_request_->GetLoadState();
4546 EXPECT_EQ(expected_first_load_state_, load_state.state);
4547 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4548 base::MessageLoop::current()->PostTask(
4550 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4553 void LogSecondDelegate() {
4554 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
4555 LoadStateWithParam load_state = url_request_->GetLoadState();
4556 EXPECT_EQ(expected_second_load_state_, load_state.state);
4557 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4558 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4560 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4562 base::MessageLoop::current()->PostTask(
4564 base::Bind(&AsyncDelegateLogger::LogComplete, this));
4567 void LogComplete() {
4568 url_request_->LogUnblocked();
4569 LoadStateWithParam load_state = url_request_->GetLoadState();
4570 EXPECT_EQ(expected_third_load_state_, load_state.state);
4571 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
4572 EXPECT_EQ(base::string16(), load_state.param);
4576 URLRequest* url_request_;
4577 const int expected_first_load_state_;
4578 const int expected_second_load_state_;
4579 const int expected_third_load_state_;
4580 const Callback callback_;
4582 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4585 // NetworkDelegate that logs delegate information before a request is started,
4586 // before headers are sent, when headers are read, and when auth information
4587 // is requested. Uses AsyncDelegateLogger.
4588 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4590 AsyncLoggingNetworkDelegate() {}
4591 ~AsyncLoggingNetworkDelegate() override {}
4593 // NetworkDelegate implementation.
4594 int OnBeforeURLRequest(URLRequest* request,
4595 const CompletionCallback& callback,
4596 GURL* new_url) override {
4597 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4598 return RunCallbackAsynchronously(request, callback);
4601 int OnBeforeSendHeaders(URLRequest* request,
4602 const CompletionCallback& callback,
4603 HttpRequestHeaders* headers) override {
4604 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4605 return RunCallbackAsynchronously(request, callback);
4608 int OnHeadersReceived(
4609 URLRequest* request,
4610 const CompletionCallback& callback,
4611 const HttpResponseHeaders* original_response_headers,
4612 scoped_refptr<HttpResponseHeaders>* override_response_headers,
4613 GURL* allowed_unsafe_redirect_url) override {
4614 TestNetworkDelegate::OnHeadersReceived(request,
4616 original_response_headers,
4617 override_response_headers,
4618 allowed_unsafe_redirect_url);
4619 return RunCallbackAsynchronously(request, callback);
4622 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
4623 URLRequest* request,
4624 const AuthChallengeInfo& auth_info,
4625 const AuthCallback& callback,
4626 AuthCredentials* credentials) override {
4627 AsyncDelegateLogger::Run(
4629 LOAD_STATE_WAITING_FOR_DELEGATE,
4630 LOAD_STATE_WAITING_FOR_DELEGATE,
4631 LOAD_STATE_WAITING_FOR_DELEGATE,
4632 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4633 callback, credentials));
4634 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4638 static int RunCallbackAsynchronously(
4639 URLRequest* request,
4640 const CompletionCallback& callback) {
4641 AsyncDelegateLogger::Run(
4643 LOAD_STATE_WAITING_FOR_DELEGATE,
4644 LOAD_STATE_WAITING_FOR_DELEGATE,
4645 LOAD_STATE_WAITING_FOR_DELEGATE,
4646 base::Bind(callback, OK));
4647 return ERR_IO_PENDING;
4650 static void SetAuthAndResume(const AuthCallback& callback,
4651 AuthCredentials* credentials) {
4652 *credentials = AuthCredentials(kUser, kSecret);
4653 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4656 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4659 // URLRequest::Delegate that logs delegate information when the headers
4660 // are received, when each read completes, and during redirects. Uses
4661 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4663 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4664 // advancing to the next step in most cases, as well as cancellation.
4665 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4669 CANCEL_ON_RECEIVED_REDIRECT,
4670 CANCEL_ON_RESPONSE_STARTED,
4671 CANCEL_ON_READ_COMPLETED
4674 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4675 : cancel_stage_(cancel_stage) {
4676 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4677 set_cancel_in_received_redirect(true);
4678 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4679 set_cancel_in_response_started(true);
4680 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4681 set_cancel_in_received_data(true);
4683 ~AsyncLoggingUrlRequestDelegate() override {}
4685 // URLRequest::Delegate implementation:
4686 void OnReceivedRedirect(URLRequest* request,
4687 const RedirectInfo& redirect_info,
4688 bool* defer_redirect) override {
4689 *defer_redirect = true;
4690 AsyncDelegateLogger::Run(
4692 LOAD_STATE_WAITING_FOR_DELEGATE,
4693 LOAD_STATE_WAITING_FOR_DELEGATE,
4694 LOAD_STATE_WAITING_FOR_DELEGATE,
4696 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4697 base::Unretained(this), request, redirect_info));
4700 void OnResponseStarted(URLRequest* request) override {
4701 AsyncDelegateLogger::Run(
4703 LOAD_STATE_WAITING_FOR_DELEGATE,
4704 LOAD_STATE_WAITING_FOR_DELEGATE,
4705 LOAD_STATE_WAITING_FOR_DELEGATE,
4707 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4708 base::Unretained(this), request));
4711 void OnReadCompleted(URLRequest* request, int bytes_read) override {
4712 AsyncDelegateLogger::Run(
4718 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4719 base::Unretained(this), request, bytes_read));
4723 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4724 const RedirectInfo& redirect_info) {
4725 bool defer_redirect = false;
4726 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
4727 // FollowDeferredRedirect should not be called after cancellation.
4728 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4730 if (!defer_redirect)
4731 request->FollowDeferredRedirect();
4734 void OnResponseStartedLoggingComplete(URLRequest* request) {
4735 // The parent class continues the request.
4736 TestDelegate::OnResponseStarted(request);
4739 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4740 // The parent class continues the request.
4741 TestDelegate::OnReadCompleted(request, bytes_read);
4744 const CancelStage cancel_stage_;
4746 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4749 // Tests handling of delegate info before a request starts.
4750 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4751 ASSERT_TRUE(test_server_.Start());
4753 TestDelegate request_delegate;
4754 TestURLRequestContext context(true);
4755 context.set_network_delegate(NULL);
4756 context.set_net_log(&net_log_);
4760 scoped_ptr<URLRequest> r(context.CreateRequest(
4761 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &request_delegate,
4763 LoadStateWithParam load_state = r->GetLoadState();
4764 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4765 EXPECT_EQ(base::string16(), load_state.param);
4767 AsyncDelegateLogger::Run(
4769 LOAD_STATE_WAITING_FOR_DELEGATE,
4770 LOAD_STATE_WAITING_FOR_DELEGATE,
4772 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
4774 base::RunLoop().Run();
4776 EXPECT_EQ(200, r->GetResponseCode());
4777 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4780 CapturingNetLog::CapturedEntryList entries;
4781 net_log_.GetEntries(&entries);
4782 size_t log_position = ExpectLogContainsSomewhereAfter(
4785 NetLog::TYPE_DELEGATE_INFO,
4786 NetLog::PHASE_BEGIN);
4788 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4790 // Nothing else should add any delegate info to the request.
4791 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4792 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4795 // Tests handling of delegate info from a network delegate.
4796 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4797 ASSERT_TRUE(test_server_.Start());
4799 TestDelegate request_delegate;
4800 AsyncLoggingNetworkDelegate network_delegate;
4801 TestURLRequestContext context(true);
4802 context.set_network_delegate(&network_delegate);
4803 context.set_net_log(&net_log_);
4807 scoped_ptr<URLRequest> r(context.CreateRequest(
4808 test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &request_delegate,
4810 LoadStateWithParam load_state = r->GetLoadState();
4811 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4812 EXPECT_EQ(base::string16(), load_state.param);
4815 base::RunLoop().Run();
4817 EXPECT_EQ(200, r->GetResponseCode());
4818 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4819 EXPECT_EQ(1, network_delegate.created_requests());
4820 EXPECT_EQ(0, network_delegate.destroyed_requests());
4822 EXPECT_EQ(1, network_delegate.destroyed_requests());
4824 size_t log_position = 0;
4825 CapturingNetLog::CapturedEntryList entries;
4826 net_log_.GetEntries(&entries);
4827 for (size_t i = 0; i < 3; ++i) {
4828 log_position = ExpectLogContainsSomewhereAfter(
4831 NetLog::TYPE_URL_REQUEST_DELEGATE,
4832 NetLog::PHASE_BEGIN);
4834 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4837 ASSERT_LT(log_position, entries.size());
4838 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4839 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4842 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4843 entries, log_position + 1);
4847 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4848 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4851 // Tests handling of delegate info from a network delegate in the case of an
4853 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4854 ASSERT_TRUE(test_server_.Start());
4856 TestDelegate request_delegate;
4857 AsyncLoggingNetworkDelegate network_delegate;
4858 TestURLRequestContext context(true);
4859 context.set_network_delegate(&network_delegate);
4860 context.set_net_log(&net_log_);
4864 scoped_ptr<URLRequest> r(context.CreateRequest(
4865 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4866 &request_delegate, NULL));
4867 LoadStateWithParam load_state = r->GetLoadState();
4868 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4869 EXPECT_EQ(base::string16(), load_state.param);
4872 base::RunLoop().Run();
4874 EXPECT_EQ(200, r->GetResponseCode());
4875 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4876 EXPECT_EQ(2, network_delegate.created_requests());
4877 EXPECT_EQ(0, network_delegate.destroyed_requests());
4879 EXPECT_EQ(1, network_delegate.destroyed_requests());
4881 size_t log_position = 0;
4882 CapturingNetLog::CapturedEntryList entries;
4883 net_log_.GetEntries(&entries);
4884 // The NetworkDelegate logged information in OnBeforeURLRequest,
4885 // OnBeforeSendHeaders, and OnHeadersReceived.
4886 for (size_t i = 0; i < 3; ++i) {
4887 log_position = ExpectLogContainsSomewhereAfter(
4890 NetLog::TYPE_URL_REQUEST_DELEGATE,
4891 NetLog::PHASE_BEGIN);
4893 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4896 ASSERT_LT(log_position, entries.size());
4897 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4898 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4901 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4902 entries, log_position + 1);
4906 // The URLRequest::Delegate then gets informed about the redirect.
4907 log_position = ExpectLogContainsSomewhereAfter(
4910 NetLog::TYPE_URL_REQUEST_DELEGATE,
4911 NetLog::PHASE_BEGIN);
4913 // The NetworkDelegate logged information in the same three events as before.
4914 for (size_t i = 0; i < 3; ++i) {
4915 log_position = ExpectLogContainsSomewhereAfter(
4918 NetLog::TYPE_URL_REQUEST_DELEGATE,
4919 NetLog::PHASE_BEGIN);
4921 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4924 ASSERT_LT(log_position, entries.size());
4925 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4926 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4929 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4930 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4933 // Tests handling of delegate info from a network delegate in the case of HTTP
4935 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4936 ASSERT_TRUE(test_server_.Start());
4938 TestDelegate request_delegate;
4939 AsyncLoggingNetworkDelegate network_delegate;
4940 TestURLRequestContext context(true);
4941 context.set_network_delegate(&network_delegate);
4942 context.set_net_log(&net_log_);
4946 scoped_ptr<URLRequest> r(context.CreateRequest(
4947 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &request_delegate,
4949 LoadStateWithParam load_state = r->GetLoadState();
4950 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4951 EXPECT_EQ(base::string16(), load_state.param);
4954 base::RunLoop().Run();
4956 EXPECT_EQ(200, r->GetResponseCode());
4957 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4958 EXPECT_EQ(1, network_delegate.created_requests());
4959 EXPECT_EQ(0, network_delegate.destroyed_requests());
4961 EXPECT_EQ(1, network_delegate.destroyed_requests());
4963 size_t log_position = 0;
4964 CapturingNetLog::CapturedEntryList entries;
4965 net_log_.GetEntries(&entries);
4966 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4967 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4968 // OnBeforeURLRequest and OnBeforeSendHeaders.
4969 for (size_t i = 0; i < 6; ++i) {
4970 log_position = ExpectLogContainsSomewhereAfter(
4973 NetLog::TYPE_URL_REQUEST_DELEGATE,
4974 NetLog::PHASE_BEGIN);
4976 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4979 ASSERT_LT(log_position, entries.size());
4980 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4981 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4984 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4985 entries, log_position + 1);
4989 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4990 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4993 // Tests handling of delegate info from a URLRequest::Delegate.
4994 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4995 ASSERT_TRUE(test_server_.Start());
4997 AsyncLoggingUrlRequestDelegate request_delegate(
4998 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4999 TestURLRequestContext context(true);
5000 context.set_network_delegate(NULL);
5001 context.set_net_log(&net_log_);
5005 // A chunked response with delays between chunks is used to make sure that
5006 // attempts by the URLRequest delegate to log information while reading the
5007 // body are ignored. Since they are ignored, this test is robust against
5008 // the possibility of multiple reads being combined in the unlikely event
5010 scoped_ptr<URLRequest> r(context.CreateRequest(
5011 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
5012 &request_delegate, NULL));
5013 LoadStateWithParam load_state = r->GetLoadState();
5015 base::RunLoop().Run();
5017 EXPECT_EQ(200, r->GetResponseCode());
5018 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5021 CapturingNetLog::CapturedEntryList entries;
5022 net_log_.GetEntries(&entries);
5024 size_t log_position = 0;
5026 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5027 entries, log_position);
5029 // The delegate info should only have been logged on header complete. Other
5030 // times it should silently be ignored.
5032 ExpectLogContainsSomewhereAfter(entries,
5034 NetLog::TYPE_URL_REQUEST_DELEGATE,
5035 NetLog::PHASE_BEGIN);
5037 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5040 ASSERT_LT(log_position, entries.size());
5041 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5042 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5044 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5045 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5046 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5047 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5050 // Tests handling of delegate info from a URLRequest::Delegate in the case of
5051 // an HTTP redirect.
5052 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
5053 ASSERT_TRUE(test_server_.Start());
5055 AsyncLoggingUrlRequestDelegate request_delegate(
5056 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5057 TestURLRequestContext context(true);
5058 context.set_network_delegate(NULL);
5059 context.set_net_log(&net_log_);
5063 scoped_ptr<URLRequest> r(context.CreateRequest(
5064 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
5065 &request_delegate, NULL));
5066 LoadStateWithParam load_state = r->GetLoadState();
5068 base::RunLoop().Run();
5070 EXPECT_EQ(200, r->GetResponseCode());
5071 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5074 CapturingNetLog::CapturedEntryList entries;
5075 net_log_.GetEntries(&entries);
5077 // Delegate info should only have been logged in OnReceivedRedirect and
5078 // OnResponseStarted.
5079 size_t log_position = 0;
5080 for (int i = 0; i < 2; ++i) {
5082 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5083 entries, log_position) + 1;
5086 log_position = ExpectLogContainsSomewhereAfter(
5089 NetLog::TYPE_URL_REQUEST_DELEGATE,
5090 NetLog::PHASE_BEGIN);
5092 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5095 ASSERT_LT(log_position, entries.size());
5096 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5097 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5100 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5101 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5102 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5103 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5106 // Tests handling of delegate info from a URLRequest::Delegate in the case of
5107 // an HTTP redirect, with cancellation at various points.
5108 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
5109 ASSERT_TRUE(test_server_.Start());
5111 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5112 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5113 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5114 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5117 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5119 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5120 TestURLRequestContext context(true);
5121 CapturingNetLog net_log;
5122 context.set_network_delegate(NULL);
5123 context.set_net_log(&net_log);
5127 scoped_ptr<URLRequest> r(context.CreateRequest(
5128 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
5129 &request_delegate, NULL));
5130 LoadStateWithParam load_state = r->GetLoadState();
5132 base::RunLoop().Run();
5133 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5136 CapturingNetLog::CapturedEntryList entries;
5137 net_log.GetEntries(&entries);
5139 // Delegate info is always logged in both OnReceivedRedirect and
5140 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5141 // OnResponseStarted delegate call is after cancellation, but logging is
5142 // still currently supported in that call.
5143 size_t log_position = 0;
5144 for (int i = 0; i < 2; ++i) {
5146 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5147 entries, log_position) + 1;
5150 log_position = ExpectLogContainsSomewhereAfter(
5153 NetLog::TYPE_URL_REQUEST_DELEGATE,
5154 NetLog::PHASE_BEGIN);
5156 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5159 ASSERT_LT(log_position, entries.size());
5160 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5161 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5164 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5165 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5166 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5167 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5173 const char kExtraHeader[] = "Allow-Snafu";
5174 const char kExtraValue[] = "fubar";
5176 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
5177 void OnReceivedRedirect(URLRequest* request,
5178 const RedirectInfo& redirect_info,
5179 bool* defer_redirect) override {
5180 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
5181 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5187 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
5188 ASSERT_TRUE(test_server_.Start());
5190 GURL destination_url = test_server_.GetURL(
5191 "echoheader?" + std::string(kExtraHeader));
5192 GURL original_url = test_server_.GetURL(
5193 "server-redirect?" + destination_url.spec());
5194 RedirectWithAdditionalHeadersDelegate d;
5195 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5196 original_url, DEFAULT_PRIORITY, &d, NULL));
5198 base::RunLoop().Run();
5201 const HttpRequestHeaders& headers = req->extra_request_headers();
5202 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5203 EXPECT_EQ(kExtraValue, value);
5204 EXPECT_FALSE(req->is_pending());
5205 EXPECT_FALSE(req->is_redirecting());
5206 EXPECT_EQ(kExtraValue, d.data_received());
5211 const char kExtraHeaderToRemove[] = "To-Be-Removed";
5213 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
5214 void OnReceivedRedirect(URLRequest* request,
5215 const RedirectInfo& redirect_info,
5216 bool* defer_redirect) override {
5217 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
5218 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5224 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
5225 ASSERT_TRUE(test_server_.Start());
5227 GURL destination_url = test_server_.GetURL(
5228 "echoheader?" + std::string(kExtraHeaderToRemove));
5229 GURL original_url = test_server_.GetURL(
5230 "server-redirect?" + destination_url.spec());
5231 RedirectWithHeaderRemovalDelegate d;
5232 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5233 original_url, DEFAULT_PRIORITY, &d, NULL));
5234 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5236 base::RunLoop().Run();
5239 const HttpRequestHeaders& headers = req->extra_request_headers();
5240 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
5241 EXPECT_FALSE(req->is_pending());
5242 EXPECT_FALSE(req->is_redirecting());
5243 EXPECT_EQ("None", d.data_received());
5246 TEST_F(URLRequestTestHTTP, CancelTest) {
5249 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5250 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d, NULL));
5253 EXPECT_TRUE(r->is_pending());
5257 base::RunLoop().Run();
5259 // We expect to receive OnResponseStarted even though the request has been
5261 EXPECT_EQ(1, d.response_started_count());
5262 EXPECT_EQ(0, d.bytes_received());
5263 EXPECT_FALSE(d.received_data_before_response());
5267 TEST_F(URLRequestTestHTTP, CancelTest2) {
5268 ASSERT_TRUE(test_server_.Start());
5272 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5273 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
5275 d.set_cancel_in_response_started(true);
5278 EXPECT_TRUE(r->is_pending());
5280 base::RunLoop().Run();
5282 EXPECT_EQ(1, d.response_started_count());
5283 EXPECT_EQ(0, d.bytes_received());
5284 EXPECT_FALSE(d.received_data_before_response());
5285 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5289 TEST_F(URLRequestTestHTTP, CancelTest3) {
5290 ASSERT_TRUE(test_server_.Start());
5294 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5295 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
5297 d.set_cancel_in_received_data(true);
5300 EXPECT_TRUE(r->is_pending());
5302 base::RunLoop().Run();
5304 EXPECT_EQ(1, d.response_started_count());
5305 // There is no guarantee about how much data was received
5306 // before the cancel was issued. It could have been 0 bytes,
5307 // or it could have been all the bytes.
5308 // EXPECT_EQ(0, d.bytes_received());
5309 EXPECT_FALSE(d.received_data_before_response());
5310 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5314 TEST_F(URLRequestTestHTTP, CancelTest4) {
5315 ASSERT_TRUE(test_server_.Start());
5319 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5320 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
5323 EXPECT_TRUE(r->is_pending());
5325 // The request will be implicitly canceled when it is destroyed. The
5326 // test delegate must not post a quit message when this happens because
5327 // this test doesn't actually have a message loop. The quit message would
5328 // get put on this thread's message queue and the next test would exit
5329 // early, causing problems.
5330 d.set_quit_on_complete(false);
5332 // expect things to just cleanup properly.
5334 // we won't actually get a received reponse here because we've never run the
5336 EXPECT_FALSE(d.received_data_before_response());
5337 EXPECT_EQ(0, d.bytes_received());
5340 TEST_F(URLRequestTestHTTP, CancelTest5) {
5341 ASSERT_TRUE(test_server_.Start());
5346 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5347 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
5349 base::RunLoop().Run();
5350 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5353 // cancel read from cache (see bug 990242)
5356 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5357 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
5360 base::RunLoop().Run();
5362 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5363 EXPECT_EQ(1, d.response_started_count());
5364 EXPECT_EQ(0, d.bytes_received());
5365 EXPECT_FALSE(d.received_data_before_response());
5369 TEST_F(URLRequestTestHTTP, PostTest) {
5370 ASSERT_TRUE(test_server_.Start());
5371 HTTPUploadDataOperationTest("POST");
5374 TEST_F(URLRequestTestHTTP, PutTest) {
5375 ASSERT_TRUE(test_server_.Start());
5376 HTTPUploadDataOperationTest("PUT");
5379 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5380 ASSERT_TRUE(test_server_.Start());
5384 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5385 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5386 r->set_method("POST");
5389 EXPECT_TRUE(r->is_pending());
5391 base::RunLoop().Run();
5393 ASSERT_EQ(1, d.response_started_count())
5394 << "request failed: " << r->status().status()
5395 << ", error: " << r->status().error();
5397 EXPECT_FALSE(d.received_data_before_response());
5398 EXPECT_TRUE(d.data_received().empty());
5402 TEST_F(URLRequestTestHTTP, PostFileTest) {
5403 ASSERT_TRUE(test_server_.Start());
5407 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5408 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5409 r->set_method("POST");
5412 PathService::Get(base::DIR_EXE, &dir);
5413 base::SetCurrentDirectory(dir);
5415 ScopedVector<UploadElementReader> element_readers;
5417 base::FilePath path;
5418 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5419 path = path.Append(FILE_PATH_LITERAL("net"));
5420 path = path.Append(FILE_PATH_LITERAL("data"));
5421 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5422 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5423 element_readers.push_back(
5424 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5429 r->set_upload(make_scoped_ptr<UploadDataStream>(
5430 new ElementsUploadDataStream(element_readers.Pass(), 0)));
5433 EXPECT_TRUE(r->is_pending());
5435 base::RunLoop().Run();
5438 ASSERT_EQ(true, base::GetFileSize(path, &size));
5439 scoped_ptr<char[]> buf(new char[size]);
5441 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
5443 ASSERT_EQ(1, d.response_started_count())
5444 << "request failed: " << r->status().status()
5445 << ", error: " << r->status().error();
5447 EXPECT_FALSE(d.received_data_before_response());
5449 EXPECT_EQ(size, d.bytes_received());
5450 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
5454 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5455 ASSERT_TRUE(test_server_.Start());
5459 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5460 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5461 r->set_method("POST");
5463 ScopedVector<UploadElementReader> element_readers;
5465 element_readers.push_back(new UploadFileElementReader(
5466 base::MessageLoopProxy::current().get(),
5467 base::FilePath(FILE_PATH_LITERAL(
5468 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5472 r->set_upload(make_scoped_ptr<UploadDataStream>(
5473 new ElementsUploadDataStream(element_readers.Pass(), 0)));
5476 EXPECT_TRUE(r->is_pending());
5478 base::RunLoop().Run();
5480 EXPECT_TRUE(d.request_failed());
5481 EXPECT_FALSE(d.received_data_before_response());
5482 EXPECT_EQ(0, d.bytes_received());
5483 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5484 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
5488 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5489 ASSERT_TRUE(test_server_.Start());
5493 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5494 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5495 r->EnableChunkedUpload();
5496 r->set_method("POST");
5497 AddChunksToUpload(r.get());
5499 EXPECT_TRUE(r->is_pending());
5501 base::RunLoop().Run();
5503 VerifyReceivedDataMatchesChunks(r.get(), &d);
5507 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5508 ASSERT_TRUE(test_server_.Start());
5512 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5513 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5514 r->EnableChunkedUpload();
5515 r->set_method("POST");
5517 EXPECT_TRUE(r->is_pending());
5518 AddChunksToUpload(r.get());
5519 base::RunLoop().Run();
5521 VerifyReceivedDataMatchesChunks(r.get(), &d);
5525 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5526 ASSERT_TRUE(test_server_.Start());
5530 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5531 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5532 r->EnableChunkedUpload();
5533 r->set_method("POST");
5535 EXPECT_TRUE(r->is_pending());
5537 base::RunLoop().RunUntilIdle();
5538 AddChunksToUpload(r.get());
5539 base::RunLoop().Run();
5541 VerifyReceivedDataMatchesChunks(r.get(), &d);
5545 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5546 ASSERT_TRUE(test_server_.Start());
5549 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5550 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d,
5553 base::RunLoop().Run();
5555 const HttpResponseHeaders* headers = req->response_headers();
5557 // Simple sanity check that response_info() accesses the same data.
5558 EXPECT_EQ(headers, req->response_info().headers.get());
5561 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5562 EXPECT_EQ("private", header);
5565 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5566 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5568 // The response has two "X-Multiple-Entries" headers.
5569 // This verfies our output has them concatenated together.
5571 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5572 EXPECT_EQ("a, b", header);
5575 TEST_F(URLRequestTestHTTP, ProcessSTS) {
5576 SpawnedTestServer::SSLOptions ssl_options;
5577 SpawnedTestServer https_test_server(
5578 SpawnedTestServer::TYPE_HTTPS,
5580 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5581 ASSERT_TRUE(https_test_server.Start());
5584 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5585 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY, &d,
5588 base::RunLoop().Run();
5590 TransportSecurityState* security_state =
5591 default_context_.transport_security_state();
5592 TransportSecurityState::DomainState domain_state;
5593 EXPECT_TRUE(security_state->GetDynamicDomainState(
5594 SpawnedTestServer::kLocalhost, &domain_state));
5595 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5596 domain_state.sts.upgrade_mode);
5597 EXPECT_TRUE(domain_state.sts.include_subdomains);
5598 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5599 #if defined(OS_ANDROID)
5600 // Android's CertVerifyProc does not (yet) handle pins.
5602 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5606 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5607 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5608 // DomainState present because header rejected).
5609 #if defined(OS_ANDROID)
5610 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5612 #define MAYBE_ProcessPKP ProcessPKP
5615 // Tests that enabling HPKP on a domain does not affect the HSTS
5616 // validity/expiration.
5617 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5618 SpawnedTestServer::SSLOptions ssl_options;
5619 SpawnedTestServer https_test_server(
5620 SpawnedTestServer::TYPE_HTTPS,
5622 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5623 ASSERT_TRUE(https_test_server.Start());
5626 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5627 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
5630 base::RunLoop().Run();
5632 TransportSecurityState* security_state =
5633 default_context_.transport_security_state();
5634 TransportSecurityState::DomainState domain_state;
5635 EXPECT_TRUE(security_state->GetDynamicDomainState(
5636 SpawnedTestServer::kLocalhost, &domain_state));
5637 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5638 domain_state.sts.upgrade_mode);
5639 EXPECT_FALSE(domain_state.sts.include_subdomains);
5640 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5641 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5642 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5645 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5646 SpawnedTestServer::SSLOptions ssl_options;
5647 SpawnedTestServer https_test_server(
5648 SpawnedTestServer::TYPE_HTTPS,
5650 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5651 ASSERT_TRUE(https_test_server.Start());
5654 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5655 https_test_server.GetURL("files/hsts-multiple-headers.html"),
5656 DEFAULT_PRIORITY, &d, NULL));
5658 base::RunLoop().Run();
5660 // We should have set parameters from the first header, not the second.
5661 TransportSecurityState* security_state =
5662 default_context_.transport_security_state();
5663 TransportSecurityState::DomainState domain_state;
5664 EXPECT_TRUE(security_state->GetDynamicDomainState(
5665 SpawnedTestServer::kLocalhost, &domain_state));
5666 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5667 domain_state.sts.upgrade_mode);
5668 EXPECT_FALSE(domain_state.sts.include_subdomains);
5669 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5672 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5673 SpawnedTestServer::SSLOptions ssl_options;
5674 SpawnedTestServer https_test_server(
5675 SpawnedTestServer::TYPE_HTTPS,
5677 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5678 ASSERT_TRUE(https_test_server.Start());
5681 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5682 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5683 DEFAULT_PRIORITY, &d, NULL));
5685 base::RunLoop().Run();
5687 // We should have set parameters from the first header, not the second.
5688 TransportSecurityState* security_state =
5689 default_context_.transport_security_state();
5690 TransportSecurityState::DomainState domain_state;
5691 EXPECT_TRUE(security_state->GetDynamicDomainState(
5692 SpawnedTestServer::kLocalhost, &domain_state));
5693 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5694 domain_state.sts.upgrade_mode);
5695 #if defined(OS_ANDROID)
5696 // Android's CertVerifyProc does not (yet) handle pins.
5698 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5700 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5702 // Even though there is an HSTS header asserting includeSubdomains, it is
5703 // the *second* such header, and we MUST process only the first.
5704 EXPECT_FALSE(domain_state.sts.include_subdomains);
5705 // includeSubdomains does not occur in the test HPKP header.
5706 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5709 // Tests that when multiple HPKP headers are present, asserting different
5710 // policies, that only the first such policy is processed.
5711 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5712 SpawnedTestServer::SSLOptions ssl_options;
5713 SpawnedTestServer https_test_server(
5714 SpawnedTestServer::TYPE_HTTPS,
5716 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5717 ASSERT_TRUE(https_test_server.Start());
5720 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5721 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5722 DEFAULT_PRIORITY, &d, NULL));
5724 base::RunLoop().Run();
5726 TransportSecurityState* security_state =
5727 default_context_.transport_security_state();
5728 TransportSecurityState::DomainState domain_state;
5729 EXPECT_TRUE(security_state->GetDynamicDomainState(
5730 SpawnedTestServer::kLocalhost, &domain_state));
5731 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5732 domain_state.sts.upgrade_mode);
5733 #if defined(OS_ANDROID)
5734 // Android's CertVerifyProc does not (yet) handle pins.
5736 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5738 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5740 EXPECT_TRUE(domain_state.sts.include_subdomains);
5741 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5744 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5745 ASSERT_TRUE(test_server_.Start());
5748 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5749 test_server_.GetURL("files/content-type-normalization.html"),
5750 DEFAULT_PRIORITY, &d, NULL));
5752 base::RunLoop().Run();
5754 std::string mime_type;
5755 req->GetMimeType(&mime_type);
5756 EXPECT_EQ("text/html", mime_type);
5758 std::string charset;
5759 req->GetCharset(&charset);
5760 EXPECT_EQ("utf-8", charset);
5764 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
5765 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5766 GURL data_url("data:,foo");
5767 DataProtocolHandler data_protocol_handler;
5768 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5770 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5771 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
5774 #if !defined(DISABLE_FILE_SUPPORT)
5775 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5776 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5777 GURL file_url("file:///foo.txt");
5778 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5779 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5781 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5782 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
5785 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5786 ASSERT_TRUE(test_server_.Start());
5789 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5790 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY, &d,
5793 base::RunLoop().Run();
5795 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5796 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5798 #endif // !defined(DISABLE_FILE_SUPPORT)
5800 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5801 ASSERT_TRUE(test_server_.Start());
5804 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5805 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY, &d,
5808 base::MessageLoop::current()->Run();
5810 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5811 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5814 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5815 ASSERT_TRUE(test_server_.Start());
5818 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5819 test_server_.GetURL("files/redirect-to-invalid-url.html"),
5820 DEFAULT_PRIORITY, &d, NULL));
5822 base::RunLoop().Run();
5824 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5825 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
5828 // Make sure redirects are cached, despite not reading their bodies.
5829 TEST_F(URLRequestTestHTTP, CacheRedirect) {
5830 ASSERT_TRUE(test_server_.Start());
5832 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5836 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5837 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5839 base::RunLoop().Run();
5840 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5841 EXPECT_EQ(1, d.received_redirect_count());
5842 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5847 d.set_quit_on_redirect(true);
5848 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5849 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5851 base::RunLoop().Run();
5853 EXPECT_EQ(1, d.received_redirect_count());
5854 EXPECT_EQ(0, d.response_started_count());
5855 EXPECT_TRUE(req->was_cached());
5857 req->FollowDeferredRedirect();
5858 base::RunLoop().Run();
5859 EXPECT_EQ(1, d.received_redirect_count());
5860 EXPECT_EQ(1, d.response_started_count());
5861 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5862 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5866 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5867 // when the headers are read, since the body won't have been read.
5868 TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5869 ASSERT_TRUE(test_server_.Start());
5870 // URL that is normally cached.
5871 GURL initial_url = test_server_.GetURL("cachetime");
5874 // Set up the TestNetworkDelegate tp force a redirect.
5875 GURL redirect_to_url = test_server_.GetURL("echo");
5876 default_network_delegate_.set_redirect_on_headers_received_url(
5880 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5881 initial_url, DEFAULT_PRIORITY, &d, NULL));
5883 base::RunLoop().Run();
5884 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5885 EXPECT_EQ(1, d.received_redirect_count());
5886 EXPECT_EQ(redirect_to_url, req->url());
5891 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5892 initial_url, DEFAULT_PRIORITY, &d, NULL));
5894 base::RunLoop().Run();
5896 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5897 EXPECT_FALSE(req->was_cached());
5898 EXPECT_EQ(0, d.received_redirect_count());
5899 EXPECT_EQ(initial_url, req->url());
5903 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5905 TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5906 ASSERT_TRUE(test_server_.Start());
5908 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5909 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5910 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5914 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5915 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
5918 base::RunLoop().Run();
5920 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5922 EXPECT_EQ(2U, r->url_chain().size());
5923 EXPECT_EQ(OK, r->status().error());
5924 EXPECT_EQ(unsafe_url, r->url());
5925 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5929 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5930 // some other URL to the whitelist.
5931 TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5932 ASSERT_TRUE(test_server_.Start());
5934 GURL unsafe_url("data:text/html,something");
5935 GURL different_unsafe_url("data:text/html,something-else");
5936 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5937 default_network_delegate_.set_allowed_unsafe_redirect_url(
5938 different_unsafe_url);
5942 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5943 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
5946 base::RunLoop().Run();
5948 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5949 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
5953 // Redirects from an URL with fragment to an unsafe URL with fragment should
5954 // be allowed, and the reference fragment of the target URL should be preserved.
5955 TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5956 ASSERT_TRUE(test_server_.Start());
5958 GURL original_url(test_server_.GetURL("original#fragment1"));
5959 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5960 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5962 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5963 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5967 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5968 original_url, DEFAULT_PRIORITY, &d, NULL));
5971 base::RunLoop().Run();
5973 EXPECT_EQ(2U, r->url_chain().size());
5974 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5975 EXPECT_EQ(OK, r->status().error());
5976 EXPECT_EQ(original_url, r->original_url());
5977 EXPECT_EQ(expected_url, r->url());
5981 // When a delegate has specified a safe redirect URL, but it does not match the
5982 // redirect target, then do not prevent the reference fragment from being added.
5983 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
5984 ASSERT_TRUE(test_server_.Start());
5986 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5987 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5988 GURL redirect_url(test_server_.GetURL("target"));
5989 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5991 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5992 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5996 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5997 original_url, DEFAULT_PRIORITY, &d, NULL));
6000 base::RunLoop().Run();
6002 EXPECT_EQ(2U, r->url_chain().size());
6003 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6004 EXPECT_EQ(OK, r->status().error());
6005 EXPECT_EQ(original_url, r->original_url());
6006 EXPECT_EQ(expected_redirect_url, r->url());
6010 // When a delegate has specified a safe redirect URL, assume that the redirect
6011 // URL should not be changed. In particular, the reference fragment should not
6013 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
6014 ASSERT_TRUE(test_server_.Start());
6016 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6017 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6019 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6020 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6024 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6025 original_url, DEFAULT_PRIORITY, &d, NULL));
6028 base::RunLoop().Run();
6030 EXPECT_EQ(2U, r->url_chain().size());
6031 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6032 EXPECT_EQ(OK, r->status().error());
6033 EXPECT_EQ(original_url, r->original_url());
6034 EXPECT_EQ(redirect_url, r->url());
6038 // When a URLRequestRedirectJob is created, the redirection must be followed and
6039 // the reference fragment of the target URL must not be modified.
6040 TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
6041 ASSERT_TRUE(test_server_.Start());
6043 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6044 GURL redirect_url(test_server_.GetURL("echo"));
6047 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6048 original_url, DEFAULT_PRIORITY, &d, NULL));
6050 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6051 r.get(), &default_network_delegate_, redirect_url,
6052 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6053 AddTestInterceptor()->set_main_intercept_job(job);
6056 base::RunLoop().Run();
6058 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6059 EXPECT_EQ(OK, r->status().error());
6060 EXPECT_EQ(original_url, r->original_url());
6061 EXPECT_EQ(redirect_url, r->url());
6064 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
6065 ASSERT_TRUE(test_server_.Start());
6068 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6069 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6070 req->SetReferrer("http://user:pass@foo.com/");
6072 base::RunLoop().Run();
6074 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6077 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
6078 ASSERT_TRUE(test_server_.Start());
6081 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6082 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6083 req->SetReferrer("http://foo.com/test#fragment");
6085 base::RunLoop().Run();
6087 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6090 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
6091 ASSERT_TRUE(test_server_.Start());
6094 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6095 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6096 req->SetReferrer("http://foo.com/test#fragment");
6097 req->SetReferrer("");
6099 base::RunLoop().Run();
6101 EXPECT_EQ(std::string("None"), d.data_received());
6104 // Defer network start and then resume, checking that the request was a success
6105 // and bytes were received.
6106 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
6107 ASSERT_TRUE(test_server_.Start());
6111 d.set_quit_on_network_start(true);
6112 GURL test_url(test_server_.GetURL("echo"));
6113 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6114 test_url, DEFAULT_PRIORITY, &d, NULL));
6117 base::RunLoop().Run();
6119 EXPECT_EQ(1, d.received_before_network_start_count());
6120 EXPECT_EQ(0, d.response_started_count());
6122 req->ResumeNetworkStart();
6123 base::RunLoop().Run();
6125 EXPECT_EQ(1, d.response_started_count());
6126 EXPECT_NE(0, d.bytes_received());
6127 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6131 // Check that OnBeforeNetworkStart is only called once even if there is a
6133 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
6134 ASSERT_TRUE(test_server_.Start());
6138 d.set_quit_on_redirect(true);
6139 d.set_quit_on_network_start(true);
6140 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6141 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d,
6145 base::RunLoop().Run();
6147 EXPECT_EQ(1, d.received_before_network_start_count());
6148 EXPECT_EQ(0, d.response_started_count());
6149 EXPECT_EQ(0, d.received_redirect_count());
6151 req->ResumeNetworkStart();
6152 base::RunLoop().Run();
6154 EXPECT_EQ(1, d.received_redirect_count());
6155 req->FollowDeferredRedirect();
6156 base::RunLoop().Run();
6158 // Check that the redirect's new network transaction does not get propagated
6159 // to a second OnBeforeNetworkStart() notification.
6160 EXPECT_EQ(1, d.received_before_network_start_count());
6162 EXPECT_EQ(1, d.response_started_count());
6163 EXPECT_NE(0, d.bytes_received());
6164 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6168 // Cancel the request after learning that the request would use the network.
6169 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
6170 ASSERT_TRUE(test_server_.Start());
6174 d.set_quit_on_network_start(true);
6175 GURL test_url(test_server_.GetURL("echo"));
6176 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6177 test_url, DEFAULT_PRIORITY, &d, NULL));
6180 base::RunLoop().Run();
6182 EXPECT_EQ(1, d.received_before_network_start_count());
6183 EXPECT_EQ(0, d.response_started_count());
6186 base::RunLoop().Run();
6188 EXPECT_EQ(1, d.response_started_count());
6189 EXPECT_EQ(0, d.bytes_received());
6190 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
6194 TEST_F(URLRequestTestHTTP, CancelRedirect) {
6195 ASSERT_TRUE(test_server_.Start());
6199 d.set_cancel_in_received_redirect(true);
6200 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6201 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
6204 base::RunLoop().Run();
6206 EXPECT_EQ(1, d.response_started_count());
6207 EXPECT_EQ(0, d.bytes_received());
6208 EXPECT_FALSE(d.received_data_before_response());
6209 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
6213 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6214 ASSERT_TRUE(test_server_.Start());
6218 d.set_quit_on_redirect(true);
6219 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
6220 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6221 test_url, DEFAULT_PRIORITY, &d, NULL));
6224 base::RunLoop().Run();
6226 EXPECT_EQ(1, d.received_redirect_count());
6228 req->FollowDeferredRedirect();
6229 base::RunLoop().Run();
6231 EXPECT_EQ(1, d.response_started_count());
6232 EXPECT_FALSE(d.received_data_before_response());
6233 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6235 base::FilePath path;
6236 PathService::Get(base::DIR_SOURCE_ROOT, &path);
6237 path = path.Append(FILE_PATH_LITERAL("net"));
6238 path = path.Append(FILE_PATH_LITERAL("data"));
6239 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6240 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6242 std::string contents;
6243 EXPECT_TRUE(base::ReadFileToString(path, &contents));
6244 EXPECT_EQ(contents, d.data_received());
6248 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6249 ASSERT_TRUE(test_server_.Start());
6253 d.set_quit_on_redirect(true);
6254 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
6255 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6256 test_url, DEFAULT_PRIORITY, &d, NULL));
6258 EXPECT_FALSE(d.have_full_request_headers());
6261 base::RunLoop().Run();
6263 EXPECT_EQ(1, d.received_redirect_count());
6264 EXPECT_TRUE(d.have_full_request_headers());
6265 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6266 d.ClearFullRequestHeaders();
6268 req->FollowDeferredRedirect();
6269 base::RunLoop().Run();
6271 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6272 EXPECT_EQ(1, d.response_started_count());
6273 EXPECT_TRUE(d.have_full_request_headers());
6274 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6275 EXPECT_FALSE(d.received_data_before_response());
6276 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6278 base::FilePath path;
6279 PathService::Get(base::DIR_SOURCE_ROOT, &path);
6280 path = path.Append(FILE_PATH_LITERAL("net"));
6281 path = path.Append(FILE_PATH_LITERAL("data"));
6282 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6283 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6285 std::string contents;
6286 EXPECT_TRUE(base::ReadFileToString(path, &contents));
6287 EXPECT_EQ(contents, d.data_received());
6291 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6292 ASSERT_TRUE(test_server_.Start());
6296 d.set_quit_on_redirect(true);
6297 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6298 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
6301 base::RunLoop().Run();
6303 EXPECT_EQ(1, d.received_redirect_count());
6306 base::RunLoop().Run();
6308 EXPECT_EQ(1, d.response_started_count());
6309 EXPECT_EQ(0, d.bytes_received());
6310 EXPECT_FALSE(d.received_data_before_response());
6311 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
6315 TEST_F(URLRequestTestHTTP, VaryHeader) {
6316 ASSERT_TRUE(test_server_.Start());
6318 // Populate the cache.
6321 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6322 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6324 HttpRequestHeaders headers;
6325 headers.SetHeader("foo", "1");
6326 req->SetExtraRequestHeaders(headers);
6328 base::RunLoop().Run();
6330 LoadTimingInfo load_timing_info;
6331 req->GetLoadTimingInfo(&load_timing_info);
6332 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6335 // Expect a cache hit.
6338 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6339 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6341 HttpRequestHeaders headers;
6342 headers.SetHeader("foo", "1");
6343 req->SetExtraRequestHeaders(headers);
6345 base::RunLoop().Run();
6347 EXPECT_TRUE(req->was_cached());
6349 LoadTimingInfo load_timing_info;
6350 req->GetLoadTimingInfo(&load_timing_info);
6351 TestLoadTimingCacheHitNoNetwork(load_timing_info);
6354 // Expect a cache miss.
6357 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6358 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6360 HttpRequestHeaders headers;
6361 headers.SetHeader("foo", "2");
6362 req->SetExtraRequestHeaders(headers);
6364 base::RunLoop().Run();
6366 EXPECT_FALSE(req->was_cached());
6368 LoadTimingInfo load_timing_info;
6369 req->GetLoadTimingInfo(&load_timing_info);
6370 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6374 TEST_F(URLRequestTestHTTP, BasicAuth) {
6375 ASSERT_TRUE(test_server_.Start());
6377 // populate the cache
6380 d.set_credentials(AuthCredentials(kUser, kSecret));
6382 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6383 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6386 base::RunLoop().Run();
6388 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6391 // repeat request with end-to-end validation. since auth-basic results in a
6392 // cachable page, we expect this test to result in a 304. in which case, the
6393 // response should be fetched from the cache.
6396 d.set_credentials(AuthCredentials(kUser, kSecret));
6398 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6399 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6400 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6403 base::RunLoop().Run();
6405 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6407 // Should be the same cached document.
6408 EXPECT_TRUE(r->was_cached());
6412 // Check that Set-Cookie headers in 401 responses are respected.
6413 // http://crbug.com/6450
6414 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6415 ASSERT_TRUE(test_server_.Start());
6417 GURL url_requiring_auth =
6418 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6420 // Request a page that will give a 401 containing a Set-Cookie header.
6421 // Verify that when the transaction is restarted, it includes the new cookie.
6423 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6424 TestURLRequestContext context(true);
6425 context.set_network_delegate(&network_delegate);
6429 d.set_credentials(AuthCredentials(kUser, kSecret));
6431 scoped_ptr<URLRequest> r(context.CreateRequest(
6432 url_requiring_auth, DEFAULT_PRIORITY, &d, NULL));
6435 base::RunLoop().Run();
6437 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6439 // Make sure we sent the cookie in the restarted transaction.
6440 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6441 != std::string::npos);
6444 // Same test as above, except this time the restart is initiated earlier
6445 // (without user intervention since identity is embedded in the URL).
6447 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6448 TestURLRequestContext context(true);
6449 context.set_network_delegate(&network_delegate);
6454 GURL::Replacements replacements;
6455 std::string username("user2");
6456 std::string password("secret");
6457 replacements.SetUsernameStr(username);
6458 replacements.SetPasswordStr(password);
6459 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6461 scoped_ptr<URLRequest> r(context.CreateRequest(
6462 url_with_identity, DEFAULT_PRIORITY, &d, NULL));
6465 base::RunLoop().Run();
6467 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6469 // Make sure we sent the cookie in the restarted transaction.
6470 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6471 != std::string::npos);
6475 // Tests that load timing works as expected with auth and the cache.
6476 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6477 ASSERT_TRUE(test_server_.Start());
6479 // populate the cache
6482 d.set_credentials(AuthCredentials(kUser, kSecret));
6484 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6485 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6488 base::RunLoop().Run();
6490 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6492 LoadTimingInfo load_timing_info_before_auth;
6493 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6494 &load_timing_info_before_auth));
6495 TestLoadTimingNotReused(load_timing_info_before_auth,
6496 CONNECT_TIMING_HAS_DNS_TIMES);
6498 LoadTimingInfo load_timing_info;
6499 r->GetLoadTimingInfo(&load_timing_info);
6500 // The test server does not support keep alive sockets, so the second
6501 // request with auth should use a new socket.
6502 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6503 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6504 load_timing_info.socket_log_id);
6505 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6506 load_timing_info.connect_timing.connect_start);
6509 // Repeat request with end-to-end validation. Since auth-basic results in a
6510 // cachable page, we expect this test to result in a 304. In which case, the
6511 // response should be fetched from the cache.
6514 d.set_credentials(AuthCredentials(kUser, kSecret));
6516 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6517 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6518 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6521 base::RunLoop().Run();
6523 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6525 // Should be the same cached document.
6526 EXPECT_TRUE(r->was_cached());
6528 // Since there was a request that went over the wire, the load timing
6529 // information should include connection times.
6530 LoadTimingInfo load_timing_info;
6531 r->GetLoadTimingInfo(&load_timing_info);
6532 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6536 // In this test, we do a POST which the server will 302 redirect.
6537 // The subsequent transaction should use GET, and should not send the
6538 // Content-Type header.
6539 // http://code.google.com/p/chromium/issues/detail?id=843
6540 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6541 ASSERT_TRUE(test_server_.Start());
6543 const char kData[] = "hello world";
6546 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6547 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
6549 req->set_method("POST");
6550 req->set_upload(CreateSimpleUploadData(kData));
6552 // Set headers (some of which are specific to the POST).
6553 HttpRequestHeaders headers;
6554 headers.AddHeadersFromString(
6555 "Content-Type: multipart/form-data; "
6556 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6557 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6558 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6559 "Accept-Language: en-US,en\r\n"
6560 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6561 "Content-Length: 11\r\n"
6562 "Origin: http://localhost:1337/");
6563 req->SetExtraRequestHeaders(headers);
6565 base::RunLoop().Run();
6567 std::string mime_type;
6568 req->GetMimeType(&mime_type);
6569 EXPECT_EQ("text/html", mime_type);
6571 const std::string& data = d.data_received();
6573 // Check that the post-specific headers were stripped:
6574 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6575 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6576 EXPECT_FALSE(ContainsString(data, "Origin:"));
6578 // These extra request headers should not have been stripped.
6579 EXPECT_TRUE(ContainsString(data, "Accept:"));
6580 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6581 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6584 // The following tests check that we handle mutating the request method for
6585 // HTTP redirects as expected.
6586 // See http://crbug.com/56373 and http://crbug.com/102130.
6588 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6589 ASSERT_TRUE(test_server_.Start());
6591 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
6593 HTTPRedirectMethodTest(url, "POST", "GET", true);
6594 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6595 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6598 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6599 ASSERT_TRUE(test_server_.Start());
6601 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6603 HTTPRedirectMethodTest(url, "POST", "GET", true);
6604 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6605 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6608 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6609 ASSERT_TRUE(test_server_.Start());
6611 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6613 HTTPRedirectMethodTest(url, "POST", "GET", true);
6614 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6615 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6618 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6619 ASSERT_TRUE(test_server_.Start());
6621 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6623 HTTPRedirectMethodTest(url, "POST", "POST", true);
6624 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6625 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6628 TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6629 ASSERT_TRUE(test_server_.Start());
6631 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6633 HTTPRedirectMethodTest(url, "POST", "POST", true);
6634 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6635 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6638 // Make sure that 308 responses without bodies are not treated as redirects.
6639 // Certain legacy apis that pre-date the response code expect this behavior
6640 // (Like Google Drive).
6641 TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6642 ASSERT_TRUE(test_server_.Start());
6645 const GURL url = test_server_.GetURL("files/308-without-location-header");
6647 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
6648 url, DEFAULT_PRIORITY, &d, NULL));
6651 base::RunLoop().Run();
6652 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6653 EXPECT_EQ(OK, request->status().error());
6654 EXPECT_EQ(0, d.received_redirect_count());
6655 EXPECT_EQ(308, request->response_headers()->response_code());
6656 EXPECT_EQ("This is not a redirect.", d.data_received());
6659 TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6660 ASSERT_TRUE(test_server_.Start());
6662 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6663 GURL expected_url(test_server_.GetURL("echo#fragment"));
6667 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6668 original_url, DEFAULT_PRIORITY, &d, NULL));
6671 base::RunLoop().Run();
6673 EXPECT_EQ(2U, r->url_chain().size());
6674 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6675 EXPECT_EQ(OK, r->status().error());
6676 EXPECT_EQ(original_url, r->original_url());
6677 EXPECT_EQ(expected_url, r->url());
6681 TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6682 ASSERT_TRUE(test_server_.Start());
6684 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6685 GURL first_party_url("http://example.com");
6689 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6690 url, DEFAULT_PRIORITY, &d, NULL));
6691 r->set_first_party_for_cookies(first_party_url);
6694 base::RunLoop().Run();
6696 EXPECT_EQ(2U, r->url_chain().size());
6697 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6698 EXPECT_EQ(OK, r->status().error());
6699 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
6703 TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6704 ASSERT_TRUE(test_server_.Start());
6706 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6707 GURL original_first_party_url("http://example.com");
6708 GURL expected_first_party_url(test_server_.GetURL("echo"));
6712 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6713 url, DEFAULT_PRIORITY, &d, NULL));
6714 r->set_first_party_for_cookies(original_first_party_url);
6715 r->set_first_party_url_policy(
6716 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6719 base::RunLoop().Run();
6721 EXPECT_EQ(2U, r->url_chain().size());
6722 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6723 EXPECT_EQ(OK, r->status().error());
6724 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
6728 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6729 ASSERT_TRUE(test_server_.Start());
6731 const char kData[] = "hello world";
6734 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6735 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6736 req->set_method("POST");
6737 req->set_upload(CreateSimpleUploadData(kData));
6738 HttpRequestHeaders headers;
6739 headers.SetHeader(HttpRequestHeaders::kContentLength,
6740 base::UintToString(arraysize(kData) - 1));
6741 req->SetExtraRequestHeaders(headers);
6743 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6744 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6745 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6746 AddTestInterceptor()->set_main_intercept_job(job);
6749 base::RunLoop().Run();
6750 EXPECT_EQ("GET", req->method());
6753 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6754 ASSERT_TRUE(test_server_.Start());
6756 const char kData[] = "hello world";
6759 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6760 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6761 req->set_method("POST");
6762 req->set_upload(CreateSimpleUploadData(kData));
6763 HttpRequestHeaders headers;
6764 headers.SetHeader(HttpRequestHeaders::kContentLength,
6765 base::UintToString(arraysize(kData) - 1));
6766 req->SetExtraRequestHeaders(headers);
6768 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6769 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6770 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6771 "Very Good Reason");
6772 AddTestInterceptor()->set_main_intercept_job(job);
6775 base::RunLoop().Run();
6776 EXPECT_EQ("POST", req->method());
6777 EXPECT_EQ(kData, d.data_received());
6780 // Check that default A-L header is sent.
6781 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6782 ASSERT_TRUE(test_server_.Start());
6784 StaticHttpUserAgentSettings settings("en", std::string());
6785 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6786 TestURLRequestContext context(true);
6787 context.set_network_delegate(&network_delegate);
6788 context.set_http_user_agent_settings(&settings);
6792 scoped_ptr<URLRequest> req(context.CreateRequest(
6793 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6796 base::RunLoop().Run();
6797 EXPECT_EQ("en", d.data_received());
6800 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6801 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6802 ASSERT_TRUE(test_server_.Start());
6804 std::string empty_string; // Avoid most vexing parse on line below.
6805 StaticHttpUserAgentSettings settings(empty_string, empty_string);
6806 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6807 TestURLRequestContext context(true);
6808 context.set_network_delegate(&network_delegate);
6810 // We override the language after initialization because empty entries
6811 // get overridden by Init().
6812 context.set_http_user_agent_settings(&settings);
6815 scoped_ptr<URLRequest> req(context.CreateRequest(
6816 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6819 base::RunLoop().Run();
6820 EXPECT_EQ("None", d.data_received());
6823 // Check that if request overrides the A-L header, the default is not appended.
6824 // See http://crbug.com/20894
6825 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6826 ASSERT_TRUE(test_server_.Start());
6829 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6830 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6832 HttpRequestHeaders headers;
6833 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6834 req->SetExtraRequestHeaders(headers);
6836 base::RunLoop().Run();
6837 EXPECT_EQ(std::string("ru"), d.data_received());
6840 // Check that default A-E header is sent.
6841 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6842 ASSERT_TRUE(test_server_.Start());
6845 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6846 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6848 HttpRequestHeaders headers;
6849 req->SetExtraRequestHeaders(headers);
6851 base::RunLoop().Run();
6852 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6855 // Check that if request overrides the A-E header, the default is not appended.
6856 // See http://crbug.com/47381
6857 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6858 ASSERT_TRUE(test_server_.Start());
6861 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6862 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6864 HttpRequestHeaders headers;
6865 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6866 req->SetExtraRequestHeaders(headers);
6868 base::RunLoop().Run();
6869 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6870 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6873 // Check that setting the A-C header sends the proper header.
6874 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
6875 ASSERT_TRUE(test_server_.Start());
6878 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6879 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d,
6881 HttpRequestHeaders headers;
6882 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6883 req->SetExtraRequestHeaders(headers);
6885 base::RunLoop().Run();
6886 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6889 // Check that default User-Agent header is sent.
6890 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6891 ASSERT_TRUE(test_server_.Start());
6894 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6895 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6898 base::RunLoop().Run();
6899 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
6903 // Check that if request overrides the User-Agent header,
6904 // the default is not appended.
6905 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6906 ASSERT_TRUE(test_server_.Start());
6909 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6910 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6912 HttpRequestHeaders headers;
6913 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6914 req->SetExtraRequestHeaders(headers);
6916 base::RunLoop().Run();
6917 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
6920 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6921 // User-Agent header to be sent but does not send the Accept-Language and
6922 // Accept-Charset headers.
6923 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6924 ASSERT_TRUE(test_server_.Start());
6926 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6927 TestURLRequestContext context(true);
6928 context.set_network_delegate(&network_delegate);
6930 // We override the HttpUserAgentSettings after initialization because empty
6931 // entries get overridden by Init().
6932 context.set_http_user_agent_settings(NULL);
6935 const char* request;
6936 const char* expected_response;
6937 } tests[] = { { "echoheader?Accept-Language", "None" },
6938 { "echoheader?Accept-Charset", "None" },
6939 { "echoheader?User-Agent", "" } };
6941 for (size_t i = 0; i < arraysize(tests); i++) {
6943 scoped_ptr<URLRequest> req(context.CreateRequest(
6944 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, NULL));
6946 base::RunLoop().Run();
6947 EXPECT_EQ(tests[i].expected_response, d.data_received())
6948 << " Request = \"" << tests[i].request << "\"";
6952 // Make sure that URLRequest passes on its priority updates to
6953 // newly-created jobs after the first one.
6954 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6955 ASSERT_TRUE(test_server_.Start());
6958 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6959 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6960 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
6962 scoped_refptr<URLRequestRedirectJob> redirect_job =
6963 new URLRequestRedirectJob(
6964 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6965 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6966 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
6968 req->SetPriority(LOW);
6970 EXPECT_TRUE(req->is_pending());
6972 scoped_refptr<URLRequestTestJob> job =
6973 new URLRequestTestJob(req.get(), &default_network_delegate_);
6974 AddTestInterceptor()->set_main_intercept_job(job.get());
6976 // Should trigger |job| to be started.
6977 base::RunLoop().Run();
6978 EXPECT_EQ(LOW, job->priority());
6981 // Check that creating a network request while entering/exiting suspend mode
6982 // fails as it should. This is the only case where an HttpTransactionFactory
6983 // does not return an HttpTransaction.
6984 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6985 // Create a new HttpNetworkLayer that thinks it's suspended.
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 scoped_ptr<HttpNetworkLayer> network_layer(
6997 new HttpNetworkLayer(new HttpNetworkSession(params)));
6998 network_layer->OnSuspend();
7000 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
7001 HttpCache::DefaultBackend::InMemory(0));
7003 TestURLRequestContext context(true);
7004 context.set_http_transaction_factory(&http_cache);
7008 scoped_ptr<URLRequest> req(context.CreateRequest(
7009 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
7011 base::RunLoop().Run();
7013 EXPECT_TRUE(d.request_failed());
7014 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7015 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
7018 // Check that creating a network request while entering/exiting suspend mode
7019 // fails as it should in the case there is no cache. This is the only case
7020 // where an HttpTransactionFactory does not return an HttpTransaction.
7021 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
7022 // Create a new HttpNetworkLayer that thinks it's suspended.
7023 HttpNetworkSession::Params params;
7024 params.host_resolver = default_context_.host_resolver();
7025 params.cert_verifier = default_context_.cert_verifier();
7026 params.transport_security_state = default_context_.transport_security_state();
7027 params.proxy_service = default_context_.proxy_service();
7028 params.ssl_config_service = default_context_.ssl_config_service();
7029 params.http_auth_handler_factory =
7030 default_context_.http_auth_handler_factory();
7031 params.network_delegate = &default_network_delegate_;
7032 params.http_server_properties = default_context_.http_server_properties();
7033 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
7034 network_layer.OnSuspend();
7036 TestURLRequestContext context(true);
7037 context.set_http_transaction_factory(&network_layer);
7041 scoped_ptr<URLRequest> req(context.CreateRequest(
7042 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
7044 base::RunLoop().Run();
7046 EXPECT_TRUE(d.request_failed());
7047 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7048 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
7051 class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7053 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7054 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7055 // tests into the factory tests.
7056 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7059 void SetUpFactory() override {
7060 interceptor_ = new MockURLRequestInterceptor();
7061 job_factory_.reset(new URLRequestInterceptingJobFactory(
7062 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7065 MockURLRequestInterceptor* interceptor() const {
7066 return interceptor_;
7070 MockURLRequestInterceptor* interceptor_;
7073 TEST_F(URLRequestInterceptorTestHTTP,
7074 NetworkDelegateNotificationOnRedirectIntercept) {
7075 interceptor()->set_intercept_redirect(true);
7076 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7077 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7079 ASSERT_TRUE(test_server()->Start());
7082 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7083 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY,
7086 base::RunLoop().Run();
7088 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7089 // Check we got one good response
7090 EXPECT_TRUE(req->status().is_success());
7091 if (req->status().is_success())
7092 EXPECT_EQ(200, req->response_headers()->response_code());
7094 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7095 EXPECT_EQ(1, d.response_started_count());
7096 EXPECT_EQ(0, d.received_redirect_count());
7098 EXPECT_EQ(1, default_network_delegate()->created_requests());
7099 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7100 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7103 TEST_F(URLRequestInterceptorTestHTTP,
7104 NetworkDelegateNotificationOnErrorIntercept) {
7105 // Intercept that error and respond with an OK response.
7106 interceptor()->set_intercept_final_response(true);
7107 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7108 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7109 default_network_delegate()->set_can_be_intercepted_on_error(true);
7111 ASSERT_TRUE(test_server()->Start());
7114 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7115 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
7117 req->set_method("GET");
7119 base::RunLoop().Run();
7121 EXPECT_TRUE(interceptor()->did_intercept_final());
7123 // Check we received one good response.
7124 EXPECT_TRUE(req->status().is_success());
7125 if (req->status().is_success())
7126 EXPECT_EQ(200, req->response_headers()->response_code());
7127 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7128 EXPECT_EQ(1, d.response_started_count());
7129 EXPECT_EQ(0, d.received_redirect_count());
7131 EXPECT_EQ(1, default_network_delegate()->created_requests());
7132 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7133 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7136 TEST_F(URLRequestInterceptorTestHTTP,
7137 NetworkDelegateNotificationOnResponseIntercept) {
7138 // Intercept that error and respond with an OK response.
7139 interceptor()->set_intercept_final_response(true);
7141 // Intercept with a real URLRequestHttpJob.
7142 interceptor()->set_use_url_request_http_job(true);
7144 ASSERT_TRUE(test_server()->Start());
7147 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7148 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY,
7150 req->set_method("GET");
7152 base::RunLoop().Run();
7154 EXPECT_TRUE(interceptor()->did_intercept_final());
7156 // Check we received one good response.
7157 EXPECT_TRUE(req->status().is_success());
7158 if (req->status().is_success())
7159 EXPECT_EQ(200, req->response_headers()->response_code());
7160 EXPECT_EQ("hello", d.data_received());
7161 EXPECT_EQ(1, d.response_started_count());
7162 EXPECT_EQ(0, d.received_redirect_count());
7164 EXPECT_EQ(1, default_network_delegate()->created_requests());
7165 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7166 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7169 class HTTPSRequestTest : public testing::Test {
7171 HTTPSRequestTest() : default_context_(true) {
7172 default_context_.set_network_delegate(&default_network_delegate_);
7173 default_context_.Init();
7175 ~HTTPSRequestTest() override {}
7178 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7179 TestURLRequestContext default_context_;
7182 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
7183 SpawnedTestServer test_server(
7184 SpawnedTestServer::TYPE_HTTPS,
7185 SpawnedTestServer::kLocalhost,
7186 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7187 ASSERT_TRUE(test_server.Start());
7191 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7192 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7194 EXPECT_TRUE(r->is_pending());
7196 base::RunLoop().Run();
7198 EXPECT_EQ(1, d.response_started_count());
7199 EXPECT_FALSE(d.received_data_before_response());
7200 EXPECT_NE(0, d.bytes_received());
7201 CheckSSLInfo(r->ssl_info());
7202 EXPECT_EQ(test_server.host_port_pair().host(),
7203 r->GetSocketAddress().host());
7204 EXPECT_EQ(test_server.host_port_pair().port(),
7205 r->GetSocketAddress().port());
7209 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
7210 SpawnedTestServer::SSLOptions ssl_options(
7211 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7212 SpawnedTestServer test_server(
7213 SpawnedTestServer::TYPE_HTTPS,
7215 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7216 ASSERT_TRUE(test_server.Start());
7218 bool err_allowed = true;
7219 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7222 d.set_allow_certificate_errors(err_allowed);
7223 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7224 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7227 EXPECT_TRUE(r->is_pending());
7229 base::RunLoop().Run();
7231 EXPECT_EQ(1, d.response_started_count());
7232 EXPECT_FALSE(d.received_data_before_response());
7233 EXPECT_TRUE(d.have_certificate_errors());
7235 EXPECT_NE(0, d.bytes_received());
7236 CheckSSLInfo(r->ssl_info());
7238 EXPECT_EQ(0, d.bytes_received());
7244 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
7245 SpawnedTestServer::SSLOptions ssl_options(
7246 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7247 SpawnedTestServer test_server(
7248 SpawnedTestServer::TYPE_HTTPS,
7250 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7251 ASSERT_TRUE(test_server.Start());
7253 // Iterate from false to true, just so that we do the opposite of the
7254 // previous test in order to increase test coverage.
7255 bool err_allowed = false;
7256 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7259 d.set_allow_certificate_errors(err_allowed);
7260 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7261 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7264 EXPECT_TRUE(r->is_pending());
7266 base::RunLoop().Run();
7268 EXPECT_EQ(1, d.response_started_count());
7269 EXPECT_FALSE(d.received_data_before_response());
7270 EXPECT_TRUE(d.have_certificate_errors());
7272 EXPECT_NE(0, d.bytes_received());
7273 CheckSSLInfo(r->ssl_info());
7275 EXPECT_EQ(0, d.bytes_received());
7281 // This tests that a load of www.google.com with a certificate error sets
7282 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
7283 // the interstitial to be fatal.
7284 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
7285 SpawnedTestServer::SSLOptions ssl_options(
7286 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7287 SpawnedTestServer test_server(
7288 SpawnedTestServer::TYPE_HTTPS,
7290 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7291 ASSERT_TRUE(test_server.Start());
7293 // We require that the URL be www.google.com in order to pick up the
7294 // preloaded HSTS entries in the TransportSecurityState. This means that we
7295 // have to use a MockHostResolver in order to direct www.google.com to the
7296 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7298 MockHostResolver host_resolver;
7299 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7300 TestURLRequestContext context(true);
7301 context.set_network_delegate(&network_delegate);
7302 context.set_host_resolver(&host_resolver);
7303 TransportSecurityState transport_security_state;
7304 context.set_transport_security_state(&transport_security_state);
7308 scoped_ptr<URLRequest> r(context.CreateRequest(
7309 GURL(base::StringPrintf("https://www.google.com:%d",
7310 test_server.host_port_pair().port())),
7311 DEFAULT_PRIORITY, &d, NULL));
7314 EXPECT_TRUE(r->is_pending());
7316 base::RunLoop().Run();
7318 EXPECT_EQ(1, d.response_started_count());
7319 EXPECT_FALSE(d.received_data_before_response());
7320 EXPECT_TRUE(d.have_certificate_errors());
7321 EXPECT_TRUE(d.certificate_errors_are_fatal());
7324 // This tests that cached HTTPS page loads do not cause any updates to the
7325 // TransportSecurityState.
7326 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7327 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7328 // matter. It just has to be any error.
7329 SpawnedTestServer::SSLOptions ssl_options(
7330 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7331 SpawnedTestServer test_server(
7332 SpawnedTestServer::TYPE_HTTPS,
7334 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7335 ASSERT_TRUE(test_server.Start());
7337 // We require that the URL be www.google.com in order to pick up the static
7338 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7339 // that we have to use a MockHostResolver in order to direct www.google.com to
7340 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7342 MockHostResolver host_resolver;
7343 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7344 TestURLRequestContext context(true);
7345 context.set_network_delegate(&network_delegate);
7346 context.set_host_resolver(&host_resolver);
7347 TransportSecurityState transport_security_state;
7349 TransportSecurityState::DomainState static_domain_state;
7350 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
7351 "www.google.com", &static_domain_state));
7352 context.set_transport_security_state(&transport_security_state);
7355 TransportSecurityState::DomainState dynamic_domain_state;
7356 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7357 "www.google.com", &dynamic_domain_state));
7360 scoped_ptr<URLRequest> r(context.CreateRequest(
7361 GURL(base::StringPrintf("https://www.google.com:%d",
7362 test_server.host_port_pair().port())),
7363 DEFAULT_PRIORITY, &d, NULL));
7366 EXPECT_TRUE(r->is_pending());
7368 base::RunLoop().Run();
7370 EXPECT_EQ(1, d.response_started_count());
7371 EXPECT_FALSE(d.received_data_before_response());
7372 EXPECT_TRUE(d.have_certificate_errors());
7373 EXPECT_TRUE(d.certificate_errors_are_fatal());
7375 // Get a fresh copy of the states, and check that they haven't changed.
7376 TransportSecurityState::DomainState new_static_domain_state;
7377 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
7378 "www.google.com", &new_static_domain_state));
7379 TransportSecurityState::DomainState new_dynamic_domain_state;
7380 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7381 "www.google.com", &new_dynamic_domain_state));
7383 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7384 static_domain_state.sts.upgrade_mode);
7385 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7386 static_domain_state.sts.include_subdomains);
7387 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7388 static_domain_state.pkp.include_subdomains);
7389 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7390 static_domain_state.pkp.spki_hashes));
7391 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7392 static_domain_state.pkp.bad_spki_hashes));
7395 // Make sure HSTS preserves a POST request's method and body.
7396 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7397 static const char kData[] = "hello world";
7399 SpawnedTestServer::SSLOptions ssl_options(
7400 SpawnedTestServer::SSLOptions::CERT_OK);
7401 SpawnedTestServer test_server(
7402 SpawnedTestServer::TYPE_HTTPS,
7404 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7405 ASSERT_TRUE(test_server.Start());
7408 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7409 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
7410 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7412 MockHostResolver host_resolver;
7414 // Force https for www.somewhere.com.
7415 TransportSecurityState transport_security_state;
7416 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7417 bool include_subdomains = false;
7418 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7419 include_subdomains);
7421 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7423 TestURLRequestContext context(true);
7424 context.set_host_resolver(&host_resolver);
7425 context.set_transport_security_state(&transport_security_state);
7426 context.set_network_delegate(&network_delegate);
7430 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7431 // cause a certificate error. Ignore the error.
7432 d.set_allow_certificate_errors(true);
7434 scoped_ptr<URLRequest> req(context.CreateRequest(
7435 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
7436 test_server.host_port_pair().port())),
7437 DEFAULT_PRIORITY, &d, NULL));
7438 req->set_method("POST");
7439 req->set_upload(CreateSimpleUploadData(kData));
7442 base::RunLoop().Run();
7444 EXPECT_EQ("https", req->url().scheme());
7445 EXPECT_EQ("POST", req->method());
7446 EXPECT_EQ(kData, d.data_received());
7448 LoadTimingInfo load_timing_info;
7449 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7450 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7451 TestLoadTimingCacheHitNoNetwork(load_timing_info);
7454 // Make sure that the CORS headers are added to cross-origin HSTS redirects.
7455 TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7456 static const char kOriginHeaderValue[] = "http://www.example.com";
7458 SpawnedTestServer::SSLOptions ssl_options(
7459 SpawnedTestServer::SSLOptions::CERT_OK);
7460 SpawnedTestServer test_server(
7461 SpawnedTestServer::TYPE_HTTPS,
7463 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7464 ASSERT_TRUE(test_server.Start());
7466 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7467 // address, so a MockHostResolver is needed to redirect example.net to the
7468 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7469 MockHostResolver host_resolver;
7471 TransportSecurityState transport_security_state;
7472 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7473 bool include_subdomains = false;
7474 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7476 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7478 MockCertVerifier cert_verifier;
7479 cert_verifier.set_default_result(OK);
7481 TestURLRequestContext context(true);
7482 context.set_host_resolver(&host_resolver);
7483 context.set_transport_security_state(&transport_security_state);
7484 context.set_network_delegate(&network_delegate);
7485 context.set_cert_verifier(&cert_verifier);
7488 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7489 test_server.host_port_pair().port()));
7490 url::Replacements<char> replacements;
7491 const char kNewScheme[] = "https";
7492 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7493 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7496 // Quit on redirect to allow response header inspection upon redirect.
7497 d.set_quit_on_redirect(true);
7499 scoped_ptr<URLRequest> req(context.CreateRequest(hsts_http_url,
7500 DEFAULT_PRIORITY, &d, NULL));
7501 // Set Origin header to simulate a cross-origin request.
7502 HttpRequestHeaders request_headers;
7503 request_headers.SetHeader("Origin", kOriginHeaderValue);
7504 req->SetExtraRequestHeaders(request_headers);
7507 base::RunLoop().Run();
7509 EXPECT_EQ(1, d.received_redirect_count());
7511 const HttpResponseHeaders* headers = req->response_headers();
7512 std::string redirect_location;
7513 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7514 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7516 std::string received_cors_header;
7517 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7518 &received_cors_header));
7519 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7524 class SSLClientAuthTestDelegate : public TestDelegate {
7526 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7528 void OnCertificateRequested(URLRequest* request,
7529 SSLCertRequestInfo* cert_request_info) override {
7530 on_certificate_requested_count_++;
7531 base::MessageLoop::current()->Quit();
7533 int on_certificate_requested_count() {
7534 return on_certificate_requested_count_;
7537 int on_certificate_requested_count_;
7542 // TODO(davidben): Test the rest of the code. Specifically,
7543 // - Filtering which certificates to select.
7544 // - Sending a certificate back.
7545 // - Getting a certificate request in an SSL renegotiation sending the
7547 TEST_F(HTTPSRequestTest, ClientAuthTest) {
7548 SpawnedTestServer::SSLOptions ssl_options;
7549 ssl_options.request_client_certificate = true;
7550 SpawnedTestServer test_server(
7551 SpawnedTestServer::TYPE_HTTPS,
7553 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7554 ASSERT_TRUE(test_server.Start());
7556 SSLClientAuthTestDelegate d;
7558 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7559 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7562 EXPECT_TRUE(r->is_pending());
7564 base::RunLoop().Run();
7566 EXPECT_EQ(1, d.on_certificate_requested_count());
7567 EXPECT_FALSE(d.received_data_before_response());
7568 EXPECT_EQ(0, d.bytes_received());
7570 // Send no certificate.
7571 // TODO(davidben): Get temporary client cert import (with keys) working on
7572 // all platforms so we can test sending a cert as well.
7573 r->ContinueWithCertificate(NULL);
7575 base::RunLoop().Run();
7577 EXPECT_EQ(1, d.response_started_count());
7578 EXPECT_FALSE(d.received_data_before_response());
7579 EXPECT_NE(0, d.bytes_received());
7583 TEST_F(HTTPSRequestTest, ResumeTest) {
7584 // Test that we attempt a session resume when making two connections to the
7586 SpawnedTestServer::SSLOptions ssl_options;
7587 ssl_options.record_resume = true;
7588 SpawnedTestServer test_server(
7589 SpawnedTestServer::TYPE_HTTPS,
7591 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7592 ASSERT_TRUE(test_server.Start());
7594 SSLClientSocket::ClearSessionCache();
7598 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7599 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7602 EXPECT_TRUE(r->is_pending());
7604 base::RunLoop().Run();
7606 EXPECT_EQ(1, d.response_started_count());
7609 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7610 CloseAllConnections();
7614 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7615 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7618 EXPECT_TRUE(r->is_pending());
7620 base::RunLoop().Run();
7622 // The response will look like;
7627 // With a newline at the end which makes the split think that there are
7630 EXPECT_EQ(1, d.response_started_count());
7631 std::vector<std::string> lines;
7632 base::SplitString(d.data_received(), '\n', &lines);
7633 ASSERT_EQ(4u, lines.size()) << d.data_received();
7635 std::string session_id;
7637 for (size_t i = 0; i < 2; i++) {
7638 std::vector<std::string> parts;
7639 base::SplitString(lines[i], '\t', &parts);
7640 ASSERT_EQ(2u, parts.size());
7642 EXPECT_EQ("insert", parts[0]);
7643 session_id = parts[1];
7645 EXPECT_EQ("lookup", parts[0]);
7646 EXPECT_EQ(session_id, parts[1]);
7652 // AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7653 // the result of fetching "ssl-session-cache" from the test server, indicates
7654 // that exactly two different sessions were inserted, with no lookups etc.
7655 static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7656 std::vector<std::string> lines;
7657 base::SplitString(session_info, '\n', &lines);
7658 ASSERT_EQ(3u, lines.size()) << session_info;
7660 std::string session_id;
7661 for (size_t i = 0; i < 2; i++) {
7662 std::vector<std::string> parts;
7663 base::SplitString(lines[i], '\t', &parts);
7664 ASSERT_EQ(2u, parts.size());
7665 EXPECT_EQ("insert", parts[0]);
7667 session_id = parts[1];
7669 EXPECT_NE(session_id, parts[1]);
7674 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7675 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7677 SpawnedTestServer::SSLOptions ssl_options;
7678 ssl_options.record_resume = true;
7679 SpawnedTestServer test_server(
7680 SpawnedTestServer::TYPE_HTTPS,
7682 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7683 ASSERT_TRUE(test_server.Start());
7685 SSLClientSocket::ClearSessionCache();
7689 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7690 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7693 EXPECT_TRUE(r->is_pending());
7695 base::RunLoop().Run();
7697 EXPECT_EQ(1, d.response_started_count());
7700 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7701 HttpNetworkSession::Params params;
7702 params.host_resolver = default_context_.host_resolver();
7703 params.cert_verifier = default_context_.cert_verifier();
7704 params.transport_security_state = default_context_.transport_security_state();
7705 params.proxy_service = default_context_.proxy_service();
7706 params.ssl_config_service = default_context_.ssl_config_service();
7707 params.http_auth_handler_factory =
7708 default_context_.http_auth_handler_factory();
7709 params.network_delegate = &default_network_delegate_;
7710 params.http_server_properties = default_context_.http_server_properties();
7711 params.ssl_session_cache_shard = "alternate";
7713 scoped_ptr<HttpCache> cache(new HttpCache(
7714 new HttpNetworkSession(params),
7715 HttpCache::DefaultBackend::InMemory(0)));
7717 default_context_.set_http_transaction_factory(cache.get());
7721 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7722 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7725 EXPECT_TRUE(r->is_pending());
7727 base::RunLoop().Run();
7729 // The response will look like;
7733 // With a newline at the end which makes the split think that there are
7736 EXPECT_EQ(1, d.response_started_count());
7737 AssertTwoDistinctSessionsInserted(d.data_received());
7745 bool IsECDSACipherSuite(uint16_t cipher_suite) {
7746 const char* key_exchange;
7750 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7751 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7756 // Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7758 TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
7759 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7760 LOG(INFO) << "Skipping test on this version.";
7764 SpawnedTestServer test_server(
7765 SpawnedTestServer::TYPE_HTTPS,
7766 SpawnedTestServer::kLocalhost,
7767 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7768 ASSERT_TRUE(test_server.Start());
7771 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7772 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d, NULL));
7774 EXPECT_TRUE(r->is_pending());
7776 base::RunLoop().Run();
7778 EXPECT_EQ(1, d.response_started_count());
7779 std::vector<std::string> lines;
7780 base::SplitString(d.data_received(), '\n', &lines);
7782 for (size_t i = 0; i < lines.size(); i++) {
7784 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7785 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7786 << "ClientHello advertised " << cipher_suite;
7792 class TestSSLConfigService : public SSLConfigService {
7794 TestSSLConfigService(bool ev_enabled,
7795 bool online_rev_checking,
7796 bool rev_checking_required_local_anchors)
7797 : ev_enabled_(ev_enabled),
7798 online_rev_checking_(online_rev_checking),
7799 rev_checking_required_local_anchors_(
7800 rev_checking_required_local_anchors),
7801 min_version_(kDefaultSSLVersionMin),
7802 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7804 void set_min_version(uint16 version) {
7805 min_version_ = version;
7808 void set_fallback_min_version(uint16 version) {
7809 fallback_min_version_ = version;
7812 // SSLConfigService:
7813 void GetSSLConfig(SSLConfig* config) override {
7814 *config = SSLConfig();
7815 config->rev_checking_enabled = online_rev_checking_;
7816 config->verify_ev_cert = ev_enabled_;
7817 config->rev_checking_required_local_anchors =
7818 rev_checking_required_local_anchors_;
7819 if (fallback_min_version_) {
7820 config->version_fallback_min = fallback_min_version_;
7823 config->version_min = min_version_;
7828 ~TestSSLConfigService() override {}
7831 const bool ev_enabled_;
7832 const bool online_rev_checking_;
7833 const bool rev_checking_required_local_anchors_;
7834 uint16 min_version_;
7835 uint16 fallback_min_version_;
7838 class FallbackTestURLRequestContext : public TestURLRequestContext {
7840 explicit FallbackTestURLRequestContext(bool delay_initialization)
7841 : TestURLRequestContext(delay_initialization) {}
7843 void set_fallback_min_version(uint16 version) {
7844 TestSSLConfigService *ssl_config_service =
7845 new TestSSLConfigService(true /* check for EV */,
7846 false /* online revocation checking */,
7847 false /* require rev. checking for local
7849 ssl_config_service->set_min_version(SSL_PROTOCOL_VERSION_SSL3);
7850 ssl_config_service->set_fallback_min_version(version);
7851 set_ssl_config_service(ssl_config_service);
7855 class HTTPSFallbackTest : public testing::Test {
7857 HTTPSFallbackTest() : context_(true) {}
7858 ~HTTPSFallbackTest() override {}
7861 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7864 delegate_.set_allow_certificate_errors(true);
7866 SpawnedTestServer test_server(
7867 SpawnedTestServer::TYPE_HTTPS,
7869 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7870 ASSERT_TRUE(test_server.Start());
7872 request_ = context_.CreateRequest(
7873 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate_, NULL);
7876 base::RunLoop().Run();
7879 void set_fallback_min_version(uint16 version) {
7880 context_.set_fallback_min_version(version);
7883 void ExpectConnection(int version) {
7884 EXPECT_EQ(1, delegate_.response_started_count());
7885 EXPECT_NE(0, delegate_.bytes_received());
7886 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7887 request_->ssl_info().connection_status));
7888 EXPECT_TRUE(request_->ssl_info().connection_status &
7889 SSL_CONNECTION_VERSION_FALLBACK);
7892 void ExpectFailure(int error) {
7893 EXPECT_EQ(1, delegate_.response_started_count());
7894 EXPECT_FALSE(request_->status().is_success());
7895 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7896 EXPECT_EQ(error, request_->status().error());
7900 TestDelegate delegate_;
7901 FallbackTestURLRequestContext context_;
7902 scoped_ptr<URLRequest> request_;
7905 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7907 TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7908 SpawnedTestServer::SSLOptions ssl_options(
7909 SpawnedTestServer::SSLOptions::CERT_OK);
7910 ssl_options.tls_intolerant =
7911 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7913 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7914 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7917 // This test is disabled on Android because the remote test server doesn't cause
7919 #if !defined(OS_ANDROID)
7920 // Tests fallback to TLS 1.0 on connection reset.
7921 TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7922 SpawnedTestServer::SSLOptions ssl_options(
7923 SpawnedTestServer::SSLOptions::CERT_OK);
7924 ssl_options.tls_intolerant =
7925 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7926 ssl_options.tls_intolerance_type =
7927 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7929 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7930 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7932 #endif // !OS_ANDROID
7934 // Tests that we don't fallback on handshake failure with servers that implement
7935 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7936 TEST_F(HTTPSFallbackTest, FallbackSCSV) {
7937 SpawnedTestServer::SSLOptions ssl_options(
7938 SpawnedTestServer::SSLOptions::CERT_OK);
7939 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7940 // a version fallback.
7941 ssl_options.tls_intolerant =
7942 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7943 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7944 // connections are rejected.
7945 ssl_options.fallback_scsv_enabled = true;
7947 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7949 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7950 // intolerance. If the fallback SCSV is processed when the original error
7951 // that caused the fallback should be returned, which should be
7952 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7953 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7956 // Tests that we don't fallback on connection closed with servers that implement
7957 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7958 TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
7959 SpawnedTestServer::SSLOptions ssl_options(
7960 SpawnedTestServer::SSLOptions::CERT_OK);
7961 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7962 // a version fallback.
7963 ssl_options.tls_intolerant =
7964 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7965 ssl_options.tls_intolerance_type =
7966 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7967 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7968 // connections are rejected.
7969 ssl_options.fallback_scsv_enabled = true;
7971 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7973 // The original error should be replayed on rejected fallback.
7974 ExpectFailure(ERR_CONNECTION_CLOSED);
7977 // Tests that the SSLv3 fallback doesn't happen by default.
7978 TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7979 SpawnedTestServer::SSLOptions ssl_options(
7980 SpawnedTestServer::SSLOptions::CERT_OK);
7981 ssl_options.tls_intolerant =
7982 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7984 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7985 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7988 // Tests that the SSLv3 fallback works when explicitly enabled.
7989 TEST_F(HTTPSFallbackTest, SSLv3FallbackEnabled) {
7990 SpawnedTestServer::SSLOptions ssl_options(
7991 SpawnedTestServer::SSLOptions::CERT_OK);
7992 ssl_options.tls_intolerant =
7993 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7994 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7996 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7997 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
8000 // Tests that the SSLv3 fallback triggers on closed connections when explicitly
8002 TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8003 SpawnedTestServer::SSLOptions ssl_options(
8004 SpawnedTestServer::SSLOptions::CERT_OK);
8005 ssl_options.tls_intolerant =
8006 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8007 ssl_options.tls_intolerance_type =
8008 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8009 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
8011 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8012 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
8015 // Test that SSLv3 fallback probe connections don't cause sessions to be cached.
8016 TEST_F(HTTPSRequestTest, SSLv3FallbackNoCache) {
8017 SpawnedTestServer::SSLOptions ssl_options(
8018 SpawnedTestServer::SSLOptions::CERT_OK);
8019 ssl_options.tls_intolerant =
8020 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8021 ssl_options.tls_intolerance_type =
8022 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8023 ssl_options.record_resume = true;
8025 SpawnedTestServer test_server(
8026 SpawnedTestServer::TYPE_HTTPS,
8028 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8029 ASSERT_TRUE(test_server.Start());
8031 SSLClientSocket::ClearSessionCache();
8033 // Make a connection that does a probe fallback to SSLv3 but fails because
8034 // SSLv3 fallback is disabled. We don't wish a session for this connection to
8035 // be inserted locally.
8037 TestDelegate delegate;
8038 FallbackTestURLRequestContext context(true);
8040 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
8042 scoped_ptr<URLRequest> request(context.CreateRequest(
8043 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate, NULL));
8046 base::RunLoop().Run();
8048 EXPECT_EQ(1, delegate.response_started_count());
8049 EXPECT_FALSE(request->status().is_success());
8050 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8051 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8052 request->status().error());
8055 // Now allow SSLv3 connections and request the session cache log.
8057 TestDelegate delegate;
8058 FallbackTestURLRequestContext context(true);
8059 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
8062 scoped_ptr<URLRequest> request(
8063 context.CreateRequest(test_server.GetURL("ssl-session-cache"),
8069 base::RunLoop().Run();
8071 EXPECT_EQ(1, delegate.response_started_count());
8072 EXPECT_NE(0, delegate.bytes_received());
8073 EXPECT_EQ(SSL_CONNECTION_VERSION_SSL3, SSLConnectionStatusToVersion(
8074 request->ssl_info().connection_status));
8075 EXPECT_TRUE(request->ssl_info().connection_status &
8076 SSL_CONNECTION_VERSION_FALLBACK);
8078 std::vector<std::string> lines;
8079 // If no sessions were cached then the server should have seen two sessions
8080 // inserted with no lookups.
8081 AssertTwoDistinctSessionsInserted(delegate.data_received());
8085 // This test is disabled on Android because the remote test server doesn't cause
8087 #if !defined(OS_ANDROID)
8088 // Tests that a reset connection does not fallback down to SSL3.
8089 TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
8090 SpawnedTestServer::SSLOptions ssl_options(
8091 SpawnedTestServer::SSLOptions::CERT_OK);
8092 ssl_options.tls_intolerant =
8093 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8094 ssl_options.tls_intolerance_type =
8095 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8097 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8098 ExpectFailure(ERR_CONNECTION_RESET);
8100 #endif // !OS_ANDROID
8102 class HTTPSSessionTest : public testing::Test {
8104 HTTPSSessionTest() : default_context_(true) {
8105 cert_verifier_.set_default_result(OK);
8107 default_context_.set_network_delegate(&default_network_delegate_);
8108 default_context_.set_cert_verifier(&cert_verifier_);
8109 default_context_.Init();
8111 ~HTTPSSessionTest() override {}
8114 MockCertVerifier cert_verifier_;
8115 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8116 TestURLRequestContext default_context_;
8119 // Tests that session resumption is not attempted if an invalid certificate
8121 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8122 SpawnedTestServer::SSLOptions ssl_options;
8123 ssl_options.record_resume = true;
8124 SpawnedTestServer test_server(
8125 SpawnedTestServer::TYPE_HTTPS,
8127 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8128 ASSERT_TRUE(test_server.Start());
8130 SSLClientSocket::ClearSessionCache();
8132 // Simulate the certificate being expired and attempt a connection.
8133 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
8136 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8137 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
8140 EXPECT_TRUE(r->is_pending());
8142 base::RunLoop().Run();
8144 EXPECT_EQ(1, d.response_started_count());
8147 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8148 CloseAllConnections();
8150 // Now change the certificate to be acceptable (so that the response is
8151 // loaded), and ensure that no session id is presented to the peer.
8152 cert_verifier_.set_default_result(OK);
8155 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8156 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
8159 EXPECT_TRUE(r->is_pending());
8161 base::RunLoop().Run();
8163 // The response will look like;
8167 // With a newline at the end which makes the split think that there are
8170 // If a session was presented (eg: a bug), then the response would look
8176 EXPECT_EQ(1, d.response_started_count());
8177 AssertTwoDistinctSessionsInserted(d.data_received());
8181 // This the fingerprint of the "Testing CA" certificate used by the testserver.
8182 // See net/data/ssl/certificates/ocsp-test-root.pem.
8183 static const SHA1HashValue kOCSPTestCertFingerprint =
8184 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8185 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8187 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8189 static const SHA256HashValue kOCSPTestCertSPKI = { {
8190 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8191 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8192 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8193 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8196 // This is the policy OID contained in the certificates that testserver
8198 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8200 class HTTPSOCSPTest : public HTTPSRequestTest {
8205 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8206 kOCSPTestCertFingerprint,
8207 kOCSPTestCertPolicy)) {
8210 void SetUp() override {
8211 SetupContext(&context_);
8214 scoped_refptr<X509Certificate> root_cert =
8215 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
8216 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
8217 test_root_.reset(new ScopedTestRoot(root_cert.get()));
8219 #if defined(USE_NSS) || defined(OS_IOS)
8220 SetURLRequestContextForNSSHttpIO(&context_);
8221 EnsureNSSHttpIOInit();
8225 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
8226 CertStatus* out_cert_status) {
8227 // We always overwrite out_cert_status.
8228 *out_cert_status = 0;
8229 SpawnedTestServer test_server(
8230 SpawnedTestServer::TYPE_HTTPS,
8232 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8233 ASSERT_TRUE(test_server.Start());
8236 d.set_allow_certificate_errors(true);
8237 scoped_ptr<URLRequest> r(context_.CreateRequest(
8238 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
8241 base::RunLoop().Run();
8243 EXPECT_EQ(1, d.response_started_count());
8244 *out_cert_status = r->ssl_info().cert_status;
8247 ~HTTPSOCSPTest() override {
8248 #if defined(USE_NSS) || defined(OS_IOS)
8249 ShutdownNSSHttpIO();
8254 // SetupContext configures the URLRequestContext that will be used for making
8255 // connetions to testserver. This can be overridden in test subclasses for
8256 // different behaviour.
8257 virtual void SetupContext(URLRequestContext* context) {
8258 context->set_ssl_config_service(
8259 new TestSSLConfigService(true /* check for EV */,
8260 true /* online revocation checking */,
8261 false /* require rev. checking for local
8265 scoped_ptr<ScopedTestRoot> test_root_;
8266 TestURLRequestContext context_;
8267 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
8270 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
8272 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8273 // have that ability on other platforms.
8274 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8280 // SystemSupportsHardFailRevocationChecking returns true iff the current
8281 // operating system supports revocation checking and can distinguish between
8282 // situations where a given certificate lacks any revocation information (eg:
8283 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8284 // revocation information cannot be obtained (eg: the CRL was unreachable).
8285 // If it does not, then tests which rely on 'hard fail' behaviour should be
8287 static bool SystemSupportsHardFailRevocationChecking() {
8288 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
8295 // SystemUsesChromiumEVMetadata returns true iff the current operating system
8296 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8297 // several tests are effected because our testing EV certificate won't be
8298 // recognised as EV.
8299 static bool SystemUsesChromiumEVMetadata() {
8300 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
8301 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8303 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8304 // On OS X and Android, we use the system to tell us whether a certificate is
8305 // EV or not and the system won't recognise our testing root.
8312 static bool SystemSupportsOCSP() {
8313 #if defined(USE_OPENSSL)
8314 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8316 #elif defined(OS_WIN)
8317 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8318 #elif defined(OS_ANDROID)
8319 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8326 TEST_F(HTTPSOCSPTest, Valid) {
8327 if (!SystemSupportsOCSP()) {
8328 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8332 SpawnedTestServer::SSLOptions ssl_options(
8333 SpawnedTestServer::SSLOptions::CERT_AUTO);
8334 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8336 CertStatus cert_status;
8337 DoConnection(ssl_options, &cert_status);
8339 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8341 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8342 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8344 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8347 TEST_F(HTTPSOCSPTest, Revoked) {
8348 if (!SystemSupportsOCSP()) {
8349 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8353 SpawnedTestServer::SSLOptions ssl_options(
8354 SpawnedTestServer::SSLOptions::CERT_AUTO);
8355 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8357 CertStatus cert_status;
8358 DoConnection(ssl_options, &cert_status);
8360 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
8361 // Doesn't pass on OS X yet for reasons that need to be investigated.
8362 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8364 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8365 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8368 TEST_F(HTTPSOCSPTest, Invalid) {
8369 if (!SystemSupportsOCSP()) {
8370 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8374 SpawnedTestServer::SSLOptions ssl_options(
8375 SpawnedTestServer::SSLOptions::CERT_AUTO);
8376 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8378 CertStatus cert_status;
8379 DoConnection(ssl_options, &cert_status);
8381 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8382 cert_status & CERT_STATUS_ALL_ERRORS);
8384 // Without a positive OCSP response, we shouldn't show the EV status.
8385 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8386 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8389 class HTTPSHardFailTest : public HTTPSOCSPTest {
8391 void SetupContext(URLRequestContext* context) override {
8392 context->set_ssl_config_service(
8393 new TestSSLConfigService(false /* check for EV */,
8394 false /* online revocation checking */,
8395 true /* require rev. checking for local
8401 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8402 if (!SystemSupportsOCSP()) {
8403 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8407 if (!SystemSupportsHardFailRevocationChecking()) {
8408 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8409 << "revocation checking";
8413 SpawnedTestServer::SSLOptions ssl_options(
8414 SpawnedTestServer::SSLOptions::CERT_AUTO);
8415 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8417 CertStatus cert_status;
8418 DoConnection(ssl_options, &cert_status);
8420 EXPECT_EQ(CERT_STATUS_REVOKED,
8421 cert_status & CERT_STATUS_REVOKED);
8423 // Without a positive OCSP response, we shouldn't show the EV status.
8424 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8427 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8429 void SetupContext(URLRequestContext* context) override {
8430 context->set_ssl_config_service(
8431 new TestSSLConfigService(true /* check for EV */,
8432 false /* online revocation checking */,
8433 false /* require rev. checking for local
8438 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8439 if (!SystemSupportsOCSP()) {
8440 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8444 SpawnedTestServer::SSLOptions ssl_options(
8445 SpawnedTestServer::SSLOptions::CERT_AUTO);
8446 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8447 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8449 CertStatus cert_status;
8450 DoConnection(ssl_options, &cert_status);
8452 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8453 cert_status & CERT_STATUS_ALL_ERRORS);
8455 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8456 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8457 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8460 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8461 if (!SystemSupportsOCSP()) {
8462 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8466 SpawnedTestServer::SSLOptions ssl_options(
8467 SpawnedTestServer::SSLOptions::CERT_AUTO);
8468 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8469 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8471 CertStatus cert_status;
8472 DoConnection(ssl_options, &cert_status);
8474 // Currently only works for Windows. When using NSS or OS X, it's not
8475 // possible to determine whether the check failed because of actual
8476 // revocation or because there was an OCSP failure.
8478 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8480 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8483 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8484 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8485 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8488 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8489 if (!SystemSupportsOCSP()) {
8490 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8494 SpawnedTestServer::SSLOptions ssl_options(
8495 SpawnedTestServer::SSLOptions::CERT_AUTO);
8496 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8497 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8499 CertStatus cert_status;
8500 DoConnection(ssl_options, &cert_status);
8502 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8504 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8505 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8506 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8507 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8510 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8511 if (!SystemSupportsOCSP()) {
8512 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8516 SpawnedTestServer::SSLOptions ssl_options(
8517 SpawnedTestServer::SSLOptions::CERT_AUTO);
8518 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8519 SSLConfigService::SetCRLSet(
8520 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8522 CertStatus cert_status;
8523 DoConnection(ssl_options, &cert_status);
8525 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8526 cert_status & CERT_STATUS_ALL_ERRORS);
8528 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8529 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8530 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8533 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8534 if (!SystemSupportsOCSP()) {
8535 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8539 SpawnedTestServer::SSLOptions ssl_options(
8540 SpawnedTestServer::SSLOptions::CERT_AUTO);
8541 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8542 SSLConfigService::SetCRLSet(
8543 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8544 false, &kOCSPTestCertSPKI, "")));
8546 CertStatus cert_status;
8547 DoConnection(ssl_options, &cert_status);
8549 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8550 // revocation check for EV.
8551 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8552 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8553 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8555 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8558 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8559 if (!SystemSupportsOCSP()) {
8560 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8564 SpawnedTestServer::SSLOptions ssl_options(
8565 SpawnedTestServer::SSLOptions::CERT_AUTO);
8566 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8567 SSLConfigService::SetCRLSet(
8568 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8570 CertStatus cert_status = 0;
8571 DoConnection(ssl_options, &cert_status);
8573 // Even with a fresh CRLSet, we should still do online revocation checks when
8574 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8576 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8577 cert_status & CERT_STATUS_ALL_ERRORS);
8579 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8580 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8581 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8584 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8585 // Test that when EV verification is requested, but online revocation
8586 // checking is disabled, and the leaf certificate is not in fact EV, that
8587 // no revocation checking actually happens.
8588 if (!SystemSupportsOCSP()) {
8589 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8593 // Unmark the certificate's OID as EV, which should disable revocation
8594 // checking (as per the user preference)
8595 ev_test_policy_.reset();
8597 SpawnedTestServer::SSLOptions ssl_options(
8598 SpawnedTestServer::SSLOptions::CERT_AUTO);
8599 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8600 SSLConfigService::SetCRLSet(
8601 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8603 CertStatus cert_status;
8604 DoConnection(ssl_options, &cert_status);
8606 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8608 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8609 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8612 class HTTPSCRLSetTest : public HTTPSOCSPTest {
8614 void SetupContext(URLRequestContext* context) override {
8615 context->set_ssl_config_service(
8616 new TestSSLConfigService(false /* check for EV */,
8617 false /* online revocation checking */,
8618 false /* require rev. checking for local
8623 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
8624 SpawnedTestServer::SSLOptions ssl_options(
8625 SpawnedTestServer::SSLOptions::CERT_AUTO);
8626 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8627 SSLConfigService::SetCRLSet(
8628 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8630 CertStatus cert_status;
8631 DoConnection(ssl_options, &cert_status);
8633 // If we're not trying EV verification then, even if the CRLSet has expired,
8634 // we don't fall back to online revocation checks.
8635 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8636 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8637 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8640 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
8641 #if defined(OS_ANDROID)
8642 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8646 SpawnedTestServer::SSLOptions ssl_options(
8647 SpawnedTestServer::SSLOptions::CERT_AUTO);
8648 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8649 ssl_options.cert_serial = 10;
8650 SSLConfigService::SetCRLSet(
8651 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8652 false, &kOCSPTestCertSPKI, "\x0a")));
8654 CertStatus cert_status = 0;
8655 DoConnection(ssl_options, &cert_status);
8657 // If the certificate is recorded as revoked in the CRLSet, that should be
8658 // reflected without online revocation checking.
8659 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8660 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8662 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8664 #endif // !defined(OS_IOS)
8666 #if !defined(DISABLE_FTP_SUPPORT)
8667 class URLRequestTestFTP : public URLRequestTest {
8670 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
8675 SpawnedTestServer test_server_;
8678 // Make sure an FTP request using an unsafe ports fails.
8679 TEST_F(URLRequestTestFTP, UnsafePort) {
8680 ASSERT_TRUE(test_server_.Start());
8682 URLRequestJobFactoryImpl job_factory;
8683 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
8685 GURL url("ftp://127.0.0.1:7");
8686 job_factory.SetProtocolHandler(
8688 new FtpProtocolHandler(&ftp_transaction_factory));
8689 default_context_.set_job_factory(&job_factory);
8693 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8694 url, DEFAULT_PRIORITY, &d, NULL));
8696 EXPECT_TRUE(r->is_pending());
8698 base::RunLoop().Run();
8700 EXPECT_FALSE(r->is_pending());
8701 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8702 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
8706 // Flaky, see http://crbug.com/25045.
8707 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
8708 ASSERT_TRUE(test_server_.Start());
8712 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8713 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, NULL));
8715 EXPECT_TRUE(r->is_pending());
8717 base::RunLoop().Run();
8719 EXPECT_FALSE(r->is_pending());
8720 EXPECT_EQ(1, d.response_started_count());
8721 EXPECT_FALSE(d.received_data_before_response());
8722 EXPECT_LT(0, d.bytes_received());
8723 EXPECT_EQ(test_server_.host_port_pair().host(),
8724 r->GetSocketAddress().host());
8725 EXPECT_EQ(test_server_.host_port_pair().port(),
8726 r->GetSocketAddress().port());
8730 // Flaky, see http://crbug.com/25045.
8731 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
8732 ASSERT_TRUE(test_server_.Start());
8734 base::FilePath app_path;
8735 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8736 app_path = app_path.AppendASCII("LICENSE");
8739 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8740 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d, NULL));
8742 EXPECT_TRUE(r->is_pending());
8744 base::RunLoop().Run();
8746 int64 file_size = 0;
8747 base::GetFileSize(app_path, &file_size);
8749 EXPECT_FALSE(r->is_pending());
8750 EXPECT_EQ(1, d.response_started_count());
8751 EXPECT_FALSE(d.received_data_before_response());
8752 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8753 EXPECT_EQ(test_server_.host_port_pair().host(),
8754 r->GetSocketAddress().host());
8755 EXPECT_EQ(test_server_.host_port_pair().port(),
8756 r->GetSocketAddress().port());
8760 // Flaky, see http://crbug.com/25045.
8761 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
8762 ASSERT_TRUE(test_server_.Start());
8764 base::FilePath app_path;
8765 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8766 app_path = app_path.AppendASCII("LICENSE");
8769 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8770 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8771 DEFAULT_PRIORITY, &d, NULL));
8773 EXPECT_TRUE(r->is_pending());
8775 base::RunLoop().Run();
8777 int64 file_size = 0;
8778 base::GetFileSize(app_path, &file_size);
8780 EXPECT_FALSE(r->is_pending());
8781 EXPECT_EQ(test_server_.host_port_pair().host(),
8782 r->GetSocketAddress().host());
8783 EXPECT_EQ(test_server_.host_port_pair().port(),
8784 r->GetSocketAddress().port());
8785 EXPECT_EQ(1, d.response_started_count());
8786 EXPECT_FALSE(d.received_data_before_response());
8787 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8789 LoadTimingInfo load_timing_info;
8790 r->GetLoadTimingInfo(&load_timing_info);
8791 TestLoadTimingNoHttpResponse(load_timing_info);
8795 // Flaky, see http://crbug.com/25045.
8796 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
8797 ASSERT_TRUE(test_server_.Start());
8799 base::FilePath app_path;
8800 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8801 app_path = app_path.AppendASCII("LICENSE");
8804 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8805 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8807 DEFAULT_PRIORITY, &d, NULL));
8809 EXPECT_TRUE(r->is_pending());
8811 base::RunLoop().Run();
8813 int64 file_size = 0;
8814 base::GetFileSize(app_path, &file_size);
8816 EXPECT_FALSE(r->is_pending());
8817 EXPECT_EQ(1, d.response_started_count());
8818 EXPECT_FALSE(d.received_data_before_response());
8819 EXPECT_EQ(d.bytes_received(), 0);
8823 // Flaky, see http://crbug.com/25045.
8824 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
8825 ASSERT_TRUE(test_server_.Start());
8827 base::FilePath app_path;
8828 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8829 app_path = app_path.AppendASCII("LICENSE");
8831 // Set correct login credentials. The delegate will be asked for them when
8832 // the initial login with wrong credentials will fail.
8833 d.set_credentials(AuthCredentials(kChrome, kChrome));
8835 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8836 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8838 DEFAULT_PRIORITY, &d, NULL));
8840 EXPECT_TRUE(r->is_pending());
8842 base::RunLoop().Run();
8844 int64 file_size = 0;
8845 base::GetFileSize(app_path, &file_size);
8847 EXPECT_FALSE(r->is_pending());
8848 EXPECT_EQ(1, d.response_started_count());
8849 EXPECT_FALSE(d.received_data_before_response());
8850 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8854 // Flaky, see http://crbug.com/25045.
8855 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
8856 ASSERT_TRUE(test_server_.Start());
8858 base::FilePath app_path;
8859 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8860 app_path = app_path.AppendASCII("LICENSE");
8863 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8864 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8866 DEFAULT_PRIORITY, &d, NULL));
8868 EXPECT_TRUE(r->is_pending());
8870 base::RunLoop().Run();
8872 int64 file_size = 0;
8873 base::GetFileSize(app_path, &file_size);
8875 EXPECT_FALSE(r->is_pending());
8876 EXPECT_EQ(1, d.response_started_count());
8877 EXPECT_FALSE(d.received_data_before_response());
8878 EXPECT_EQ(d.bytes_received(), 0);
8882 // Flaky, see http://crbug.com/25045.
8883 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
8884 ASSERT_TRUE(test_server_.Start());
8886 base::FilePath app_path;
8887 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8888 app_path = app_path.AppendASCII("LICENSE");
8890 // Set correct login credentials. The delegate will be asked for them when
8891 // the initial login with wrong credentials will fail.
8892 d.set_credentials(AuthCredentials(kChrome, kChrome));
8894 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8895 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8897 DEFAULT_PRIORITY, &d, NULL));
8899 EXPECT_TRUE(r->is_pending());
8901 base::RunLoop().Run();
8903 int64 file_size = 0;
8904 base::GetFileSize(app_path, &file_size);
8906 EXPECT_FALSE(r->is_pending());
8907 EXPECT_EQ(1, d.response_started_count());
8908 EXPECT_FALSE(d.received_data_before_response());
8909 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8913 // Flaky, see http://crbug.com/25045.
8914 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
8915 ASSERT_TRUE(test_server_.Start());
8917 base::FilePath app_path;
8918 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8919 app_path = app_path.AppendASCII("LICENSE");
8921 scoped_ptr<TestDelegate> d(new TestDelegate);
8923 // Pass correct login identity in the URL.
8924 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8925 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8926 DEFAULT_PRIORITY, d.get(), NULL));
8928 EXPECT_TRUE(r->is_pending());
8930 base::RunLoop().Run();
8932 int64 file_size = 0;
8933 base::GetFileSize(app_path, &file_size);
8935 EXPECT_FALSE(r->is_pending());
8936 EXPECT_EQ(1, d->response_started_count());
8937 EXPECT_FALSE(d->received_data_before_response());
8938 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8941 d.reset(new TestDelegate);
8943 // This request should use cached identity from previous request.
8944 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8945 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
8947 EXPECT_TRUE(r->is_pending());
8949 base::RunLoop().Run();
8951 int64 file_size = 0;
8952 base::GetFileSize(app_path, &file_size);
8954 EXPECT_FALSE(r->is_pending());
8955 EXPECT_EQ(1, d->response_started_count());
8956 EXPECT_FALSE(d->received_data_before_response());
8957 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8961 // Flaky, see http://crbug.com/25045.
8962 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
8963 ASSERT_TRUE(test_server_.Start());
8965 base::FilePath app_path;
8966 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8967 app_path = app_path.AppendASCII("LICENSE");
8969 scoped_ptr<TestDelegate> d(new TestDelegate);
8970 // Set correct login credentials. The delegate will be asked for them when
8971 // the initial login with wrong credentials will fail.
8972 d->set_credentials(AuthCredentials(kChrome, kChrome));
8974 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8975 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8977 DEFAULT_PRIORITY, d.get(), NULL));
8979 EXPECT_TRUE(r->is_pending());
8981 base::RunLoop().Run();
8983 int64 file_size = 0;
8984 base::GetFileSize(app_path, &file_size);
8986 EXPECT_FALSE(r->is_pending());
8987 EXPECT_EQ(1, d->response_started_count());
8988 EXPECT_FALSE(d->received_data_before_response());
8989 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8992 // Use a new delegate without explicit credentials. The cached ones should be
8994 d.reset(new TestDelegate);
8996 // Don't pass wrong credentials in the URL, they would override valid cached
8998 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8999 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
9001 EXPECT_TRUE(r->is_pending());
9003 base::RunLoop().Run();
9005 int64 file_size = 0;
9006 base::GetFileSize(app_path, &file_size);
9008 EXPECT_FALSE(r->is_pending());
9009 EXPECT_EQ(1, d->response_started_count());
9010 EXPECT_FALSE(d->received_data_before_response());
9011 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9014 #endif // !defined(DISABLE_FTP_SUPPORT)