Don't add an aura tooltip to bubble close buttons on Windows.
[chromium-blink-merge.git] / net / url_request / url_request_unittest.cc
blob52b63a1591710ddabd2d7d0c39d731cdd82c201e
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "build/build_config.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shlobj.h>
10 #endif
12 #include <algorithm>
14 #include "base/basictypes.h"
15 #include "base/bind.h"
16 #include "base/compiler_specific.h"
17 #include "base/files/file_util.h"
18 #include "base/files/scoped_temp_dir.h"
19 #include "base/format_macros.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/message_loop/message_loop.h"
23 #include "base/message_loop/message_loop_proxy.h"
24 #include "base/path_service.h"
25 #include "base/run_loop.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/stringprintf.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "net/base/chunked_upload_data_stream.h"
33 #include "net/base/elements_upload_data_stream.h"
34 #include "net/base/load_flags.h"
35 #include "net/base/load_timing_info.h"
36 #include "net/base/load_timing_info_test_util.h"
37 #include "net/base/net_errors.h"
38 #include "net/base/net_module.h"
39 #include "net/base/net_util.h"
40 #include "net/base/request_priority.h"
41 #include "net/base/test_data_directory.h"
42 #include "net/base/upload_bytes_element_reader.h"
43 #include "net/base/upload_data_stream.h"
44 #include "net/base/upload_file_element_reader.h"
45 #include "net/cert/ev_root_ca_metadata.h"
46 #include "net/cert/mock_cert_verifier.h"
47 #include "net/cert/test_root_certs.h"
48 #include "net/cookies/cookie_monster.h"
49 #include "net/cookies/cookie_store_test_helpers.h"
50 #include "net/disk_cache/disk_cache.h"
51 #include "net/dns/mock_host_resolver.h"
52 #include "net/ftp/ftp_network_layer.h"
53 #include "net/http/http_byte_range.h"
54 #include "net/http/http_cache.h"
55 #include "net/http/http_network_layer.h"
56 #include "net/http/http_network_session.h"
57 #include "net/http/http_request_headers.h"
58 #include "net/http/http_response_headers.h"
59 #include "net/http/http_util.h"
60 #include "net/log/capturing_net_log.h"
61 #include "net/log/net_log.h"
62 #include "net/log/net_log_unittest.h"
63 #include "net/ocsp/nss_ocsp.h"
64 #include "net/proxy/proxy_service.h"
65 #include "net/socket/ssl_client_socket.h"
66 #include "net/ssl/ssl_cipher_suite_names.h"
67 #include "net/ssl/ssl_connection_status_flags.h"
68 #include "net/test/cert_test_util.h"
69 #include "net/test/spawned_test_server/spawned_test_server.h"
70 #include "net/url_request/data_protocol_handler.h"
71 #include "net/url_request/static_http_user_agent_settings.h"
72 #include "net/url_request/url_request.h"
73 #include "net/url_request/url_request_http_job.h"
74 #include "net/url_request/url_request_intercepting_job_factory.h"
75 #include "net/url_request/url_request_interceptor.h"
76 #include "net/url_request/url_request_job_factory_impl.h"
77 #include "net/url_request/url_request_redirect_job.h"
78 #include "net/url_request/url_request_test_job.h"
79 #include "net/url_request/url_request_test_util.h"
80 #include "testing/gtest/include/gtest/gtest.h"
81 #include "testing/platform_test.h"
83 #if !defined(DISABLE_FILE_SUPPORT)
84 #include "net/base/filename_util.h"
85 #include "net/url_request/file_protocol_handler.h"
86 #include "net/url_request/url_request_file_dir_job.h"
87 #endif
89 #if !defined(DISABLE_FTP_SUPPORT)
90 #include "net/url_request/ftp_protocol_handler.h"
91 #endif
93 #if defined(OS_WIN)
94 #include "base/win/scoped_com_initializer.h"
95 #include "base/win/scoped_comptr.h"
96 #include "base/win/windows_version.h"
97 #endif
99 using base::ASCIIToUTF16;
100 using base::Time;
101 using std::string;
103 namespace net {
105 namespace {
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
112 // no proxy.
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) {
182 return "header";
185 void FillBuffer(char* buffer, size_t len) {
186 static bool called = false;
187 if (!called) {
188 called = true;
189 int seed = static_cast<int>(Time::Now().ToInternalValue());
190 srand(seed);
193 for (size_t i = 0; i < len; i++) {
194 buffer[i] = static_cast<char>(rand());
195 if (!buffer[i])
196 buffer[i] = 'g';
200 #if !defined(OS_IOS)
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(),
242 haystack.end(),
243 needle,
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 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
262 ssl_info.connection_status);
263 EXPECT_NE(0U, 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())
281 return false;
283 for (size_t i = 0; i < size; ++i) {
284 if (!a[i].Equals(b[i]))
285 return false;
288 return true;
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,
296 // or
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 {
303 public:
304 // Stages in which the delegate can block.
305 enum Stage {
306 NOT_BLOCKED = 0,
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.
315 enum BlockMode {
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);
333 // Setters.
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);
338 retval_ = 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) {
353 redirect_url_ = 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_;
366 private:
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(
381 URLRequest* request,
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(
388 URLRequest* request,
389 const AuthChallengeInfo& auth_info,
390 const AuthCallback& callback,
391 AuthCredentials* credentials) override;
393 // Resets the callbacks and |stage_blocked_for_callback_|.
394 void Reset();
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
412 // callback.
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_| !=
418 // USER_CALLBACK).
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),
432 retval_(OK),
433 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
434 block_on_(0),
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_;
445 Reset();
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_;
454 Reset();
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(
473 URLRequest* request,
474 const CompletionCallback& callback,
475 GURL* new_url) {
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(
488 URLRequest* request,
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(
497 URLRequest* request,
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,
503 callback,
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(
512 URLRequest* request,
513 const AuthChallengeInfo& auth_info,
514 const AuthCallback& callback,
515 AuthCredentials* credentials) {
516 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
517 credentials);
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_) {
528 case SYNCHRONOUS:
529 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
530 *target_auth_credentials_ = auth_credentials_;
531 return auth_retval_;
533 case AUTO_CALLBACK:
534 base::MessageLoop::current()->PostTask(
535 FROM_HERE,
536 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
537 weak_factory_.GetWeakPtr(), auth_retval_, callback));
538 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
540 case USER_CALLBACK:
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;
547 NOTREACHED();
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;
554 callback_.Reset();
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) {
565 return OK;
568 switch (block_mode_) {
569 case SYNCHRONOUS:
570 EXPECT_NE(OK, retval_);
571 return retval_;
573 case AUTO_CALLBACK:
574 base::MessageLoop::current()->PostTask(
575 FROM_HERE,
576 base::Bind(&BlockingNetworkDelegate::RunCallback,
577 weak_factory_.GetWeakPtr(), retval_, callback));
578 return ERR_IO_PENDING;
580 case USER_CALLBACK:
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;
587 NOTREACHED();
588 return 0;
591 class TestURLRequestContextWithProxy : public TestURLRequestContext {
592 public:
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);
599 Init();
601 ~TestURLRequestContextWithProxy() override {}
604 } // namespace
606 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
607 class URLRequestTest : public PlatformTest {
608 public:
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 void SetUp() override {
622 SetUpFactory();
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()));
633 #endif
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_;
653 protected:
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) {
662 TestDelegate d;
664 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
665 GURL("about:blank"), DEFAULT_PRIORITY, &d));
667 r->Start();
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) {
684 TestDelegate d;
686 // Use our nice little Chrome logo.
687 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
688 GURL(
689 "data:image/png;base64,"
690 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
691 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
692 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
693 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
694 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
695 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
696 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
697 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
698 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
699 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
700 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
701 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
702 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
703 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
704 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
705 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
706 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
707 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
708 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
709 DEFAULT_PRIORITY, &d));
711 r->Start();
712 EXPECT_TRUE(r->is_pending());
714 base::RunLoop().Run();
716 EXPECT_TRUE(!r->is_pending());
717 EXPECT_FALSE(d.received_data_before_response());
718 EXPECT_EQ(d.bytes_received(), 911);
719 EXPECT_EQ("", r->GetSocketAddress().host());
720 EXPECT_EQ(0, r->GetSocketAddress().port());
722 HttpRequestHeaders headers;
723 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
727 #if !defined(DISABLE_FILE_SUPPORT)
728 TEST_F(URLRequestTest, FileTest) {
729 base::FilePath app_path;
730 PathService::Get(base::FILE_EXE, &app_path);
731 GURL app_url = FilePathToFileURL(app_path);
733 TestDelegate d;
735 scoped_ptr<URLRequest> r(
736 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
738 r->Start();
739 EXPECT_TRUE(r->is_pending());
741 base::RunLoop().Run();
743 int64 file_size = -1;
744 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
746 EXPECT_TRUE(!r->is_pending());
747 EXPECT_EQ(1, d.response_started_count());
748 EXPECT_FALSE(d.received_data_before_response());
749 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
750 EXPECT_EQ("", r->GetSocketAddress().host());
751 EXPECT_EQ(0, r->GetSocketAddress().port());
753 HttpRequestHeaders headers;
754 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
758 TEST_F(URLRequestTest, FileTestCancel) {
759 base::FilePath app_path;
760 PathService::Get(base::FILE_EXE, &app_path);
761 GURL app_url = FilePathToFileURL(app_path);
763 TestDelegate d;
765 scoped_ptr<URLRequest> r(
766 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
768 r->Start();
769 EXPECT_TRUE(r->is_pending());
770 r->Cancel();
772 // Async cancellation should be safe even when URLRequest has been already
773 // destroyed.
774 base::RunLoop().RunUntilIdle();
777 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
778 const size_t buffer_size = 4000;
779 scoped_ptr<char[]> buffer(new char[buffer_size]);
780 FillBuffer(buffer.get(), buffer_size);
782 base::FilePath temp_path;
783 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
784 GURL temp_url = FilePathToFileURL(temp_path);
785 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
787 int64 file_size;
788 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
790 const size_t first_byte_position = 500;
791 const size_t last_byte_position = buffer_size - first_byte_position;
792 const size_t content_length = last_byte_position - first_byte_position + 1;
793 std::string partial_buffer_string(buffer.get() + first_byte_position,
794 buffer.get() + last_byte_position + 1);
796 TestDelegate d;
798 scoped_ptr<URLRequest> r(
799 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
801 HttpRequestHeaders headers;
802 headers.SetHeader(
803 HttpRequestHeaders::kRange,
804 HttpByteRange::Bounded(
805 first_byte_position, last_byte_position).GetHeaderValue());
806 r->SetExtraRequestHeaders(headers);
807 r->Start();
808 EXPECT_TRUE(r->is_pending());
810 base::RunLoop().Run();
811 EXPECT_TRUE(!r->is_pending());
812 EXPECT_EQ(1, d.response_started_count());
813 EXPECT_FALSE(d.received_data_before_response());
814 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
815 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
816 EXPECT_TRUE(partial_buffer_string == d.data_received());
819 EXPECT_TRUE(base::DeleteFile(temp_path, false));
822 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
823 const size_t buffer_size = 4000;
824 scoped_ptr<char[]> buffer(new char[buffer_size]);
825 FillBuffer(buffer.get(), buffer_size);
827 base::FilePath temp_path;
828 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
829 GURL temp_url = FilePathToFileURL(temp_path);
830 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
832 int64 file_size;
833 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
835 const size_t first_byte_position = 500;
836 const size_t last_byte_position = buffer_size - 1;
837 const size_t content_length = last_byte_position - first_byte_position + 1;
838 std::string partial_buffer_string(buffer.get() + first_byte_position,
839 buffer.get() + last_byte_position + 1);
841 TestDelegate d;
843 scoped_ptr<URLRequest> r(
844 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
846 HttpRequestHeaders headers;
847 headers.SetHeader(HttpRequestHeaders::kRange,
848 HttpByteRange::RightUnbounded(
849 first_byte_position).GetHeaderValue());
850 r->SetExtraRequestHeaders(headers);
851 r->Start();
852 EXPECT_TRUE(r->is_pending());
854 base::RunLoop().Run();
855 EXPECT_TRUE(!r->is_pending());
856 EXPECT_EQ(1, d.response_started_count());
857 EXPECT_FALSE(d.received_data_before_response());
858 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
859 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
860 EXPECT_TRUE(partial_buffer_string == d.data_received());
863 EXPECT_TRUE(base::DeleteFile(temp_path, false));
866 TEST_F(URLRequestTest, FileTestMultipleRanges) {
867 const size_t buffer_size = 400000;
868 scoped_ptr<char[]> buffer(new char[buffer_size]);
869 FillBuffer(buffer.get(), buffer_size);
871 base::FilePath temp_path;
872 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
873 GURL temp_url = FilePathToFileURL(temp_path);
874 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
876 int64 file_size;
877 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
879 TestDelegate d;
881 scoped_ptr<URLRequest> r(
882 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
884 HttpRequestHeaders headers;
885 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
886 r->SetExtraRequestHeaders(headers);
887 r->Start();
888 EXPECT_TRUE(r->is_pending());
890 base::RunLoop().Run();
891 EXPECT_TRUE(d.request_failed());
894 EXPECT_TRUE(base::DeleteFile(temp_path, false));
897 TEST_F(URLRequestTest, AllowFileURLs) {
898 base::ScopedTempDir temp_dir;
899 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
900 base::FilePath test_file;
901 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
902 std::string test_data("monkey");
903 base::WriteFile(test_file, test_data.data(), test_data.size());
904 GURL test_file_url = FilePathToFileURL(test_file);
907 TestDelegate d;
908 TestNetworkDelegate network_delegate;
909 network_delegate.set_can_access_files(true);
910 default_context_.set_network_delegate(&network_delegate);
911 scoped_ptr<URLRequest> r(
912 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
913 r->Start();
914 base::RunLoop().Run();
915 EXPECT_FALSE(d.request_failed());
916 EXPECT_EQ(test_data, d.data_received());
920 TestDelegate d;
921 TestNetworkDelegate network_delegate;
922 network_delegate.set_can_access_files(false);
923 default_context_.set_network_delegate(&network_delegate);
924 scoped_ptr<URLRequest> r(
925 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
926 r->Start();
927 base::RunLoop().Run();
928 EXPECT_TRUE(d.request_failed());
929 EXPECT_EQ("", d.data_received());
934 TEST_F(URLRequestTest, FileDirCancelTest) {
935 // Put in mock resource provider.
936 NetModule::SetResourceProvider(TestNetResourceProvider);
938 TestDelegate d;
940 base::FilePath file_path;
941 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
942 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
943 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
945 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
946 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
947 req->Start();
948 EXPECT_TRUE(req->is_pending());
950 d.set_cancel_in_received_data_pending(true);
952 base::RunLoop().Run();
955 // Take out mock resource provider.
956 NetModule::SetResourceProvider(NULL);
959 TEST_F(URLRequestTest, FileDirOutputSanity) {
960 // Verify the general sanity of the the output of the file:
961 // directory lister by checking for the output of a known existing
962 // file.
963 const char sentinel_name[] = "filedir-sentinel";
965 base::FilePath path;
966 PathService::Get(base::DIR_SOURCE_ROOT, &path);
967 path = path.Append(FILE_PATH_LITERAL("net"));
968 path = path.Append(FILE_PATH_LITERAL("data"));
969 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
971 TestDelegate d;
972 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
973 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
974 req->Start();
975 base::RunLoop().Run();
977 // Generate entry for the sentinel file.
978 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
979 base::File::Info info;
980 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
981 EXPECT_GT(info.size, 0);
982 std::string sentinel_output = GetDirectoryListingEntry(
983 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
984 std::string(sentinel_name),
985 false /* is_dir */,
986 info.size,
987 info.last_modified);
989 ASSERT_LT(0, d.bytes_received());
990 ASSERT_FALSE(d.request_failed());
991 ASSERT_TRUE(req->status().is_success());
992 // Check for the entry generated for the "sentinel" file.
993 const std::string& data = d.data_received();
994 ASSERT_NE(data.find(sentinel_output), std::string::npos);
997 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
998 // There is an implicit redirect when loading a file path that matches a
999 // directory and does not end with a slash. Ensure that following such
1000 // redirects does not crash. See http://crbug.com/18686.
1002 base::FilePath path;
1003 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1004 path = path.Append(FILE_PATH_LITERAL("net"));
1005 path = path.Append(FILE_PATH_LITERAL("data"));
1006 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1008 TestDelegate d;
1009 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1010 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
1011 req->Start();
1012 base::RunLoop().Run();
1014 ASSERT_EQ(1, d.received_redirect_count());
1015 ASSERT_LT(0, d.bytes_received());
1016 ASSERT_FALSE(d.request_failed());
1017 ASSERT_TRUE(req->status().is_success());
1020 #if defined(OS_WIN)
1021 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1022 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1023 TestDelegate d;
1024 scoped_ptr<URLRequest> req(
1025 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
1026 req->Start();
1027 base::RunLoop().Run();
1029 ASSERT_EQ(1, d.received_redirect_count());
1030 ASSERT_FALSE(req->status().is_success());
1032 #endif // defined(OS_WIN)
1034 #endif // !defined(DISABLE_FILE_SUPPORT)
1036 TEST_F(URLRequestTest, InvalidUrlTest) {
1037 TestDelegate d;
1039 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1040 GURL("invalid url"), DEFAULT_PRIORITY, &d));
1042 r->Start();
1043 EXPECT_TRUE(r->is_pending());
1045 base::RunLoop().Run();
1046 EXPECT_TRUE(d.request_failed());
1050 TEST_F(URLRequestTest, InvalidReferrerTest) {
1051 TestURLRequestContext context;
1052 TestNetworkDelegate network_delegate;
1053 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1054 context.set_network_delegate(&network_delegate);
1055 TestDelegate d;
1056 scoped_ptr<URLRequest> req(
1057 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
1058 req->SetReferrer("https://somewhere.com/");
1060 req->Start();
1061 base::RunLoop().Run();
1062 EXPECT_TRUE(d.request_failed());
1065 #if defined(OS_WIN)
1066 TEST_F(URLRequestTest, ResolveShortcutTest) {
1067 base::FilePath app_path;
1068 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1069 app_path = app_path.AppendASCII("net");
1070 app_path = app_path.AppendASCII("data");
1071 app_path = app_path.AppendASCII("url_request_unittest");
1072 app_path = app_path.AppendASCII("with-headers.html");
1074 std::wstring lnk_path = app_path.value() + L".lnk";
1076 base::win::ScopedCOMInitializer com_initializer;
1078 // Temporarily create a shortcut for test
1080 base::win::ScopedComPtr<IShellLink> shell;
1081 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1082 CLSCTX_INPROC_SERVER)));
1083 base::win::ScopedComPtr<IPersistFile> persist;
1084 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1085 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1086 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1087 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1090 TestDelegate d;
1092 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1093 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
1095 r->Start();
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]);
1108 DWORD read_size;
1109 BOOL result;
1110 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1111 &read_size, NULL);
1112 std::string content(buffer.get(), read_size);
1113 CloseHandle(file);
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 {
1127 public:
1128 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1129 : URLRequestTestJob(request, network_delegate, true) {}
1130 protected:
1131 void StartAsync() override { this->NotifyRestartRequired(); }
1132 private:
1133 ~RestartTestJob() override {}
1136 class CancelTestJob : public URLRequestTestJob {
1137 public:
1138 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1139 : URLRequestTestJob(request, network_delegate, true) {}
1140 protected:
1141 void StartAsync() override { request_->Cancel(); }
1142 private:
1143 ~CancelTestJob() override {}
1146 class CancelThenRestartTestJob : public URLRequestTestJob {
1147 public:
1148 explicit CancelThenRestartTestJob(URLRequest* request,
1149 NetworkDelegate* network_delegate)
1150 : URLRequestTestJob(request, network_delegate, true) {
1152 protected:
1153 void StartAsync() override {
1154 request_->Cancel();
1155 this->NotifyRestartRequired();
1157 private:
1158 ~CancelThenRestartTestJob() override {}
1161 // An Interceptor for use with interceptor tests.
1162 class MockURLRequestInterceptor : public URLRequestInterceptor {
1163 public:
1164 // Static getters for canned response header and data strings.
1165 static std::string ok_data() {
1166 return URLRequestTestJob::test_data_1();
1169 static std::string ok_headers() {
1170 return URLRequestTestJob::test_headers();
1173 static std::string redirect_data() {
1174 return std::string();
1177 static std::string redirect_headers() {
1178 return URLRequestTestJob::test_redirect_headers();
1181 static std::string error_data() {
1182 return std::string("ohhh nooooo mr. bill!");
1185 static std::string error_headers() {
1186 return URLRequestTestJob::test_error_headers();
1189 MockURLRequestInterceptor()
1190 : intercept_main_request_(false), restart_main_request_(false),
1191 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1192 simulate_main_network_error_(false),
1193 intercept_redirect_(false), cancel_redirect_request_(false),
1194 intercept_final_response_(false), cancel_final_request_(false),
1195 use_url_request_http_job_(false),
1196 did_intercept_main_(false), did_restart_main_(false),
1197 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1198 did_simulate_error_main_(false),
1199 did_intercept_redirect_(false), did_cancel_redirect_(false),
1200 did_intercept_final_(false), did_cancel_final_(false) {
1203 ~MockURLRequestInterceptor() override {
1206 // URLRequestInterceptor implementation:
1207 URLRequestJob* MaybeInterceptRequest(
1208 URLRequest* request,
1209 NetworkDelegate* network_delegate) const override {
1210 if (restart_main_request_) {
1211 restart_main_request_ = false;
1212 did_restart_main_ = true;
1213 return new RestartTestJob(request, network_delegate);
1215 if (cancel_main_request_) {
1216 cancel_main_request_ = false;
1217 did_cancel_main_ = true;
1218 return new CancelTestJob(request, network_delegate);
1220 if (cancel_then_restart_main_request_) {
1221 cancel_then_restart_main_request_ = false;
1222 did_cancel_then_restart_main_ = true;
1223 return new CancelThenRestartTestJob(request, network_delegate);
1225 if (simulate_main_network_error_) {
1226 simulate_main_network_error_ = false;
1227 did_simulate_error_main_ = true;
1228 if (use_url_request_http_job_) {
1229 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1231 // This job will result in error since the requested URL is not one of the
1232 // URLs supported by these tests.
1233 return new URLRequestTestJob(request, network_delegate, true);
1235 if (!intercept_main_request_)
1236 return nullptr;
1237 intercept_main_request_ = false;
1238 did_intercept_main_ = true;
1239 URLRequestTestJob* job = new URLRequestTestJob(request,
1240 network_delegate,
1241 main_headers_,
1242 main_data_,
1243 true);
1244 job->set_load_timing_info(main_request_load_timing_info_);
1245 return job;
1248 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1249 NetworkDelegate* network_delegate,
1250 const GURL& location) const override {
1251 if (cancel_redirect_request_) {
1252 cancel_redirect_request_ = false;
1253 did_cancel_redirect_ = true;
1254 return new CancelTestJob(request, network_delegate);
1256 if (!intercept_redirect_)
1257 return nullptr;
1258 intercept_redirect_ = false;
1259 did_intercept_redirect_ = true;
1260 if (use_url_request_http_job_) {
1261 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1263 return new URLRequestTestJob(request,
1264 network_delegate,
1265 redirect_headers_,
1266 redirect_data_,
1267 true);
1270 URLRequestJob* MaybeInterceptResponse(
1271 URLRequest* request,
1272 NetworkDelegate* network_delegate) const override {
1273 if (cancel_final_request_) {
1274 cancel_final_request_ = false;
1275 did_cancel_final_ = true;
1276 return new CancelTestJob(request, network_delegate);
1278 if (!intercept_final_response_)
1279 return nullptr;
1280 intercept_final_response_ = false;
1281 did_intercept_final_ = true;
1282 if (use_url_request_http_job_) {
1283 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1285 return new URLRequestTestJob(request,
1286 network_delegate,
1287 final_headers_,
1288 final_data_,
1289 true);
1292 void set_intercept_main_request(bool intercept_main_request) {
1293 intercept_main_request_ = intercept_main_request;
1296 void set_main_headers(const std::string& main_headers) {
1297 main_headers_ = main_headers;
1300 void set_main_data(const std::string& main_data) {
1301 main_data_ = main_data;
1304 void set_main_request_load_timing_info(
1305 const LoadTimingInfo& main_request_load_timing_info) {
1306 main_request_load_timing_info_ = main_request_load_timing_info;
1309 void set_restart_main_request(bool restart_main_request) {
1310 restart_main_request_ = restart_main_request;
1313 void set_cancel_main_request(bool cancel_main_request) {
1314 cancel_main_request_ = cancel_main_request;
1317 void set_cancel_then_restart_main_request(
1318 bool cancel_then_restart_main_request) {
1319 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1322 void set_simulate_main_network_error(bool simulate_main_network_error) {
1323 simulate_main_network_error_ = simulate_main_network_error;
1326 void set_intercept_redirect(bool intercept_redirect) {
1327 intercept_redirect_ = intercept_redirect;
1330 void set_redirect_headers(const std::string& redirect_headers) {
1331 redirect_headers_ = redirect_headers;
1334 void set_redirect_data(const std::string& redirect_data) {
1335 redirect_data_ = redirect_data;
1338 void set_cancel_redirect_request(bool cancel_redirect_request) {
1339 cancel_redirect_request_ = cancel_redirect_request;
1342 void set_intercept_final_response(bool intercept_final_response) {
1343 intercept_final_response_ = intercept_final_response;
1346 void set_final_headers(const std::string& final_headers) {
1347 final_headers_ = final_headers;
1350 void set_final_data(const std::string& final_data) {
1351 final_data_ = final_data;
1354 void set_cancel_final_request(bool cancel_final_request) {
1355 cancel_final_request_ = cancel_final_request;
1358 void set_use_url_request_http_job(bool use_url_request_http_job) {
1359 use_url_request_http_job_ = use_url_request_http_job;
1362 bool did_intercept_main() const {
1363 return did_intercept_main_;
1366 bool did_restart_main() const {
1367 return did_restart_main_;
1370 bool did_cancel_main() const {
1371 return did_cancel_main_;
1374 bool did_cancel_then_restart_main() const {
1375 return did_cancel_then_restart_main_;
1378 bool did_simulate_error_main() const {
1379 return did_simulate_error_main_;
1382 bool did_intercept_redirect() const {
1383 return did_intercept_redirect_;
1386 bool did_cancel_redirect() const {
1387 return did_cancel_redirect_;
1390 bool did_intercept_final() const {
1391 return did_intercept_final_;
1394 bool did_cancel_final() const {
1395 return did_cancel_final_;
1398 private:
1399 // Indicate whether to intercept the main request, and if so specify the
1400 // response to return and the LoadTimingInfo to use.
1401 mutable bool intercept_main_request_;
1402 mutable std::string main_headers_;
1403 mutable std::string main_data_;
1404 mutable LoadTimingInfo main_request_load_timing_info_;
1406 // These indicate actions that can be taken within MaybeInterceptRequest.
1407 mutable bool restart_main_request_;
1408 mutable bool cancel_main_request_;
1409 mutable bool cancel_then_restart_main_request_;
1410 mutable bool simulate_main_network_error_;
1412 // Indicate whether to intercept redirects, and if so specify the response to
1413 // return.
1414 mutable bool intercept_redirect_;
1415 mutable std::string redirect_headers_;
1416 mutable std::string redirect_data_;
1418 // Cancel the request within MaybeInterceptRedirect.
1419 mutable bool cancel_redirect_request_;
1421 // Indicate whether to intercept the final response, and if so specify the
1422 // response to return.
1423 mutable bool intercept_final_response_;
1424 mutable std::string final_headers_;
1425 mutable std::string final_data_;
1427 // Cancel the final request within MaybeInterceptResponse.
1428 mutable bool cancel_final_request_;
1430 // Instruct the interceptor to use a real URLRequestHTTPJob.
1431 mutable bool use_url_request_http_job_;
1433 // These indicate if the interceptor did something or not.
1434 mutable bool did_intercept_main_;
1435 mutable bool did_restart_main_;
1436 mutable bool did_cancel_main_;
1437 mutable bool did_cancel_then_restart_main_;
1438 mutable bool did_simulate_error_main_;
1439 mutable bool did_intercept_redirect_;
1440 mutable bool did_cancel_redirect_;
1441 mutable bool did_intercept_final_;
1442 mutable bool did_cancel_final_;
1445 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1446 class URLRequestInterceptorTest : public URLRequestTest {
1447 public:
1448 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1451 ~URLRequestInterceptorTest() override {
1452 // URLRequestJobs may post clean-up tasks on destruction.
1453 base::RunLoop().RunUntilIdle();
1456 void SetUpFactory() override {
1457 interceptor_ = new MockURLRequestInterceptor();
1458 job_factory_.reset(new URLRequestInterceptingJobFactory(
1459 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1462 MockURLRequestInterceptor* interceptor() const {
1463 return interceptor_;
1466 private:
1467 MockURLRequestInterceptor* interceptor_;
1470 TEST_F(URLRequestInterceptorTest, Intercept) {
1471 // Intercept the main request and respond with a simple response.
1472 interceptor()->set_intercept_main_request(true);
1473 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1474 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1475 TestDelegate d;
1476 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1477 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1478 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1479 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1480 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1481 req->SetUserData(nullptr, user_data0);
1482 req->SetUserData(&user_data1, user_data1);
1483 req->SetUserData(&user_data2, user_data2);
1484 req->set_method("GET");
1485 req->Start();
1486 base::RunLoop().Run();
1488 // Make sure we can retrieve our specific user data.
1489 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1490 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1491 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1493 // Check that we got one good response.
1494 EXPECT_TRUE(req->status().is_success());
1495 EXPECT_EQ(200, req->response_headers()->response_code());
1496 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1497 EXPECT_EQ(1, d.response_started_count());
1498 EXPECT_EQ(0, d.received_redirect_count());
1501 TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1502 // Intercept the main request and respond with a redirect.
1503 interceptor()->set_intercept_main_request(true);
1504 interceptor()->set_main_headers(
1505 MockURLRequestInterceptor::redirect_headers());
1506 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1508 // Intercept that redirect and respond with a final OK response.
1509 interceptor()->set_intercept_redirect(true);
1510 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1511 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1513 TestDelegate d;
1514 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1515 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1516 req->set_method("GET");
1517 req->Start();
1518 base::RunLoop().Run();
1520 // Check that the interceptor got called as expected.
1521 EXPECT_TRUE(interceptor()->did_intercept_main());
1522 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1524 // Check that we got one good response.
1525 EXPECT_TRUE(req->status().is_success());
1526 if (req->status().is_success())
1527 EXPECT_EQ(200, req->response_headers()->response_code());
1529 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1530 EXPECT_EQ(1, d.response_started_count());
1531 EXPECT_EQ(0, d.received_redirect_count());
1534 TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1535 // Intercept the main request to generate a server error response.
1536 interceptor()->set_intercept_main_request(true);
1537 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1538 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1540 // Intercept that error and respond with an OK response.
1541 interceptor()->set_intercept_final_response(true);
1542 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1543 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1545 TestDelegate d;
1546 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1547 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1548 req->set_method("GET");
1549 req->Start();
1550 base::RunLoop().Run();
1552 // Check that the interceptor got called as expected.
1553 EXPECT_TRUE(interceptor()->did_intercept_main());
1554 EXPECT_TRUE(interceptor()->did_intercept_final());
1556 // Check that we got one good response.
1557 EXPECT_TRUE(req->status().is_success());
1558 EXPECT_EQ(200, req->response_headers()->response_code());
1559 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1560 EXPECT_EQ(1, d.response_started_count());
1561 EXPECT_EQ(0, d.received_redirect_count());
1564 TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1565 // Intercept the main request to simulate a network error.
1566 interceptor()->set_simulate_main_network_error(true);
1568 // Intercept that error and respond with an OK response.
1569 interceptor()->set_intercept_final_response(true);
1570 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1571 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1573 TestDelegate d;
1574 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1575 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1576 req->set_method("GET");
1577 req->Start();
1578 base::RunLoop().Run();
1580 // Check that the interceptor got called as expected.
1581 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1582 EXPECT_TRUE(interceptor()->did_intercept_final());
1584 // Check that we received one good response.
1585 EXPECT_TRUE(req->status().is_success());
1586 EXPECT_EQ(200, req->response_headers()->response_code());
1587 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1588 EXPECT_EQ(1, d.response_started_count());
1589 EXPECT_EQ(0, d.received_redirect_count());
1592 TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1593 // Restart the main request.
1594 interceptor()->set_restart_main_request(true);
1596 // then intercept the new main request and respond with an OK response
1597 interceptor()->set_intercept_main_request(true);
1598 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1599 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1601 TestDelegate d;
1602 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1603 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1604 req->set_method("GET");
1605 req->Start();
1606 base::RunLoop().Run();
1608 // Check that the interceptor got called as expected.
1609 EXPECT_TRUE(interceptor()->did_restart_main());
1610 EXPECT_TRUE(interceptor()->did_intercept_main());
1612 // Check that we received one good response.
1613 EXPECT_TRUE(req->status().is_success());
1614 if (req->status().is_success())
1615 EXPECT_EQ(200, req->response_headers()->response_code());
1617 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1618 EXPECT_EQ(1, d.response_started_count());
1619 EXPECT_EQ(0, d.received_redirect_count());
1622 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1623 // Intercept the main request and cancel from within the restarted job.
1624 interceptor()->set_cancel_main_request(true);
1626 // Set up to intercept the final response and override it with an OK response.
1627 interceptor()->set_intercept_final_response(true);
1628 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1629 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1631 TestDelegate d;
1632 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1633 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1634 req->set_method("GET");
1635 req->Start();
1636 base::RunLoop().Run();
1638 // Check that the interceptor got called as expected.
1639 EXPECT_TRUE(interceptor()->did_cancel_main());
1640 EXPECT_FALSE(interceptor()->did_intercept_final());
1642 // Check that we see a canceled request.
1643 EXPECT_FALSE(req->status().is_success());
1644 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1647 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1648 // Intercept the main request and respond with a redirect.
1649 interceptor()->set_intercept_main_request(true);
1650 interceptor()->set_main_headers(
1651 MockURLRequestInterceptor::redirect_headers());
1652 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1654 // Intercept the redirect and cancel from within that job.
1655 interceptor()->set_cancel_redirect_request(true);
1657 // Set up to intercept the final response and override it with an OK response.
1658 interceptor()->set_intercept_final_response(true);
1659 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1660 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1662 TestDelegate d;
1663 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1664 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1665 req->set_method("GET");
1666 req->Start();
1667 base::RunLoop().Run();
1669 // Check that the interceptor got called as expected.
1670 EXPECT_TRUE(interceptor()->did_intercept_main());
1671 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1672 EXPECT_FALSE(interceptor()->did_intercept_final());
1674 // Check that we see a canceled request.
1675 EXPECT_FALSE(req->status().is_success());
1676 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1679 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1680 // Intercept the main request to simulate a network error.
1681 interceptor()->set_simulate_main_network_error(true);
1683 // Set up to intercept final the response and cancel from within that job.
1684 interceptor()->set_cancel_final_request(true);
1686 TestDelegate d;
1687 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1688 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1689 req->set_method("GET");
1690 req->Start();
1691 base::RunLoop().Run();
1693 // Check that the interceptor got called as expected.
1694 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1695 EXPECT_TRUE(interceptor()->did_cancel_final());
1697 // Check that we see a canceled request.
1698 EXPECT_FALSE(req->status().is_success());
1699 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1702 TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1703 // Intercept the main request and cancel then restart from within that job.
1704 interceptor()->set_cancel_then_restart_main_request(true);
1706 // Set up to intercept the final response and override it with an OK response.
1707 interceptor()->set_intercept_final_response(true);
1708 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1709 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1711 TestDelegate d;
1712 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1713 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1714 req->set_method("GET");
1715 req->Start();
1716 base::RunLoop().Run();
1718 // Check that the interceptor got called as expected.
1719 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1720 EXPECT_FALSE(interceptor()->did_intercept_final());
1722 // Check that we see a canceled request.
1723 EXPECT_FALSE(req->status().is_success());
1724 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1727 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1728 // reused. |connect_time_flags| is used to indicate if there should be dns
1729 // or SSL times, and |used_proxy| is used for proxy times.
1730 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1731 int connect_time_flags,
1732 bool used_proxy) {
1733 LoadTimingInfo load_timing;
1734 load_timing.socket_log_id = 1;
1736 if (used_proxy) {
1737 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1738 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1741 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1742 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1743 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1744 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1746 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1747 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1748 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1749 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1751 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1753 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1754 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1755 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1756 return load_timing;
1759 // Same as above, but in the case of a reused socket.
1760 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1761 bool used_proxy) {
1762 LoadTimingInfo load_timing;
1763 load_timing.socket_log_id = 1;
1764 load_timing.socket_reused = true;
1766 if (used_proxy) {
1767 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1768 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1771 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1772 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1773 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1774 return load_timing;
1777 LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1778 const LoadTimingInfo& job_load_timing,
1779 const URLRequestContext& context,
1780 MockURLRequestInterceptor* interceptor) {
1781 interceptor->set_intercept_main_request(true);
1782 interceptor->set_main_request_load_timing_info(job_load_timing);
1783 TestDelegate d;
1784 scoped_ptr<URLRequest> req(context.CreateRequest(
1785 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
1786 req->Start();
1787 base::RunLoop().Run();
1789 LoadTimingInfo resulting_load_timing;
1790 req->GetLoadTimingInfo(&resulting_load_timing);
1792 // None of these should be modified by the URLRequest.
1793 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1794 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1795 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1796 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1797 EXPECT_EQ(job_load_timing.receive_headers_end,
1798 resulting_load_timing.receive_headers_end);
1800 return resulting_load_timing;
1803 // Basic test that the intercept + load timing tests work.
1804 TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
1805 base::TimeTicks now = base::TimeTicks::Now();
1806 LoadTimingInfo job_load_timing =
1807 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1809 LoadTimingInfo load_timing_result =
1810 RunURLRequestInterceptorLoadTimingTest(
1811 job_load_timing, default_context(), interceptor());
1813 // Nothing should have been changed by the URLRequest.
1814 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1815 load_timing_result.proxy_resolve_start);
1816 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1817 load_timing_result.proxy_resolve_end);
1818 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1819 load_timing_result.connect_timing.dns_start);
1820 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1821 load_timing_result.connect_timing.dns_end);
1822 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1823 load_timing_result.connect_timing.connect_start);
1824 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1825 load_timing_result.connect_timing.connect_end);
1826 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1827 load_timing_result.connect_timing.ssl_start);
1828 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1829 load_timing_result.connect_timing.ssl_end);
1831 // Redundant sanity check.
1832 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1835 // Another basic test, with proxy and SSL times, but no DNS times.
1836 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
1837 base::TimeTicks now = base::TimeTicks::Now();
1838 LoadTimingInfo job_load_timing =
1839 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1841 LoadTimingInfo load_timing_result =
1842 RunURLRequestInterceptorLoadTimingTest(
1843 job_load_timing, default_context(), interceptor());
1845 // Nothing should have been changed by the URLRequest.
1846 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1847 load_timing_result.proxy_resolve_start);
1848 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1849 load_timing_result.proxy_resolve_end);
1850 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1851 load_timing_result.connect_timing.dns_start);
1852 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1853 load_timing_result.connect_timing.dns_end);
1854 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1855 load_timing_result.connect_timing.connect_start);
1856 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1857 load_timing_result.connect_timing.connect_end);
1858 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1859 load_timing_result.connect_timing.ssl_start);
1860 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1861 load_timing_result.connect_timing.ssl_end);
1863 // Redundant sanity check.
1864 TestLoadTimingNotReusedWithProxy(load_timing_result,
1865 CONNECT_TIMING_HAS_SSL_TIMES);
1868 // Make sure that URLRequest correctly adjusts proxy times when they're before
1869 // |request_start|, due to already having a connected socket. This happens in
1870 // the case of reusing a SPDY session. The connected socket is not considered
1871 // reused in this test (May be a preconnect).
1873 // To mix things up from the test above, assumes DNS times but no SSL times.
1874 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
1875 base::TimeTicks now = base::TimeTicks::Now();
1876 LoadTimingInfo job_load_timing =
1877 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1878 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1879 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1880 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1881 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1882 job_load_timing.connect_timing.connect_start =
1883 now - base::TimeDelta::FromDays(2);
1884 job_load_timing.connect_timing.connect_end =
1885 now - base::TimeDelta::FromDays(1);
1887 LoadTimingInfo load_timing_result =
1888 RunURLRequestInterceptorLoadTimingTest(
1889 job_load_timing, default_context(), interceptor());
1891 // Proxy times, connect times, and DNS times should all be replaced with
1892 // request_start.
1893 EXPECT_EQ(load_timing_result.request_start,
1894 load_timing_result.proxy_resolve_start);
1895 EXPECT_EQ(load_timing_result.request_start,
1896 load_timing_result.proxy_resolve_end);
1897 EXPECT_EQ(load_timing_result.request_start,
1898 load_timing_result.connect_timing.dns_start);
1899 EXPECT_EQ(load_timing_result.request_start,
1900 load_timing_result.connect_timing.dns_end);
1901 EXPECT_EQ(load_timing_result.request_start,
1902 load_timing_result.connect_timing.connect_start);
1903 EXPECT_EQ(load_timing_result.request_start,
1904 load_timing_result.connect_timing.connect_end);
1906 // Other times should have been left null.
1907 TestLoadTimingNotReusedWithProxy(load_timing_result,
1908 CONNECT_TIMING_HAS_DNS_TIMES);
1911 // Same as above, but in the reused case.
1912 TEST_F(URLRequestInterceptorTest,
1913 InterceptLoadTimingEarlyProxyResolutionReused) {
1914 base::TimeTicks now = base::TimeTicks::Now();
1915 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1916 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1917 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1919 LoadTimingInfo load_timing_result =
1920 RunURLRequestInterceptorLoadTimingTest(
1921 job_load_timing, default_context(), interceptor());
1923 // Proxy times and connect times should all be replaced with request_start.
1924 EXPECT_EQ(load_timing_result.request_start,
1925 load_timing_result.proxy_resolve_start);
1926 EXPECT_EQ(load_timing_result.request_start,
1927 load_timing_result.proxy_resolve_end);
1929 // Other times should have been left null.
1930 TestLoadTimingReusedWithProxy(load_timing_result);
1933 // Make sure that URLRequest correctly adjusts connect times when they're before
1934 // |request_start|, due to reusing a connected socket. The connected socket is
1935 // not considered reused in this test (May be a preconnect).
1937 // To mix things up, the request has SSL times, but no DNS times.
1938 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
1939 base::TimeTicks now = base::TimeTicks::Now();
1940 LoadTimingInfo job_load_timing =
1941 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1942 job_load_timing.connect_timing.connect_start =
1943 now - base::TimeDelta::FromDays(1);
1944 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1945 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1946 job_load_timing.connect_timing.connect_end =
1947 now - base::TimeDelta::FromDays(4);
1949 LoadTimingInfo load_timing_result =
1950 RunURLRequestInterceptorLoadTimingTest(
1951 job_load_timing, default_context(), interceptor());
1953 // Connect times, and SSL times should be replaced with request_start.
1954 EXPECT_EQ(load_timing_result.request_start,
1955 load_timing_result.connect_timing.connect_start);
1956 EXPECT_EQ(load_timing_result.request_start,
1957 load_timing_result.connect_timing.ssl_start);
1958 EXPECT_EQ(load_timing_result.request_start,
1959 load_timing_result.connect_timing.ssl_end);
1960 EXPECT_EQ(load_timing_result.request_start,
1961 load_timing_result.connect_timing.connect_end);
1963 // Other times should have been left null.
1964 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1967 // Make sure that URLRequest correctly adjusts connect times when they're before
1968 // |request_start|, due to reusing a connected socket in the case that there
1969 // are also proxy times. The connected socket is not considered reused in this
1970 // test (May be a preconnect).
1972 // In this test, there are no SSL or DNS times.
1973 TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
1974 base::TimeTicks now = base::TimeTicks::Now();
1975 LoadTimingInfo job_load_timing =
1976 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1977 job_load_timing.connect_timing.connect_start =
1978 now - base::TimeDelta::FromDays(1);
1979 job_load_timing.connect_timing.connect_end =
1980 now - base::TimeDelta::FromDays(2);
1982 LoadTimingInfo load_timing_result =
1983 RunURLRequestInterceptorLoadTimingTest(
1984 job_load_timing, default_context(), interceptor());
1986 // Connect times should be replaced with proxy_resolve_end.
1987 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1988 load_timing_result.connect_timing.connect_start);
1989 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1990 load_timing_result.connect_timing.connect_end);
1992 // Other times should have been left null.
1993 TestLoadTimingNotReusedWithProxy(load_timing_result,
1994 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1997 // Check that two different URL requests have different identifiers.
1998 TEST_F(URLRequestTest, Identifiers) {
1999 TestDelegate d;
2000 TestURLRequestContext context;
2001 scoped_ptr<URLRequest> req(
2002 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2003 scoped_ptr<URLRequest> other_req(
2004 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2006 ASSERT_NE(req->identifier(), other_req->identifier());
2009 // Check that a failure to connect to the proxy is reported to the network
2010 // delegate.
2011 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2012 MockHostResolver host_resolver;
2013 host_resolver.rules()->AddSimulatedFailure("*");
2015 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
2016 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2018 TestDelegate d;
2019 scoped_ptr<URLRequest> req(
2020 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2021 req->set_method("GET");
2023 req->Start();
2024 base::RunLoop().Run();
2026 // Check we see a failed request.
2027 EXPECT_FALSE(req->status().is_success());
2028 // The proxy server is not set before failure.
2029 EXPECT_TRUE(req->proxy_server().IsEmpty());
2030 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2031 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
2033 EXPECT_EQ(1, network_delegate.error_count());
2034 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2035 EXPECT_EQ(1, network_delegate.completed_requests());
2038 // Make sure that NetworkDelegate::NotifyCompleted is called if
2039 // content is empty.
2040 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2041 TestDelegate d;
2042 scoped_ptr<URLRequest> req(
2043 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
2044 req->Start();
2045 base::RunLoop().Run();
2046 EXPECT_EQ("", d.data_received());
2047 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2050 // Make sure that SetPriority actually sets the URLRequest's priority
2051 // correctly, both before and after start.
2052 TEST_F(URLRequestTest, SetPriorityBasic) {
2053 TestDelegate d;
2054 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2055 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
2056 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
2058 req->SetPriority(LOW);
2059 EXPECT_EQ(LOW, req->priority());
2061 req->Start();
2062 EXPECT_EQ(LOW, req->priority());
2064 req->SetPriority(MEDIUM);
2065 EXPECT_EQ(MEDIUM, req->priority());
2068 // Make sure that URLRequest calls SetPriority on a job before calling
2069 // Start on it.
2070 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2071 TestDelegate d;
2072 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2073 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
2074 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
2076 scoped_refptr<URLRequestTestJob> job =
2077 new URLRequestTestJob(req.get(), &default_network_delegate_);
2078 AddTestInterceptor()->set_main_intercept_job(job.get());
2079 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2081 req->SetPriority(LOW);
2083 req->Start();
2084 EXPECT_EQ(LOW, job->priority());
2087 // Make sure that URLRequest passes on its priority updates to its
2088 // job.
2089 TEST_F(URLRequestTest, SetJobPriority) {
2090 TestDelegate d;
2091 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2092 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
2094 scoped_refptr<URLRequestTestJob> job =
2095 new URLRequestTestJob(req.get(), &default_network_delegate_);
2096 AddTestInterceptor()->set_main_intercept_job(job.get());
2098 req->SetPriority(LOW);
2099 req->Start();
2100 EXPECT_EQ(LOW, job->priority());
2102 req->SetPriority(MEDIUM);
2103 EXPECT_EQ(MEDIUM, req->priority());
2104 EXPECT_EQ(MEDIUM, job->priority());
2107 // Setting the IGNORE_LIMITS load flag should be okay if the priority
2108 // is MAXIMUM_PRIORITY.
2109 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2110 TestDelegate d;
2111 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2112 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
2113 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2115 scoped_refptr<URLRequestTestJob> job =
2116 new URLRequestTestJob(req.get(), &default_network_delegate_);
2117 AddTestInterceptor()->set_main_intercept_job(job.get());
2119 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2120 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2122 req->SetPriority(MAXIMUM_PRIORITY);
2123 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2125 req->Start();
2126 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
2127 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2130 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
2131 #if !defined(OS_IOS)
2132 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
2133 // This is to work around mysterious failures in chrome_frame_net_tests. See:
2134 // http://crbug.com/114369
2135 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
2136 class LocalHttpTestServer : public SpawnedTestServer {
2137 public:
2138 explicit LocalHttpTestServer(const base::FilePath& document_root)
2139 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2140 ScopedCustomUrlRequestTestHttpHost::value(),
2141 document_root) {}
2142 LocalHttpTestServer()
2143 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2144 ScopedCustomUrlRequestTestHttpHost::value(),
2145 base::FilePath()) {}
2148 TEST_F(URLRequestTest, DelayedCookieCallback) {
2149 LocalHttpTestServer test_server;
2150 ASSERT_TRUE(test_server.Start());
2152 TestURLRequestContext context;
2153 scoped_refptr<DelayedCookieMonster> delayed_cm =
2154 new DelayedCookieMonster();
2155 scoped_refptr<CookieStore> cookie_store = delayed_cm;
2156 context.set_cookie_store(delayed_cm.get());
2158 // Set up a cookie.
2160 TestNetworkDelegate network_delegate;
2161 context.set_network_delegate(&network_delegate);
2162 TestDelegate d;
2163 scoped_ptr<URLRequest> req(context.CreateRequest(
2164 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2165 &d));
2166 req->Start();
2167 base::RunLoop().Run();
2168 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2169 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2170 EXPECT_EQ(1, network_delegate.set_cookie_count());
2173 // Verify that the cookie is set.
2175 TestNetworkDelegate network_delegate;
2176 context.set_network_delegate(&network_delegate);
2177 TestDelegate d;
2178 scoped_ptr<URLRequest> req(context.CreateRequest(
2179 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2180 req->Start();
2181 base::RunLoop().Run();
2183 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2184 != std::string::npos);
2185 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2186 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2190 TEST_F(URLRequestTest, DoNotSendCookies) {
2191 LocalHttpTestServer test_server;
2192 ASSERT_TRUE(test_server.Start());
2194 // Set up a cookie.
2196 TestNetworkDelegate network_delegate;
2197 default_context_.set_network_delegate(&network_delegate);
2198 TestDelegate d;
2199 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2200 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2201 &d));
2202 req->Start();
2203 base::RunLoop().Run();
2204 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2205 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2208 // Verify that the cookie is set.
2210 TestNetworkDelegate network_delegate;
2211 default_context_.set_network_delegate(&network_delegate);
2212 TestDelegate d;
2213 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2214 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2215 req->Start();
2216 base::RunLoop().Run();
2218 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2219 != std::string::npos);
2220 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2221 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2224 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2226 TestNetworkDelegate network_delegate;
2227 default_context_.set_network_delegate(&network_delegate);
2228 TestDelegate d;
2229 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2230 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2231 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2232 req->Start();
2233 base::RunLoop().Run();
2235 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2236 == std::string::npos);
2238 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2239 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2240 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2244 TEST_F(URLRequestTest, DoNotSaveCookies) {
2245 LocalHttpTestServer test_server;
2246 ASSERT_TRUE(test_server.Start());
2248 // Set up a cookie.
2250 TestNetworkDelegate network_delegate;
2251 default_context_.set_network_delegate(&network_delegate);
2252 TestDelegate d;
2253 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2254 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2255 &d));
2256 req->Start();
2257 base::RunLoop().Run();
2259 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2260 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2261 EXPECT_EQ(1, network_delegate.set_cookie_count());
2264 // Try to set-up another cookie and update the previous cookie.
2266 TestNetworkDelegate network_delegate;
2267 default_context_.set_network_delegate(&network_delegate);
2268 TestDelegate d;
2269 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2270 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2271 DEFAULT_PRIORITY, &d));
2272 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2273 req->Start();
2275 base::RunLoop().Run();
2277 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2278 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2279 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2280 EXPECT_EQ(0, network_delegate.set_cookie_count());
2283 // Verify the cookies weren't saved or updated.
2285 TestNetworkDelegate network_delegate;
2286 default_context_.set_network_delegate(&network_delegate);
2287 TestDelegate d;
2288 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2289 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2290 req->Start();
2291 base::RunLoop().Run();
2293 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2294 == std::string::npos);
2295 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2296 != std::string::npos);
2298 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2299 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2300 EXPECT_EQ(0, network_delegate.set_cookie_count());
2304 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2305 LocalHttpTestServer test_server;
2306 ASSERT_TRUE(test_server.Start());
2308 // Set up a cookie.
2310 TestNetworkDelegate network_delegate;
2311 default_context_.set_network_delegate(&network_delegate);
2312 TestDelegate d;
2313 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2314 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2315 &d));
2316 req->Start();
2317 base::RunLoop().Run();
2319 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2320 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2323 // Verify that the cookie is set.
2325 TestNetworkDelegate network_delegate;
2326 default_context_.set_network_delegate(&network_delegate);
2327 TestDelegate d;
2328 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2329 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2330 req->Start();
2331 base::RunLoop().Run();
2333 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2334 != std::string::npos);
2336 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2337 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2340 // Verify that the cookie isn't sent.
2342 TestNetworkDelegate network_delegate;
2343 default_context_.set_network_delegate(&network_delegate);
2344 TestDelegate d;
2345 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2346 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2347 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2348 req->Start();
2349 base::RunLoop().Run();
2351 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2352 == std::string::npos);
2354 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2355 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2359 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2360 LocalHttpTestServer test_server;
2361 ASSERT_TRUE(test_server.Start());
2363 // Set up a cookie.
2365 TestNetworkDelegate network_delegate;
2366 default_context_.set_network_delegate(&network_delegate);
2367 TestDelegate d;
2368 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2369 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2370 &d));
2371 req->Start();
2372 base::RunLoop().Run();
2374 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2375 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2378 // Try to set-up another cookie and update the previous cookie.
2380 TestNetworkDelegate network_delegate;
2381 default_context_.set_network_delegate(&network_delegate);
2382 TestDelegate d;
2383 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2384 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2385 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2386 DEFAULT_PRIORITY, &d));
2387 req->Start();
2389 base::RunLoop().Run();
2391 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2392 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2395 // Verify the cookies weren't saved or updated.
2397 TestNetworkDelegate network_delegate;
2398 default_context_.set_network_delegate(&network_delegate);
2399 TestDelegate d;
2400 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2401 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2402 req->Start();
2403 base::RunLoop().Run();
2405 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2406 == std::string::npos);
2407 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2408 != std::string::npos);
2410 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2411 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2415 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2416 LocalHttpTestServer test_server;
2417 ASSERT_TRUE(test_server.Start());
2419 // Set up an empty cookie.
2421 TestNetworkDelegate network_delegate;
2422 default_context_.set_network_delegate(&network_delegate);
2423 TestDelegate d;
2424 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2425 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
2426 req->Start();
2427 base::RunLoop().Run();
2429 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2430 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2431 EXPECT_EQ(0, network_delegate.set_cookie_count());
2435 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2436 LocalHttpTestServer test_server;
2437 ASSERT_TRUE(test_server.Start());
2439 // Set up a cookie.
2441 TestNetworkDelegate network_delegate;
2442 default_context_.set_network_delegate(&network_delegate);
2443 TestDelegate d;
2444 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2445 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2446 &d));
2447 req->Start();
2448 base::RunLoop().Run();
2450 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2451 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2454 // Verify that the cookie is set.
2456 TestNetworkDelegate network_delegate;
2457 default_context_.set_network_delegate(&network_delegate);
2458 TestDelegate d;
2459 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2460 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2461 req->Start();
2462 base::RunLoop().Run();
2464 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2465 != std::string::npos);
2467 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2468 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2471 // Verify that the cookie isn't sent.
2473 TestNetworkDelegate network_delegate;
2474 default_context_.set_network_delegate(&network_delegate);
2475 TestDelegate d;
2476 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2477 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2478 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2479 req->Start();
2480 base::RunLoop().Run();
2482 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2483 == std::string::npos);
2485 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2486 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2490 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2491 LocalHttpTestServer test_server;
2492 ASSERT_TRUE(test_server.Start());
2494 // Set up a cookie.
2496 TestNetworkDelegate network_delegate;
2497 default_context_.set_network_delegate(&network_delegate);
2498 TestDelegate d;
2499 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2500 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2501 &d));
2502 req->Start();
2503 base::RunLoop().Run();
2505 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2506 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2509 // Try to set-up another cookie and update the previous cookie.
2511 TestNetworkDelegate network_delegate;
2512 default_context_.set_network_delegate(&network_delegate);
2513 TestDelegate d;
2514 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2515 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2516 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2517 DEFAULT_PRIORITY, &d));
2518 req->Start();
2520 base::RunLoop().Run();
2522 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2523 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2526 // Verify the cookies weren't saved or updated.
2528 TestNetworkDelegate network_delegate;
2529 default_context_.set_network_delegate(&network_delegate);
2530 TestDelegate d;
2531 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2532 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2533 req->Start();
2534 base::RunLoop().Run();
2536 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2537 == std::string::npos);
2538 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2539 != std::string::npos);
2541 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2542 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2546 TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2547 LocalHttpTestServer test_server;
2548 ASSERT_TRUE(test_server.Start());
2550 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2551 // LocalHttpTestServer points).
2553 TestNetworkDelegate network_delegate;
2554 network_delegate.set_first_party_only_cookies_enabled(true);
2555 default_context_.set_network_delegate(&network_delegate);
2557 TestDelegate d;
2558 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2559 test_server.GetURL(
2560 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2561 DEFAULT_PRIORITY, &d));
2562 req->Start();
2563 base::RunLoop().Run();
2564 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2565 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2566 EXPECT_EQ(1, network_delegate.set_cookie_count());
2569 // Verify that the cookie is sent for first-party requests.
2571 TestNetworkDelegate network_delegate;
2572 network_delegate.set_first_party_only_cookies_enabled(true);
2573 default_context_.set_network_delegate(&network_delegate);
2574 TestDelegate d;
2575 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2576 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2577 req->set_first_party_for_cookies(test_server.GetURL(""));
2578 req->Start();
2579 base::RunLoop().Run();
2581 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2582 std::string::npos);
2583 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2584 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2587 // Verify that the cookie is not-sent for non-first-party requests.
2589 TestNetworkDelegate network_delegate;
2590 network_delegate.set_first_party_only_cookies_enabled(true);
2591 default_context_.set_network_delegate(&network_delegate);
2592 TestDelegate d;
2593 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2594 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2595 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2596 req->Start();
2597 base::RunLoop().Run();
2599 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2600 std::string::npos);
2601 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2602 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2606 TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2607 LocalHttpTestServer test_server;
2608 ASSERT_TRUE(test_server.Start());
2610 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2611 // LocalHttpTestServer points).
2613 TestNetworkDelegate network_delegate;
2614 network_delegate.set_first_party_only_cookies_enabled(false);
2615 default_context_.set_network_delegate(&network_delegate);
2617 TestDelegate d;
2618 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2619 test_server.GetURL(
2620 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2621 DEFAULT_PRIORITY, &d));
2622 req->Start();
2623 base::RunLoop().Run();
2624 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2625 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2626 EXPECT_EQ(1, network_delegate.set_cookie_count());
2629 // Verify that the cookie is sent for first-party requests.
2631 TestNetworkDelegate network_delegate;
2632 network_delegate.set_first_party_only_cookies_enabled(false);
2633 default_context_.set_network_delegate(&network_delegate);
2634 TestDelegate d;
2635 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2636 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2637 req->set_first_party_for_cookies(test_server.GetURL(""));
2638 req->Start();
2639 base::RunLoop().Run();
2641 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2642 std::string::npos);
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 also sent for non-first-party requests.
2649 TestNetworkDelegate network_delegate;
2650 network_delegate.set_first_party_only_cookies_enabled(false);
2651 default_context_.set_network_delegate(&network_delegate);
2652 TestDelegate d;
2653 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2654 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2655 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2656 req->Start();
2657 base::RunLoop().Run();
2659 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2660 std::string::npos);
2661 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2662 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2666 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2667 // value for the |fixed_date| argument given to the constructor.
2668 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2669 public:
2670 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2671 : fixed_date_(fixed_date) {}
2672 ~FixedDateNetworkDelegate() override {}
2674 // NetworkDelegate implementation
2675 int OnHeadersReceived(
2676 URLRequest* request,
2677 const CompletionCallback& callback,
2678 const HttpResponseHeaders* original_response_headers,
2679 scoped_refptr<HttpResponseHeaders>* override_response_headers,
2680 GURL* allowed_unsafe_redirect_url) override;
2682 private:
2683 std::string fixed_date_;
2685 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2688 int FixedDateNetworkDelegate::OnHeadersReceived(
2689 URLRequest* request,
2690 const CompletionCallback& callback,
2691 const HttpResponseHeaders* original_response_headers,
2692 scoped_refptr<HttpResponseHeaders>* override_response_headers,
2693 GURL* allowed_unsafe_redirect_url) {
2694 HttpResponseHeaders* new_response_headers =
2695 new HttpResponseHeaders(original_response_headers->raw_headers());
2697 new_response_headers->RemoveHeader("Date");
2698 new_response_headers->AddHeader("Date: " + fixed_date_);
2700 *override_response_headers = new_response_headers;
2701 return TestNetworkDelegate::OnHeadersReceived(request,
2702 callback,
2703 original_response_headers,
2704 override_response_headers,
2705 allowed_unsafe_redirect_url);
2708 // Test that cookie expiration times are adjusted for server/client clock
2709 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2710 // headers by defaulting to GMT. (crbug.com/135131)
2711 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2712 LocalHttpTestServer test_server;
2713 ASSERT_TRUE(test_server.Start());
2715 // Set up an expired cookie.
2717 TestNetworkDelegate network_delegate;
2718 default_context_.set_network_delegate(&network_delegate);
2719 TestDelegate d;
2720 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2721 test_server.GetURL(
2722 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2723 DEFAULT_PRIORITY, &d));
2724 req->Start();
2725 base::RunLoop().Run();
2727 // Verify that the cookie is not set.
2729 TestNetworkDelegate network_delegate;
2730 default_context_.set_network_delegate(&network_delegate);
2731 TestDelegate d;
2732 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2733 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2734 req->Start();
2735 base::RunLoop().Run();
2737 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2739 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2741 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2742 default_context_.set_network_delegate(&network_delegate);
2743 TestDelegate d;
2744 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2745 test_server.GetURL(
2746 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2747 DEFAULT_PRIORITY, &d));
2748 req->Start();
2749 base::RunLoop().Run();
2751 // Verify that the cookie is set.
2753 TestNetworkDelegate network_delegate;
2754 default_context_.set_network_delegate(&network_delegate);
2755 TestDelegate d;
2756 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2757 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2758 req->Start();
2759 base::RunLoop().Run();
2761 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2766 // Check that it is impossible to change the referrer in the extra headers of
2767 // an URLRequest.
2768 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2769 LocalHttpTestServer test_server;
2770 ASSERT_TRUE(test_server.Start());
2772 // If extra headers contain referer and the request contains a referer,
2773 // only the latter shall be respected.
2775 TestDelegate d;
2776 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2777 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
2778 req->SetReferrer("http://foo.com/");
2780 HttpRequestHeaders headers;
2781 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2782 req->SetExtraRequestHeaders(headers);
2784 req->Start();
2785 base::RunLoop().Run();
2787 EXPECT_EQ("http://foo.com/", d.data_received());
2790 // If extra headers contain a referer but the request does not, no referer
2791 // shall be sent in the header.
2793 TestDelegate d;
2794 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2795 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
2797 HttpRequestHeaders headers;
2798 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2799 req->SetExtraRequestHeaders(headers);
2800 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
2802 req->Start();
2803 base::RunLoop().Run();
2805 EXPECT_EQ("None", d.data_received());
2809 class URLRequestTestHTTP : public URLRequestTest {
2810 public:
2811 URLRequestTestHTTP()
2812 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2813 "net/data/url_request_unittest"))) {
2816 protected:
2817 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2818 // |request_method| is the method to use for the initial request.
2819 // |redirect_method| is the method that is expected to be used for the second
2820 // request, after redirection.
2821 // If |include_data| is true, data is uploaded with the request. The
2822 // response body is expected to match it exactly, if and only if
2823 // |request_method| == |redirect_method|.
2824 void HTTPRedirectMethodTest(const GURL& redirect_url,
2825 const std::string& request_method,
2826 const std::string& redirect_method,
2827 bool include_data) {
2828 static const char kData[] = "hello world";
2829 TestDelegate d;
2830 scoped_ptr<URLRequest> req(
2831 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
2832 req->set_method(request_method);
2833 if (include_data) {
2834 req->set_upload(CreateSimpleUploadData(kData));
2835 HttpRequestHeaders headers;
2836 headers.SetHeader(HttpRequestHeaders::kContentLength,
2837 base::UintToString(arraysize(kData) - 1));
2838 req->SetExtraRequestHeaders(headers);
2840 req->Start();
2841 base::RunLoop().Run();
2842 EXPECT_EQ(redirect_method, req->method());
2843 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2844 EXPECT_EQ(OK, req->status().error());
2845 if (include_data) {
2846 if (request_method == redirect_method) {
2847 EXPECT_EQ(kData, d.data_received());
2848 } else {
2849 EXPECT_NE(kData, d.data_received());
2852 if (HasFailure())
2853 LOG(WARNING) << "Request method was: " << request_method;
2856 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2857 // |request_method| is the method to use for the initial request.
2858 // |redirect_method| is the method that is expected to be used for the second
2859 // request, after redirection.
2860 // |origin_value| is the expected value for the Origin header after
2861 // redirection. If empty, expects that there will be no Origin header.
2862 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
2863 const std::string& request_method,
2864 const std::string& redirect_method,
2865 const std::string& origin_value) {
2866 TestDelegate d;
2867 scoped_ptr<URLRequest> req(
2868 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
2869 req->set_method(request_method);
2870 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
2871 redirect_url.GetOrigin().spec(), false);
2872 req->Start();
2874 base::RunLoop().Run();
2876 EXPECT_EQ(redirect_method, req->method());
2877 // Note that there is no check for request success here because, for
2878 // purposes of testing, the request very well may fail. For example, if the
2879 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
2880 // origin, there is not an HTTPS server in this unit test framework, so the
2881 // request would fail. However, that's fine, as long as the request headers
2882 // are in order and pass the checks below.
2883 if (origin_value.empty()) {
2884 EXPECT_FALSE(
2885 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
2886 } else {
2887 std::string origin_header;
2888 EXPECT_TRUE(req->extra_request_headers().GetHeader(
2889 HttpRequestHeaders::kOrigin, &origin_header));
2890 EXPECT_EQ(origin_value, origin_header);
2894 void HTTPUploadDataOperationTest(const std::string& method) {
2895 const int kMsgSize = 20000; // multiple of 10
2896 const int kIterations = 50;
2897 char* uploadBytes = new char[kMsgSize+1];
2898 char* ptr = uploadBytes;
2899 char marker = 'a';
2900 for (int idx = 0; idx < kMsgSize/10; idx++) {
2901 memcpy(ptr, "----------", 10);
2902 ptr += 10;
2903 if (idx % 100 == 0) {
2904 ptr--;
2905 *ptr++ = marker;
2906 if (++marker > 'z')
2907 marker = 'a';
2910 uploadBytes[kMsgSize] = '\0';
2912 for (int i = 0; i < kIterations; ++i) {
2913 TestDelegate d;
2914 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2915 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
2916 r->set_method(method.c_str());
2918 r->set_upload(CreateSimpleUploadData(uploadBytes));
2920 r->Start();
2921 EXPECT_TRUE(r->is_pending());
2923 base::RunLoop().Run();
2925 ASSERT_EQ(1, d.response_started_count())
2926 << "request failed: " << r->status().status()
2927 << ", os error: " << r->status().error();
2929 EXPECT_FALSE(d.received_data_before_response());
2930 EXPECT_EQ(uploadBytes, d.data_received());
2932 delete[] uploadBytes;
2935 void AddChunksToUpload(URLRequest* r) {
2936 r->AppendChunkToUpload("a", 1, false);
2937 r->AppendChunkToUpload("bcd", 3, false);
2938 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2939 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2940 r->AppendChunkToUpload("0", 1, false);
2941 r->AppendChunkToUpload("2323", 4, true);
2944 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2945 // This should match the chunks sent by AddChunksToUpload().
2946 const std::string expected_data =
2947 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2949 ASSERT_EQ(1, d->response_started_count())
2950 << "request failed: " << r->status().status()
2951 << ", os error: " << r->status().error();
2953 EXPECT_FALSE(d->received_data_before_response());
2955 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2956 EXPECT_EQ(expected_data, d->data_received());
2959 bool DoManyCookiesRequest(int num_cookies) {
2960 TestDelegate d;
2961 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2962 test_server_.GetURL("set-many-cookies?" +
2963 base::IntToString(num_cookies)),
2964 DEFAULT_PRIORITY, &d));
2966 r->Start();
2967 EXPECT_TRUE(r->is_pending());
2969 base::RunLoop().Run();
2971 bool is_success = r->status().is_success();
2973 if (!is_success) {
2974 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2975 // The test server appears to be unable to handle subsequent requests
2976 // after this error is triggered. Force it to restart.
2977 EXPECT_TRUE(test_server_.Stop());
2978 EXPECT_TRUE(test_server_.Start());
2981 return is_success;
2984 LocalHttpTestServer* test_server() {
2985 return &test_server_;
2988 protected:
2989 LocalHttpTestServer test_server_;
2992 // In this unit test, we're using the HTTPTestServer as a proxy server and
2993 // issuing a CONNECT request with the magic host name "www.redirect.com".
2994 // The HTTPTestServer will return a 302 response, which we should not
2995 // follow.
2996 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2997 ASSERT_TRUE(test_server_.Start());
2999 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3000 TestURLRequestContextWithProxy context(
3001 test_server_.host_port_pair().ToString(), &network_delegate);
3003 TestDelegate d;
3005 scoped_ptr<URLRequest> r(context.CreateRequest(
3006 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
3007 r->Start();
3008 EXPECT_TRUE(r->is_pending());
3010 base::RunLoop().Run();
3012 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3013 // The proxy server is not set before failure.
3014 EXPECT_TRUE(r->proxy_server().IsEmpty());
3015 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3016 EXPECT_EQ(1, d.response_started_count());
3017 // We should not have followed the redirect.
3018 EXPECT_EQ(0, d.received_redirect_count());
3022 // This is the same as the previous test, but checks that the network delegate
3023 // registers the error.
3024 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
3025 ASSERT_TRUE(test_server_.Start());
3027 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3028 TestURLRequestContextWithProxy context(
3029 test_server_.host_port_pair().ToString(), &network_delegate);
3031 TestDelegate d;
3033 scoped_ptr<URLRequest> r(context.CreateRequest(
3034 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
3035 r->Start();
3036 EXPECT_TRUE(r->is_pending());
3038 base::RunLoop().Run();
3040 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3041 // The proxy server is not set before failure.
3042 EXPECT_TRUE(r->proxy_server().IsEmpty());
3043 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3044 EXPECT_EQ(1, d.response_started_count());
3045 // We should not have followed the redirect.
3046 EXPECT_EQ(0, d.received_redirect_count());
3048 EXPECT_EQ(1, network_delegate.error_count());
3049 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
3053 // Tests that we can block and asynchronously return OK in various stages.
3054 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3055 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3056 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3057 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3058 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3060 static const size_t blocking_stages_length = arraysize(blocking_stages);
3062 ASSERT_TRUE(test_server_.Start());
3064 TestDelegate d;
3065 BlockingNetworkDelegate network_delegate(
3066 BlockingNetworkDelegate::USER_CALLBACK);
3067 network_delegate.set_block_on(
3068 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3069 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3070 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3072 TestURLRequestContext context(true);
3073 context.set_network_delegate(&network_delegate);
3074 context.Init();
3077 scoped_ptr<URLRequest> r(context.CreateRequest(
3078 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
3080 r->Start();
3081 for (size_t i = 0; i < blocking_stages_length; ++i) {
3082 base::RunLoop().Run();
3083 EXPECT_EQ(blocking_stages[i],
3084 network_delegate.stage_blocked_for_callback());
3085 network_delegate.DoCallback(OK);
3087 base::RunLoop().Run();
3088 EXPECT_EQ(200, r->GetResponseCode());
3089 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3090 EXPECT_EQ(1, network_delegate.created_requests());
3091 EXPECT_EQ(0, network_delegate.destroyed_requests());
3093 EXPECT_EQ(1, network_delegate.destroyed_requests());
3096 // Tests that the network delegate can block and cancel a request.
3097 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3098 ASSERT_TRUE(test_server_.Start());
3100 TestDelegate d;
3101 BlockingNetworkDelegate network_delegate(
3102 BlockingNetworkDelegate::AUTO_CALLBACK);
3103 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3104 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
3106 TestURLRequestContextWithProxy context(
3107 test_server_.host_port_pair().ToString(), &network_delegate);
3110 scoped_ptr<URLRequest> r(context.CreateRequest(
3111 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
3113 r->Start();
3114 base::RunLoop().Run();
3116 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3117 // The proxy server is not set before cancellation.
3118 EXPECT_TRUE(r->proxy_server().IsEmpty());
3119 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
3120 EXPECT_EQ(1, network_delegate.created_requests());
3121 EXPECT_EQ(0, network_delegate.destroyed_requests());
3123 EXPECT_EQ(1, network_delegate.destroyed_requests());
3126 // Helper function for NetworkDelegateCancelRequestAsynchronously and
3127 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3128 // delegate operating in |block_mode| and a request for |url|. It blocks the
3129 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3130 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3131 BlockingNetworkDelegate::Stage stage,
3132 const GURL& url) {
3133 TestDelegate d;
3134 BlockingNetworkDelegate network_delegate(block_mode);
3135 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3136 network_delegate.set_block_on(stage);
3138 TestURLRequestContext context(true);
3139 context.set_network_delegate(&network_delegate);
3140 context.Init();
3143 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3145 r->Start();
3146 base::RunLoop().Run();
3148 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3149 // The proxy server is not set before cancellation.
3150 EXPECT_TRUE(r->proxy_server().IsEmpty());
3151 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
3152 EXPECT_EQ(1, network_delegate.created_requests());
3153 EXPECT_EQ(0, network_delegate.destroyed_requests());
3155 EXPECT_EQ(1, network_delegate.destroyed_requests());
3158 // The following 3 tests check that the network delegate can cancel a request
3159 // synchronously in various stages of the request.
3160 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3161 ASSERT_TRUE(test_server_.Start());
3162 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3163 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3164 test_server_.GetURL(std::string()));
3167 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3168 ASSERT_TRUE(test_server_.Start());
3169 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3170 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3171 test_server_.GetURL(std::string()));
3174 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3175 ASSERT_TRUE(test_server_.Start());
3176 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3177 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3178 test_server_.GetURL(std::string()));
3181 // The following 3 tests check that the network delegate can cancel a request
3182 // asynchronously in various stages of the request.
3183 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3184 ASSERT_TRUE(test_server_.Start());
3185 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3186 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3187 test_server_.GetURL(std::string()));
3190 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3191 ASSERT_TRUE(test_server_.Start());
3192 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3193 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3194 test_server_.GetURL(std::string()));
3197 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3198 ASSERT_TRUE(test_server_.Start());
3199 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3200 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3201 test_server_.GetURL(std::string()));
3204 // Tests that the network delegate can block and redirect a request to a new
3205 // URL.
3206 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3207 ASSERT_TRUE(test_server_.Start());
3209 TestDelegate d;
3210 BlockingNetworkDelegate network_delegate(
3211 BlockingNetworkDelegate::AUTO_CALLBACK);
3212 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3213 GURL redirect_url(test_server_.GetURL("simple.html"));
3214 network_delegate.set_redirect_url(redirect_url);
3216 TestURLRequestContextWithProxy context(
3217 test_server_.host_port_pair().ToString(), &network_delegate);
3220 GURL original_url(test_server_.GetURL("empty.html"));
3221 scoped_ptr<URLRequest> r(
3222 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
3224 // Quit after hitting the redirect, so can check the headers.
3225 d.set_quit_on_redirect(true);
3226 r->Start();
3227 base::RunLoop().Run();
3229 // Check headers from URLRequestJob.
3230 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3231 EXPECT_EQ(307, r->GetResponseCode());
3232 EXPECT_EQ(307, r->response_headers()->response_code());
3233 std::string location;
3234 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3235 &location));
3236 EXPECT_EQ(redirect_url, GURL(location));
3238 // Let the request finish.
3239 r->FollowDeferredRedirect();
3240 base::RunLoop().Run();
3241 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3242 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3243 EXPECT_EQ(
3244 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3245 EXPECT_TRUE(
3246 network_delegate.last_observed_proxy().Equals(
3247 test_server_.host_port_pair()));
3249 EXPECT_EQ(0, r->status().error());
3250 EXPECT_EQ(redirect_url, r->url());
3251 EXPECT_EQ(original_url, r->original_url());
3252 EXPECT_EQ(2U, r->url_chain().size());
3253 EXPECT_EQ(1, network_delegate.created_requests());
3254 EXPECT_EQ(0, network_delegate.destroyed_requests());
3256 EXPECT_EQ(1, network_delegate.destroyed_requests());
3259 // Tests that the network delegate can block and redirect a request to a new
3260 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3261 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3262 ASSERT_TRUE(test_server_.Start());
3264 TestDelegate d;
3265 BlockingNetworkDelegate network_delegate(
3266 BlockingNetworkDelegate::SYNCHRONOUS);
3267 GURL redirect_url(test_server_.GetURL("simple.html"));
3268 network_delegate.set_redirect_url(redirect_url);
3270 TestURLRequestContextWithProxy context(
3271 test_server_.host_port_pair().ToString(), &network_delegate);
3274 GURL original_url(test_server_.GetURL("empty.html"));
3275 scoped_ptr<URLRequest> r(
3276 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
3278 // Quit after hitting the redirect, so can check the headers.
3279 d.set_quit_on_redirect(true);
3280 r->Start();
3281 base::RunLoop().Run();
3283 // Check headers from URLRequestJob.
3284 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3285 EXPECT_EQ(307, r->GetResponseCode());
3286 EXPECT_EQ(307, r->response_headers()->response_code());
3287 std::string location;
3288 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3289 &location));
3290 EXPECT_EQ(redirect_url, GURL(location));
3292 // Let the request finish.
3293 r->FollowDeferredRedirect();
3294 base::RunLoop().Run();
3296 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3297 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3298 EXPECT_EQ(
3299 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3300 EXPECT_TRUE(
3301 network_delegate.last_observed_proxy().Equals(
3302 test_server_.host_port_pair()));
3303 EXPECT_EQ(0, r->status().error());
3304 EXPECT_EQ(redirect_url, r->url());
3305 EXPECT_EQ(original_url, r->original_url());
3306 EXPECT_EQ(2U, r->url_chain().size());
3307 EXPECT_EQ(1, network_delegate.created_requests());
3308 EXPECT_EQ(0, network_delegate.destroyed_requests());
3310 EXPECT_EQ(1, network_delegate.destroyed_requests());
3313 // Tests that redirects caused by the network delegate preserve POST data.
3314 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3315 ASSERT_TRUE(test_server_.Start());
3317 const char kData[] = "hello world";
3319 TestDelegate d;
3320 BlockingNetworkDelegate network_delegate(
3321 BlockingNetworkDelegate::AUTO_CALLBACK);
3322 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3323 GURL redirect_url(test_server_.GetURL("echo"));
3324 network_delegate.set_redirect_url(redirect_url);
3326 TestURLRequestContext context(true);
3327 context.set_network_delegate(&network_delegate);
3328 context.Init();
3331 GURL original_url(test_server_.GetURL("empty.html"));
3332 scoped_ptr<URLRequest> r(
3333 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
3334 r->set_method("POST");
3335 r->set_upload(CreateSimpleUploadData(kData));
3336 HttpRequestHeaders headers;
3337 headers.SetHeader(HttpRequestHeaders::kContentLength,
3338 base::UintToString(arraysize(kData) - 1));
3339 r->SetExtraRequestHeaders(headers);
3341 // Quit after hitting the redirect, so can check the headers.
3342 d.set_quit_on_redirect(true);
3343 r->Start();
3344 base::RunLoop().Run();
3346 // Check headers from URLRequestJob.
3347 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3348 EXPECT_EQ(307, r->GetResponseCode());
3349 EXPECT_EQ(307, r->response_headers()->response_code());
3350 std::string location;
3351 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3352 &location));
3353 EXPECT_EQ(redirect_url, GURL(location));
3355 // Let the request finish.
3356 r->FollowDeferredRedirect();
3357 base::RunLoop().Run();
3359 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3360 EXPECT_EQ(0, r->status().error());
3361 EXPECT_EQ(redirect_url, r->url());
3362 EXPECT_EQ(original_url, r->original_url());
3363 EXPECT_EQ(2U, r->url_chain().size());
3364 EXPECT_EQ(1, network_delegate.created_requests());
3365 EXPECT_EQ(0, network_delegate.destroyed_requests());
3366 EXPECT_EQ("POST", r->method());
3367 EXPECT_EQ(kData, d.data_received());
3369 EXPECT_EQ(1, network_delegate.destroyed_requests());
3372 // Tests that the network delegate can block and redirect a request to a new
3373 // URL during OnHeadersReceived.
3374 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3375 ASSERT_TRUE(test_server_.Start());
3377 TestDelegate d;
3378 BlockingNetworkDelegate network_delegate(
3379 BlockingNetworkDelegate::AUTO_CALLBACK);
3380 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3381 GURL redirect_url(test_server_.GetURL("simple.html"));
3382 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3384 TestURLRequestContextWithProxy context(
3385 test_server_.host_port_pair().ToString(), &network_delegate);
3388 GURL original_url(test_server_.GetURL("empty.html"));
3389 scoped_ptr<URLRequest> r(
3390 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
3392 r->Start();
3393 base::RunLoop().Run();
3395 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3396 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3397 EXPECT_EQ(
3398 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3399 EXPECT_TRUE(
3400 network_delegate.last_observed_proxy().Equals(
3401 test_server_.host_port_pair()));
3403 EXPECT_EQ(OK, r->status().error());
3404 EXPECT_EQ(redirect_url, r->url());
3405 EXPECT_EQ(original_url, r->original_url());
3406 EXPECT_EQ(2U, r->url_chain().size());
3407 EXPECT_EQ(2, network_delegate.created_requests());
3408 EXPECT_EQ(0, network_delegate.destroyed_requests());
3410 EXPECT_EQ(1, network_delegate.destroyed_requests());
3413 // Tests that the network delegate can synchronously complete OnAuthRequired
3414 // by taking no action. This indicates that the NetworkDelegate does not want to
3415 // handle the challenge, and is passing the buck along to the
3416 // URLRequest::Delegate.
3417 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3418 ASSERT_TRUE(test_server_.Start());
3420 TestDelegate d;
3421 BlockingNetworkDelegate network_delegate(
3422 BlockingNetworkDelegate::SYNCHRONOUS);
3424 TestURLRequestContext context(true);
3425 context.set_network_delegate(&network_delegate);
3426 context.Init();
3428 d.set_credentials(AuthCredentials(kUser, kSecret));
3431 GURL url(test_server_.GetURL("auth-basic"));
3432 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3433 r->Start();
3435 base::RunLoop().Run();
3437 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3438 EXPECT_EQ(0, r->status().error());
3439 EXPECT_EQ(200, r->GetResponseCode());
3440 EXPECT_TRUE(d.auth_required_called());
3441 EXPECT_EQ(1, network_delegate.created_requests());
3442 EXPECT_EQ(0, network_delegate.destroyed_requests());
3444 EXPECT_EQ(1, network_delegate.destroyed_requests());
3447 TEST_F(URLRequestTestHTTP,
3448 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3449 ASSERT_TRUE(test_server_.Start());
3451 TestDelegate d;
3452 BlockingNetworkDelegate network_delegate(
3453 BlockingNetworkDelegate::SYNCHRONOUS);
3455 TestURLRequestContext context(true);
3456 context.set_network_delegate(&network_delegate);
3457 context.Init();
3459 d.set_credentials(AuthCredentials(kUser, kSecret));
3462 GURL url(test_server_.GetURL("auth-basic"));
3463 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3464 r->Start();
3467 HttpRequestHeaders headers;
3468 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3469 EXPECT_FALSE(headers.HasHeader("Authorization"));
3472 base::RunLoop().Run();
3474 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3475 EXPECT_EQ(0, r->status().error());
3476 EXPECT_EQ(200, r->GetResponseCode());
3477 EXPECT_TRUE(d.auth_required_called());
3478 EXPECT_EQ(1, network_delegate.created_requests());
3479 EXPECT_EQ(0, network_delegate.destroyed_requests());
3481 EXPECT_EQ(1, network_delegate.destroyed_requests());
3484 // Tests that the network delegate can synchronously complete OnAuthRequired
3485 // by setting credentials.
3486 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3487 ASSERT_TRUE(test_server_.Start());
3489 TestDelegate d;
3490 BlockingNetworkDelegate network_delegate(
3491 BlockingNetworkDelegate::SYNCHRONOUS);
3492 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3493 network_delegate.set_auth_retval(
3494 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3496 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3498 TestURLRequestContext context(true);
3499 context.set_network_delegate(&network_delegate);
3500 context.Init();
3503 GURL url(test_server_.GetURL("auth-basic"));
3504 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3505 r->Start();
3506 base::RunLoop().Run();
3508 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3509 EXPECT_EQ(0, r->status().error());
3510 EXPECT_EQ(200, r->GetResponseCode());
3511 EXPECT_FALSE(d.auth_required_called());
3512 EXPECT_EQ(1, network_delegate.created_requests());
3513 EXPECT_EQ(0, network_delegate.destroyed_requests());
3515 EXPECT_EQ(1, network_delegate.destroyed_requests());
3518 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3519 // headers (for the first or second request) when called at the proper times.
3520 TEST_F(URLRequestTestHTTP,
3521 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3522 ASSERT_TRUE(test_server_.Start());
3524 TestDelegate d;
3525 BlockingNetworkDelegate network_delegate(
3526 BlockingNetworkDelegate::SYNCHRONOUS);
3527 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3528 network_delegate.set_auth_retval(
3529 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3531 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3533 TestURLRequestContext context(true);
3534 context.set_network_delegate(&network_delegate);
3535 context.Init();
3538 GURL url(test_server_.GetURL("auth-basic"));
3539 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3540 r->Start();
3541 base::RunLoop().Run();
3543 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3544 EXPECT_EQ(0, r->status().error());
3545 EXPECT_EQ(200, r->GetResponseCode());
3546 EXPECT_FALSE(d.auth_required_called());
3547 EXPECT_EQ(1, network_delegate.created_requests());
3548 EXPECT_EQ(0, network_delegate.destroyed_requests());
3551 HttpRequestHeaders headers;
3552 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3553 EXPECT_TRUE(headers.HasHeader("Authorization"));
3556 EXPECT_EQ(1, network_delegate.destroyed_requests());
3559 // Tests that the network delegate can synchronously complete OnAuthRequired
3560 // by cancelling authentication.
3561 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3562 ASSERT_TRUE(test_server_.Start());
3564 TestDelegate d;
3565 BlockingNetworkDelegate network_delegate(
3566 BlockingNetworkDelegate::SYNCHRONOUS);
3567 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3568 network_delegate.set_auth_retval(
3569 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3571 TestURLRequestContext context(true);
3572 context.set_network_delegate(&network_delegate);
3573 context.Init();
3576 GURL url(test_server_.GetURL("auth-basic"));
3577 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3578 r->Start();
3579 base::RunLoop().Run();
3581 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3582 EXPECT_EQ(OK, r->status().error());
3583 EXPECT_EQ(401, r->GetResponseCode());
3584 EXPECT_FALSE(d.auth_required_called());
3585 EXPECT_EQ(1, network_delegate.created_requests());
3586 EXPECT_EQ(0, network_delegate.destroyed_requests());
3588 EXPECT_EQ(1, network_delegate.destroyed_requests());
3591 // Tests that the network delegate can asynchronously complete OnAuthRequired
3592 // by taking no action. This indicates that the NetworkDelegate does not want
3593 // to handle the challenge, and is passing the buck along to the
3594 // URLRequest::Delegate.
3595 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3596 ASSERT_TRUE(test_server_.Start());
3598 TestDelegate d;
3599 BlockingNetworkDelegate network_delegate(
3600 BlockingNetworkDelegate::AUTO_CALLBACK);
3601 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3603 TestURLRequestContext context(true);
3604 context.set_network_delegate(&network_delegate);
3605 context.Init();
3607 d.set_credentials(AuthCredentials(kUser, kSecret));
3610 GURL url(test_server_.GetURL("auth-basic"));
3611 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3612 r->Start();
3613 base::RunLoop().Run();
3615 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3616 EXPECT_EQ(0, r->status().error());
3617 EXPECT_EQ(200, r->GetResponseCode());
3618 EXPECT_TRUE(d.auth_required_called());
3619 EXPECT_EQ(1, network_delegate.created_requests());
3620 EXPECT_EQ(0, network_delegate.destroyed_requests());
3622 EXPECT_EQ(1, network_delegate.destroyed_requests());
3625 // Tests that the network delegate can asynchronously complete OnAuthRequired
3626 // by setting credentials.
3627 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3628 ASSERT_TRUE(test_server_.Start());
3630 TestDelegate d;
3631 BlockingNetworkDelegate network_delegate(
3632 BlockingNetworkDelegate::AUTO_CALLBACK);
3633 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3634 network_delegate.set_auth_retval(
3635 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3637 AuthCredentials auth_credentials(kUser, kSecret);
3638 network_delegate.set_auth_credentials(auth_credentials);
3640 TestURLRequestContext context(true);
3641 context.set_network_delegate(&network_delegate);
3642 context.Init();
3645 GURL url(test_server_.GetURL("auth-basic"));
3646 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3647 r->Start();
3648 base::RunLoop().Run();
3650 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3651 EXPECT_EQ(0, r->status().error());
3653 EXPECT_EQ(200, r->GetResponseCode());
3654 EXPECT_FALSE(d.auth_required_called());
3655 EXPECT_EQ(1, network_delegate.created_requests());
3656 EXPECT_EQ(0, network_delegate.destroyed_requests());
3658 EXPECT_EQ(1, network_delegate.destroyed_requests());
3661 // Tests that the network delegate can asynchronously complete OnAuthRequired
3662 // by cancelling authentication.
3663 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3664 ASSERT_TRUE(test_server_.Start());
3666 TestDelegate d;
3667 BlockingNetworkDelegate network_delegate(
3668 BlockingNetworkDelegate::AUTO_CALLBACK);
3669 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3670 network_delegate.set_auth_retval(
3671 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3673 TestURLRequestContext context(true);
3674 context.set_network_delegate(&network_delegate);
3675 context.Init();
3678 GURL url(test_server_.GetURL("auth-basic"));
3679 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
3680 r->Start();
3681 base::RunLoop().Run();
3683 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3684 EXPECT_EQ(OK, r->status().error());
3685 EXPECT_EQ(401, r->GetResponseCode());
3686 EXPECT_FALSE(d.auth_required_called());
3687 EXPECT_EQ(1, network_delegate.created_requests());
3688 EXPECT_EQ(0, network_delegate.destroyed_requests());
3690 EXPECT_EQ(1, network_delegate.destroyed_requests());
3693 // Tests that we can handle when a network request was canceled while we were
3694 // waiting for the network delegate.
3695 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3696 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3697 ASSERT_TRUE(test_server_.Start());
3699 TestDelegate d;
3700 BlockingNetworkDelegate network_delegate(
3701 BlockingNetworkDelegate::USER_CALLBACK);
3702 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3704 TestURLRequestContext context(true);
3705 context.set_network_delegate(&network_delegate);
3706 context.Init();
3709 scoped_ptr<URLRequest> r(context.CreateRequest(
3710 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
3712 r->Start();
3713 base::RunLoop().Run();
3714 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3715 network_delegate.stage_blocked_for_callback());
3716 EXPECT_EQ(0, network_delegate.completed_requests());
3717 // Cancel before callback.
3718 r->Cancel();
3719 // Ensure that network delegate is notified.
3720 EXPECT_EQ(1, network_delegate.completed_requests());
3721 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3722 EXPECT_EQ(ERR_ABORTED, r->status().error());
3723 EXPECT_EQ(1, network_delegate.created_requests());
3724 EXPECT_EQ(0, network_delegate.destroyed_requests());
3726 EXPECT_EQ(1, network_delegate.destroyed_requests());
3729 // Tests that we can handle when a network request was canceled while we were
3730 // waiting for the network delegate.
3731 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3732 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3733 ASSERT_TRUE(test_server_.Start());
3735 TestDelegate d;
3736 BlockingNetworkDelegate network_delegate(
3737 BlockingNetworkDelegate::USER_CALLBACK);
3738 network_delegate.set_block_on(
3739 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
3741 TestURLRequestContext context(true);
3742 context.set_network_delegate(&network_delegate);
3743 context.Init();
3746 scoped_ptr<URLRequest> r(context.CreateRequest(
3747 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
3749 r->Start();
3750 base::RunLoop().Run();
3751 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3752 network_delegate.stage_blocked_for_callback());
3753 EXPECT_EQ(0, network_delegate.completed_requests());
3754 // Cancel before callback.
3755 r->Cancel();
3756 // Ensure that network delegate is notified.
3757 EXPECT_EQ(1, network_delegate.completed_requests());
3758 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3759 EXPECT_EQ(ERR_ABORTED, r->status().error());
3760 EXPECT_EQ(1, network_delegate.created_requests());
3761 EXPECT_EQ(0, network_delegate.destroyed_requests());
3763 EXPECT_EQ(1, network_delegate.destroyed_requests());
3766 // Tests that we can handle when a network request was canceled while we were
3767 // waiting for the network delegate.
3768 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3769 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3770 ASSERT_TRUE(test_server_.Start());
3772 TestDelegate d;
3773 BlockingNetworkDelegate network_delegate(
3774 BlockingNetworkDelegate::USER_CALLBACK);
3775 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3777 TestURLRequestContext context(true);
3778 context.set_network_delegate(&network_delegate);
3779 context.Init();
3782 scoped_ptr<URLRequest> r(context.CreateRequest(
3783 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
3785 r->Start();
3786 base::RunLoop().Run();
3787 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3788 network_delegate.stage_blocked_for_callback());
3789 EXPECT_EQ(0, network_delegate.completed_requests());
3790 // Cancel before callback.
3791 r->Cancel();
3792 // Ensure that network delegate is notified.
3793 EXPECT_EQ(1, network_delegate.completed_requests());
3794 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3795 EXPECT_EQ(ERR_ABORTED, r->status().error());
3796 EXPECT_EQ(1, network_delegate.created_requests());
3797 EXPECT_EQ(0, network_delegate.destroyed_requests());
3799 EXPECT_EQ(1, network_delegate.destroyed_requests());
3802 // Tests that we can handle when a network request was canceled while we were
3803 // waiting for the network delegate.
3804 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3805 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
3806 ASSERT_TRUE(test_server_.Start());
3808 TestDelegate d;
3809 BlockingNetworkDelegate network_delegate(
3810 BlockingNetworkDelegate::USER_CALLBACK);
3811 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3813 TestURLRequestContext context(true);
3814 context.set_network_delegate(&network_delegate);
3815 context.Init();
3818 scoped_ptr<URLRequest> r(context.CreateRequest(
3819 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
3821 r->Start();
3822 base::RunLoop().Run();
3823 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3824 network_delegate.stage_blocked_for_callback());
3825 EXPECT_EQ(0, network_delegate.completed_requests());
3826 // Cancel before callback.
3827 r->Cancel();
3828 // Ensure that network delegate is notified.
3829 EXPECT_EQ(1, network_delegate.completed_requests());
3830 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3831 EXPECT_EQ(ERR_ABORTED, r->status().error());
3832 EXPECT_EQ(1, network_delegate.created_requests());
3833 EXPECT_EQ(0, network_delegate.destroyed_requests());
3835 EXPECT_EQ(1, network_delegate.destroyed_requests());
3838 // In this unit test, we're using the HTTPTestServer as a proxy server and
3839 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3840 // The HTTPTestServer will return a 401 response, which we should balk at.
3841 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
3842 ASSERT_TRUE(test_server_.Start());
3844 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3845 TestURLRequestContextWithProxy context(
3846 test_server_.host_port_pair().ToString(), &network_delegate);
3848 TestDelegate d;
3850 scoped_ptr<URLRequest> r(context.CreateRequest(
3851 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
3853 r->Start();
3854 EXPECT_TRUE(r->is_pending());
3856 base::RunLoop().Run();
3858 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3859 // The proxy server is not set before failure.
3860 EXPECT_TRUE(r->proxy_server().IsEmpty());
3861 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3865 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
3866 ASSERT_TRUE(test_server_.Start());
3868 TestDelegate d;
3870 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3871 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
3873 r->Start();
3874 EXPECT_TRUE(r->is_pending());
3876 base::RunLoop().Run();
3878 EXPECT_EQ(1, d.response_started_count());
3879 EXPECT_FALSE(d.received_data_before_response());
3880 EXPECT_NE(0, d.bytes_received());
3881 EXPECT_EQ(test_server_.host_port_pair().host(),
3882 r->GetSocketAddress().host());
3883 EXPECT_EQ(test_server_.host_port_pair().port(),
3884 r->GetSocketAddress().port());
3886 // TODO(eroman): Add back the NetLog tests...
3890 // This test has the server send a large number of cookies to the client.
3891 // To ensure that no number of cookies causes a crash, a galloping binary
3892 // search is used to estimate that maximum number of cookies that are accepted
3893 // by the browser. Beyond the maximum number, the request will fail with
3894 // ERR_RESPONSE_HEADERS_TOO_BIG.
3895 #if defined(OS_WIN)
3896 // http://crbug.com/177916
3897 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3898 #else
3899 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3900 #endif // defined(OS_WIN)
3901 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
3902 ASSERT_TRUE(test_server_.Start());
3904 int lower_bound = 0;
3905 int upper_bound = 1;
3907 // Double the number of cookies until the response header limits are
3908 // exceeded.
3909 while (DoManyCookiesRequest(upper_bound)) {
3910 lower_bound = upper_bound;
3911 upper_bound *= 2;
3912 ASSERT_LT(upper_bound, 1000000);
3915 int tolerance = static_cast<int>(upper_bound * 0.005);
3916 if (tolerance < 2)
3917 tolerance = 2;
3919 // Perform a binary search to find the highest possible number of cookies,
3920 // within the desired tolerance.
3921 while (upper_bound - lower_bound >= tolerance) {
3922 int num_cookies = (lower_bound + upper_bound) / 2;
3924 if (DoManyCookiesRequest(num_cookies))
3925 lower_bound = num_cookies;
3926 else
3927 upper_bound = num_cookies;
3929 // Success: the test did not crash.
3932 TEST_F(URLRequestTestHTTP, GetTest) {
3933 ASSERT_TRUE(test_server_.Start());
3935 TestDelegate d;
3937 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3938 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
3940 r->Start();
3941 EXPECT_TRUE(r->is_pending());
3943 base::RunLoop().Run();
3945 EXPECT_EQ(1, d.response_started_count());
3946 EXPECT_FALSE(d.received_data_before_response());
3947 EXPECT_NE(0, d.bytes_received());
3948 EXPECT_EQ(test_server_.host_port_pair().host(),
3949 r->GetSocketAddress().host());
3950 EXPECT_EQ(test_server_.host_port_pair().port(),
3951 r->GetSocketAddress().port());
3955 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3956 ASSERT_TRUE(test_server_.Start());
3958 TestDelegate d;
3960 GURL test_url(test_server_.GetURL(std::string()));
3961 scoped_ptr<URLRequest> r(
3962 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
3964 HttpRequestHeaders headers;
3965 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
3967 r->Start();
3968 EXPECT_TRUE(r->is_pending());
3970 base::RunLoop().Run();
3972 EXPECT_EQ(1, d.response_started_count());
3973 EXPECT_FALSE(d.received_data_before_response());
3974 EXPECT_NE(0, d.bytes_received());
3975 EXPECT_EQ(test_server_.host_port_pair().host(),
3976 r->GetSocketAddress().host());
3977 EXPECT_EQ(test_server_.host_port_pair().port(),
3978 r->GetSocketAddress().port());
3980 EXPECT_TRUE(d.have_full_request_headers());
3981 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3985 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3986 ASSERT_TRUE(test_server_.Start());
3988 TestDelegate d;
3990 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3991 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
3993 r->Start();
3994 EXPECT_TRUE(r->is_pending());
3996 base::RunLoop().Run();
3998 LoadTimingInfo load_timing_info;
3999 r->GetLoadTimingInfo(&load_timing_info);
4000 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4002 EXPECT_EQ(1, d.response_started_count());
4003 EXPECT_FALSE(d.received_data_before_response());
4004 EXPECT_NE(0, d.bytes_received());
4005 EXPECT_EQ(test_server_.host_port_pair().host(),
4006 r->GetSocketAddress().host());
4007 EXPECT_EQ(test_server_.host_port_pair().port(),
4008 r->GetSocketAddress().port());
4012 TEST_F(URLRequestTestHTTP, GetZippedTest) {
4013 ASSERT_TRUE(test_server_.Start());
4015 // Parameter that specifies the Content-Length field in the response:
4016 // C - Compressed length.
4017 // U - Uncompressed length.
4018 // L - Large length (larger than both C & U).
4019 // M - Medium length (between C & U).
4020 // S - Small length (smaller than both C & U).
4021 const char test_parameters[] = "CULMS";
4022 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4023 // C & U should be OK.
4024 // L & M are larger than the data sent, and show an error.
4025 // S has too little data, but we seem to accept it.
4026 const bool test_expect_success[num_tests] =
4027 { true, true, false, false, true };
4029 for (int i = 0; i < num_tests ; i++) {
4030 TestDelegate d;
4032 std::string test_file =
4033 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4034 test_parameters[i]);
4036 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4037 TestURLRequestContext context(true);
4038 context.set_network_delegate(&network_delegate);
4039 context.Init();
4041 scoped_ptr<URLRequest> r(context.CreateRequest(
4042 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d));
4043 r->Start();
4044 EXPECT_TRUE(r->is_pending());
4046 base::RunLoop().Run();
4048 EXPECT_EQ(1, d.response_started_count());
4049 EXPECT_FALSE(d.received_data_before_response());
4050 VLOG(1) << " Received " << d.bytes_received() << " bytes"
4051 << " status = " << r->status().status()
4052 << " error = " << r->status().error();
4053 if (test_expect_success[i]) {
4054 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
4055 << " Parameter = \"" << test_file << "\"";
4056 } else {
4057 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4058 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
4059 << " Parameter = \"" << test_file << "\"";
4065 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4066 ASSERT_TRUE(test_server_.Start());
4068 GURL destination_url = test_server_.GetURL(std::string());
4069 GURL original_url =
4070 test_server_.GetURL("server-redirect?" + destination_url.spec());
4071 TestDelegate d;
4072 scoped_ptr<URLRequest> req(
4073 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
4074 req->Start();
4075 base::RunLoop().Run();
4077 EXPECT_EQ(1, d.response_started_count());
4078 EXPECT_EQ(1, d.received_redirect_count());
4079 EXPECT_EQ(destination_url, req->url());
4080 EXPECT_EQ(original_url, req->original_url());
4081 ASSERT_EQ(2U, req->url_chain().size());
4082 EXPECT_EQ(original_url, req->url_chain()[0]);
4083 EXPECT_EQ(destination_url, req->url_chain()[1]);
4085 LoadTimingInfo load_timing_info_before_redirect;
4086 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4087 &load_timing_info_before_redirect));
4088 TestLoadTimingNotReused(load_timing_info_before_redirect,
4089 CONNECT_TIMING_HAS_DNS_TIMES);
4091 LoadTimingInfo load_timing_info;
4092 req->GetLoadTimingInfo(&load_timing_info);
4093 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4095 // Check that a new socket was used on redirect, since the server does not
4096 // supposed keep-alive sockets, and that the times before the redirect are
4097 // before the ones recorded for the second request.
4098 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4099 load_timing_info.socket_log_id);
4100 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4101 load_timing_info.connect_timing.connect_start);
4104 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4105 ASSERT_TRUE(test_server_.Start());
4107 GURL destination_url = test_server_.GetURL(std::string());
4108 GURL middle_redirect_url =
4109 test_server_.GetURL("server-redirect?" + destination_url.spec());
4110 GURL original_url = test_server_.GetURL(
4111 "server-redirect?" + middle_redirect_url.spec());
4112 TestDelegate d;
4113 scoped_ptr<URLRequest> req(
4114 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
4115 req->Start();
4116 base::RunLoop().Run();
4118 EXPECT_EQ(1, d.response_started_count());
4119 EXPECT_EQ(2, d.received_redirect_count());
4120 EXPECT_EQ(destination_url, req->url());
4121 EXPECT_EQ(original_url, req->original_url());
4122 ASSERT_EQ(3U, req->url_chain().size());
4123 EXPECT_EQ(original_url, req->url_chain()[0]);
4124 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4125 EXPECT_EQ(destination_url, req->url_chain()[2]);
4128 // First and second pieces of information logged by delegates to URLRequests.
4129 const char kFirstDelegateInfo[] = "Wonderful delegate";
4130 const char kSecondDelegateInfo[] = "Exciting delegate";
4132 // Logs delegate information to a URLRequest. The first string is logged
4133 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4134 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4135 // another asynchronous call is used to clear the delegate information
4136 // before calling a callback. The object then deletes itself.
4137 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4138 public:
4139 typedef base::Callback<void()> Callback;
4141 // Each time delegate information is added to the URLRequest, the resulting
4142 // load state is checked. The expected load state after each request is
4143 // passed in as an argument.
4144 static void Run(URLRequest* url_request,
4145 LoadState expected_first_load_state,
4146 LoadState expected_second_load_state,
4147 LoadState expected_third_load_state,
4148 const Callback& callback) {
4149 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4150 url_request,
4151 expected_first_load_state,
4152 expected_second_load_state,
4153 expected_third_load_state,
4154 callback);
4155 logger->Start();
4158 // Checks that the log entries, starting with log_position, contain the
4159 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4160 // recorded. Returns the index of entry after the expected number of
4161 // events this logged, or entries.size() if there aren't enough entries.
4162 static size_t CheckDelegateInfo(
4163 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
4164 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4165 if (log_position + 3 >= entries.size()) {
4166 ADD_FAILURE() << "Not enough log entries";
4167 return entries.size();
4169 std::string delegate_info;
4170 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4171 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4172 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4173 &delegate_info));
4174 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4176 ++log_position;
4177 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4178 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4180 ++log_position;
4181 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4182 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4183 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4184 &delegate_info));
4185 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4187 ++log_position;
4188 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4189 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4191 return log_position + 1;
4194 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4195 // Returns the position of the end message.
4196 static size_t ExpectBeforeNetworkEvents(
4197 const CapturingNetLog::CapturedEntryList& entries,
4198 size_t log_position) {
4199 log_position =
4200 ExpectLogContainsSomewhereAfter(entries,
4201 log_position,
4202 NetLog::TYPE_URL_REQUEST_DELEGATE,
4203 NetLog::PHASE_BEGIN);
4204 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4205 entries[log_position + 1].type);
4206 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4207 return log_position + 1;
4210 private:
4211 friend class base::RefCounted<AsyncDelegateLogger>;
4213 AsyncDelegateLogger(URLRequest* url_request,
4214 LoadState expected_first_load_state,
4215 LoadState expected_second_load_state,
4216 LoadState expected_third_load_state,
4217 const Callback& callback)
4218 : url_request_(url_request),
4219 expected_first_load_state_(expected_first_load_state),
4220 expected_second_load_state_(expected_second_load_state),
4221 expected_third_load_state_(expected_third_load_state),
4222 callback_(callback) {
4225 ~AsyncDelegateLogger() {}
4227 void Start() {
4228 url_request_->LogBlockedBy(kFirstDelegateInfo);
4229 LoadStateWithParam load_state = url_request_->GetLoadState();
4230 EXPECT_EQ(expected_first_load_state_, load_state.state);
4231 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4232 base::MessageLoop::current()->PostTask(
4233 FROM_HERE,
4234 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4237 void LogSecondDelegate() {
4238 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
4239 LoadStateWithParam load_state = url_request_->GetLoadState();
4240 EXPECT_EQ(expected_second_load_state_, load_state.state);
4241 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4242 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4243 } else {
4244 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4246 base::MessageLoop::current()->PostTask(
4247 FROM_HERE,
4248 base::Bind(&AsyncDelegateLogger::LogComplete, this));
4251 void LogComplete() {
4252 url_request_->LogUnblocked();
4253 LoadStateWithParam load_state = url_request_->GetLoadState();
4254 EXPECT_EQ(expected_third_load_state_, load_state.state);
4255 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
4256 EXPECT_EQ(base::string16(), load_state.param);
4257 callback_.Run();
4260 URLRequest* url_request_;
4261 const int expected_first_load_state_;
4262 const int expected_second_load_state_;
4263 const int expected_third_load_state_;
4264 const Callback callback_;
4266 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4269 // NetworkDelegate that logs delegate information before a request is started,
4270 // before headers are sent, when headers are read, and when auth information
4271 // is requested. Uses AsyncDelegateLogger.
4272 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4273 public:
4274 AsyncLoggingNetworkDelegate() {}
4275 ~AsyncLoggingNetworkDelegate() override {}
4277 // NetworkDelegate implementation.
4278 int OnBeforeURLRequest(URLRequest* request,
4279 const CompletionCallback& callback,
4280 GURL* new_url) override {
4281 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4282 return RunCallbackAsynchronously(request, callback);
4285 int OnBeforeSendHeaders(URLRequest* request,
4286 const CompletionCallback& callback,
4287 HttpRequestHeaders* headers) override {
4288 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4289 return RunCallbackAsynchronously(request, callback);
4292 int OnHeadersReceived(
4293 URLRequest* request,
4294 const CompletionCallback& callback,
4295 const HttpResponseHeaders* original_response_headers,
4296 scoped_refptr<HttpResponseHeaders>* override_response_headers,
4297 GURL* allowed_unsafe_redirect_url) override {
4298 TestNetworkDelegate::OnHeadersReceived(request,
4299 callback,
4300 original_response_headers,
4301 override_response_headers,
4302 allowed_unsafe_redirect_url);
4303 return RunCallbackAsynchronously(request, callback);
4306 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
4307 URLRequest* request,
4308 const AuthChallengeInfo& auth_info,
4309 const AuthCallback& callback,
4310 AuthCredentials* credentials) override {
4311 AsyncDelegateLogger::Run(
4312 request,
4313 LOAD_STATE_WAITING_FOR_DELEGATE,
4314 LOAD_STATE_WAITING_FOR_DELEGATE,
4315 LOAD_STATE_WAITING_FOR_DELEGATE,
4316 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4317 callback, credentials));
4318 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4321 private:
4322 static int RunCallbackAsynchronously(
4323 URLRequest* request,
4324 const CompletionCallback& callback) {
4325 AsyncDelegateLogger::Run(
4326 request,
4327 LOAD_STATE_WAITING_FOR_DELEGATE,
4328 LOAD_STATE_WAITING_FOR_DELEGATE,
4329 LOAD_STATE_WAITING_FOR_DELEGATE,
4330 base::Bind(callback, OK));
4331 return ERR_IO_PENDING;
4334 static void SetAuthAndResume(const AuthCallback& callback,
4335 AuthCredentials* credentials) {
4336 *credentials = AuthCredentials(kUser, kSecret);
4337 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4340 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4343 // URLRequest::Delegate that logs delegate information when the headers
4344 // are received, when each read completes, and during redirects. Uses
4345 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4347 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4348 // advancing to the next step in most cases, as well as cancellation.
4349 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4350 public:
4351 enum CancelStage {
4352 NO_CANCEL = 0,
4353 CANCEL_ON_RECEIVED_REDIRECT,
4354 CANCEL_ON_RESPONSE_STARTED,
4355 CANCEL_ON_READ_COMPLETED
4358 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4359 : cancel_stage_(cancel_stage) {
4360 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4361 set_cancel_in_received_redirect(true);
4362 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4363 set_cancel_in_response_started(true);
4364 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4365 set_cancel_in_received_data(true);
4367 ~AsyncLoggingUrlRequestDelegate() override {}
4369 // URLRequest::Delegate implementation:
4370 void OnReceivedRedirect(URLRequest* request,
4371 const RedirectInfo& redirect_info,
4372 bool* defer_redirect) override {
4373 *defer_redirect = true;
4374 AsyncDelegateLogger::Run(
4375 request,
4376 LOAD_STATE_WAITING_FOR_DELEGATE,
4377 LOAD_STATE_WAITING_FOR_DELEGATE,
4378 LOAD_STATE_WAITING_FOR_DELEGATE,
4379 base::Bind(
4380 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4381 base::Unretained(this), request, redirect_info));
4384 void OnResponseStarted(URLRequest* request) override {
4385 AsyncDelegateLogger::Run(
4386 request,
4387 LOAD_STATE_WAITING_FOR_DELEGATE,
4388 LOAD_STATE_WAITING_FOR_DELEGATE,
4389 LOAD_STATE_WAITING_FOR_DELEGATE,
4390 base::Bind(
4391 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4392 base::Unretained(this), request));
4395 void OnReadCompleted(URLRequest* request, int bytes_read) override {
4396 AsyncDelegateLogger::Run(
4397 request,
4398 LOAD_STATE_IDLE,
4399 LOAD_STATE_IDLE,
4400 LOAD_STATE_IDLE,
4401 base::Bind(
4402 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4403 base::Unretained(this), request, bytes_read));
4406 private:
4407 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4408 const RedirectInfo& redirect_info) {
4409 bool defer_redirect = false;
4410 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
4411 // FollowDeferredRedirect should not be called after cancellation.
4412 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4413 return;
4414 if (!defer_redirect)
4415 request->FollowDeferredRedirect();
4418 void OnResponseStartedLoggingComplete(URLRequest* request) {
4419 // The parent class continues the request.
4420 TestDelegate::OnResponseStarted(request);
4423 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4424 // The parent class continues the request.
4425 TestDelegate::OnReadCompleted(request, bytes_read);
4428 const CancelStage cancel_stage_;
4430 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4433 // Tests handling of delegate info before a request starts.
4434 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4435 ASSERT_TRUE(test_server_.Start());
4437 TestDelegate request_delegate;
4438 TestURLRequestContext context(true);
4439 context.set_network_delegate(NULL);
4440 context.set_net_log(&net_log_);
4441 context.Init();
4444 scoped_ptr<URLRequest> r(
4445 context.CreateRequest(test_server_.GetURL("empty.html"),
4446 DEFAULT_PRIORITY, &request_delegate));
4447 LoadStateWithParam load_state = r->GetLoadState();
4448 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4449 EXPECT_EQ(base::string16(), load_state.param);
4451 AsyncDelegateLogger::Run(
4452 r.get(),
4453 LOAD_STATE_WAITING_FOR_DELEGATE,
4454 LOAD_STATE_WAITING_FOR_DELEGATE,
4455 LOAD_STATE_IDLE,
4456 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
4458 base::RunLoop().Run();
4460 EXPECT_EQ(200, r->GetResponseCode());
4461 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4464 CapturingNetLog::CapturedEntryList entries;
4465 net_log_.GetEntries(&entries);
4466 size_t log_position = ExpectLogContainsSomewhereAfter(
4467 entries,
4469 NetLog::TYPE_DELEGATE_INFO,
4470 NetLog::PHASE_BEGIN);
4472 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4474 // Nothing else should add any delegate info to the request.
4475 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4476 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4479 // Tests handling of delegate info from a network delegate.
4480 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4481 ASSERT_TRUE(test_server_.Start());
4483 TestDelegate request_delegate;
4484 AsyncLoggingNetworkDelegate network_delegate;
4485 TestURLRequestContext context(true);
4486 context.set_network_delegate(&network_delegate);
4487 context.set_net_log(&net_log_);
4488 context.Init();
4491 scoped_ptr<URLRequest> r(
4492 context.CreateRequest(test_server_.GetURL("simple.html"),
4493 DEFAULT_PRIORITY, &request_delegate));
4494 LoadStateWithParam load_state = r->GetLoadState();
4495 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4496 EXPECT_EQ(base::string16(), load_state.param);
4498 r->Start();
4499 base::RunLoop().Run();
4501 EXPECT_EQ(200, r->GetResponseCode());
4502 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4503 EXPECT_EQ(1, network_delegate.created_requests());
4504 EXPECT_EQ(0, network_delegate.destroyed_requests());
4506 EXPECT_EQ(1, network_delegate.destroyed_requests());
4508 size_t log_position = 0;
4509 CapturingNetLog::CapturedEntryList entries;
4510 net_log_.GetEntries(&entries);
4511 for (size_t i = 0; i < 3; ++i) {
4512 log_position = ExpectLogContainsSomewhereAfter(
4513 entries,
4514 log_position + 1,
4515 NetLog::TYPE_URL_REQUEST_DELEGATE,
4516 NetLog::PHASE_BEGIN);
4518 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4519 log_position + 1);
4521 ASSERT_LT(log_position, entries.size());
4522 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4523 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4525 if (i == 1) {
4526 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4527 entries, log_position + 1);
4531 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4532 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4535 // Tests handling of delegate info from a network delegate in the case of an
4536 // HTTP redirect.
4537 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4538 ASSERT_TRUE(test_server_.Start());
4540 TestDelegate request_delegate;
4541 AsyncLoggingNetworkDelegate network_delegate;
4542 TestURLRequestContext context(true);
4543 context.set_network_delegate(&network_delegate);
4544 context.set_net_log(&net_log_);
4545 context.Init();
4548 scoped_ptr<URLRequest> r(context.CreateRequest(
4549 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4550 &request_delegate));
4551 LoadStateWithParam load_state = r->GetLoadState();
4552 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4553 EXPECT_EQ(base::string16(), load_state.param);
4555 r->Start();
4556 base::RunLoop().Run();
4558 EXPECT_EQ(200, r->GetResponseCode());
4559 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4560 EXPECT_EQ(2, network_delegate.created_requests());
4561 EXPECT_EQ(0, network_delegate.destroyed_requests());
4563 EXPECT_EQ(1, network_delegate.destroyed_requests());
4565 size_t log_position = 0;
4566 CapturingNetLog::CapturedEntryList entries;
4567 net_log_.GetEntries(&entries);
4568 // The NetworkDelegate logged information in OnBeforeURLRequest,
4569 // OnBeforeSendHeaders, and OnHeadersReceived.
4570 for (size_t i = 0; i < 3; ++i) {
4571 log_position = ExpectLogContainsSomewhereAfter(
4572 entries,
4573 log_position + 1,
4574 NetLog::TYPE_URL_REQUEST_DELEGATE,
4575 NetLog::PHASE_BEGIN);
4577 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4578 log_position + 1);
4580 ASSERT_LT(log_position, entries.size());
4581 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4582 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4584 if (i == 1) {
4585 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4586 entries, log_position + 1);
4590 // The URLRequest::Delegate then gets informed about the redirect.
4591 log_position = ExpectLogContainsSomewhereAfter(
4592 entries,
4593 log_position + 1,
4594 NetLog::TYPE_URL_REQUEST_DELEGATE,
4595 NetLog::PHASE_BEGIN);
4597 // The NetworkDelegate logged information in the same three events as before.
4598 for (size_t i = 0; i < 3; ++i) {
4599 log_position = ExpectLogContainsSomewhereAfter(
4600 entries,
4601 log_position + 1,
4602 NetLog::TYPE_URL_REQUEST_DELEGATE,
4603 NetLog::PHASE_BEGIN);
4605 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4606 log_position + 1);
4608 ASSERT_LT(log_position, entries.size());
4609 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4610 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4613 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4614 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4617 // Tests handling of delegate info from a network delegate in the case of HTTP
4618 // AUTH.
4619 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4620 ASSERT_TRUE(test_server_.Start());
4622 TestDelegate request_delegate;
4623 AsyncLoggingNetworkDelegate network_delegate;
4624 TestURLRequestContext context(true);
4625 context.set_network_delegate(&network_delegate);
4626 context.set_net_log(&net_log_);
4627 context.Init();
4630 scoped_ptr<URLRequest> r(
4631 context.CreateRequest(test_server_.GetURL("auth-basic"),
4632 DEFAULT_PRIORITY, &request_delegate));
4633 LoadStateWithParam load_state = r->GetLoadState();
4634 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4635 EXPECT_EQ(base::string16(), load_state.param);
4637 r->Start();
4638 base::RunLoop().Run();
4640 EXPECT_EQ(200, r->GetResponseCode());
4641 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4642 EXPECT_EQ(1, network_delegate.created_requests());
4643 EXPECT_EQ(0, network_delegate.destroyed_requests());
4645 EXPECT_EQ(1, network_delegate.destroyed_requests());
4647 size_t log_position = 0;
4648 CapturingNetLog::CapturedEntryList entries;
4649 net_log_.GetEntries(&entries);
4650 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4651 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4652 // OnBeforeURLRequest and OnBeforeSendHeaders.
4653 for (size_t i = 0; i < 6; ++i) {
4654 log_position = ExpectLogContainsSomewhereAfter(
4655 entries,
4656 log_position + 1,
4657 NetLog::TYPE_URL_REQUEST_DELEGATE,
4658 NetLog::PHASE_BEGIN);
4660 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4661 log_position + 1);
4663 ASSERT_LT(log_position, entries.size());
4664 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4665 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4667 if (i == 1) {
4668 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4669 entries, log_position + 1);
4673 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4674 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4677 // Tests handling of delegate info from a URLRequest::Delegate.
4678 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4679 ASSERT_TRUE(test_server_.Start());
4681 AsyncLoggingUrlRequestDelegate request_delegate(
4682 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4683 TestURLRequestContext context(true);
4684 context.set_network_delegate(NULL);
4685 context.set_net_log(&net_log_);
4686 context.Init();
4689 // A chunked response with delays between chunks is used to make sure that
4690 // attempts by the URLRequest delegate to log information while reading the
4691 // body are ignored. Since they are ignored, this test is robust against
4692 // the possibility of multiple reads being combined in the unlikely event
4693 // that it occurs.
4694 scoped_ptr<URLRequest> r(context.CreateRequest(
4695 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
4696 &request_delegate));
4697 LoadStateWithParam load_state = r->GetLoadState();
4698 r->Start();
4699 base::RunLoop().Run();
4701 EXPECT_EQ(200, r->GetResponseCode());
4702 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4705 CapturingNetLog::CapturedEntryList entries;
4706 net_log_.GetEntries(&entries);
4708 size_t log_position = 0;
4710 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4711 entries, log_position);
4713 // The delegate info should only have been logged on header complete. Other
4714 // times it should silently be ignored.
4715 log_position =
4716 ExpectLogContainsSomewhereAfter(entries,
4717 log_position + 1,
4718 NetLog::TYPE_URL_REQUEST_DELEGATE,
4719 NetLog::PHASE_BEGIN);
4721 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4722 log_position + 1);
4724 ASSERT_LT(log_position, entries.size());
4725 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4726 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4728 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4729 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4730 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4731 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4734 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4735 // an HTTP redirect.
4736 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4737 ASSERT_TRUE(test_server_.Start());
4739 AsyncLoggingUrlRequestDelegate request_delegate(
4740 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4741 TestURLRequestContext context(true);
4742 context.set_network_delegate(NULL);
4743 context.set_net_log(&net_log_);
4744 context.Init();
4747 scoped_ptr<URLRequest> r(context.CreateRequest(
4748 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4749 &request_delegate));
4750 LoadStateWithParam load_state = r->GetLoadState();
4751 r->Start();
4752 base::RunLoop().Run();
4754 EXPECT_EQ(200, r->GetResponseCode());
4755 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4758 CapturingNetLog::CapturedEntryList entries;
4759 net_log_.GetEntries(&entries);
4761 // Delegate info should only have been logged in OnReceivedRedirect and
4762 // OnResponseStarted.
4763 size_t log_position = 0;
4764 for (int i = 0; i < 2; ++i) {
4765 if (i == 0) {
4766 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4767 entries, log_position) + 1;
4770 log_position = ExpectLogContainsSomewhereAfter(
4771 entries,
4772 log_position,
4773 NetLog::TYPE_URL_REQUEST_DELEGATE,
4774 NetLog::PHASE_BEGIN);
4776 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4777 log_position + 1);
4779 ASSERT_LT(log_position, entries.size());
4780 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4781 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4784 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4785 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4786 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4787 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4790 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4791 // an HTTP redirect, with cancellation at various points.
4792 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4793 ASSERT_TRUE(test_server_.Start());
4795 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4796 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4797 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4798 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4801 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4802 ++test_case) {
4803 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4804 TestURLRequestContext context(true);
4805 CapturingNetLog net_log;
4806 context.set_network_delegate(NULL);
4807 context.set_net_log(&net_log);
4808 context.Init();
4811 scoped_ptr<URLRequest> r(context.CreateRequest(
4812 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4813 &request_delegate));
4814 LoadStateWithParam load_state = r->GetLoadState();
4815 r->Start();
4816 base::RunLoop().Run();
4817 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4820 CapturingNetLog::CapturedEntryList entries;
4821 net_log.GetEntries(&entries);
4823 // Delegate info is always logged in both OnReceivedRedirect and
4824 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4825 // OnResponseStarted delegate call is after cancellation, but logging is
4826 // still currently supported in that call.
4827 size_t log_position = 0;
4828 for (int i = 0; i < 2; ++i) {
4829 if (i == 0) {
4830 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4831 entries, log_position) + 1;
4834 log_position = ExpectLogContainsSomewhereAfter(
4835 entries,
4836 log_position,
4837 NetLog::TYPE_URL_REQUEST_DELEGATE,
4838 NetLog::PHASE_BEGIN);
4840 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4841 log_position + 1);
4843 ASSERT_LT(log_position, entries.size());
4844 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4845 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4848 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4849 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4850 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4851 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4855 namespace {
4857 const char kExtraHeader[] = "Allow-Snafu";
4858 const char kExtraValue[] = "fubar";
4860 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
4861 void OnReceivedRedirect(URLRequest* request,
4862 const RedirectInfo& redirect_info,
4863 bool* defer_redirect) override {
4864 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
4865 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4869 } // namespace
4871 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4872 ASSERT_TRUE(test_server_.Start());
4874 GURL destination_url = test_server_.GetURL(
4875 "echoheader?" + std::string(kExtraHeader));
4876 GURL original_url = test_server_.GetURL(
4877 "server-redirect?" + destination_url.spec());
4878 RedirectWithAdditionalHeadersDelegate d;
4879 scoped_ptr<URLRequest> req(
4880 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
4881 req->Start();
4882 base::RunLoop().Run();
4884 std::string value;
4885 const HttpRequestHeaders& headers = req->extra_request_headers();
4886 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4887 EXPECT_EQ(kExtraValue, value);
4888 EXPECT_FALSE(req->is_pending());
4889 EXPECT_FALSE(req->is_redirecting());
4890 EXPECT_EQ(kExtraValue, d.data_received());
4893 namespace {
4895 const char kExtraHeaderToRemove[] = "To-Be-Removed";
4897 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
4898 void OnReceivedRedirect(URLRequest* request,
4899 const RedirectInfo& redirect_info,
4900 bool* defer_redirect) override {
4901 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
4902 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4906 } // namespace
4908 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4909 ASSERT_TRUE(test_server_.Start());
4911 GURL destination_url = test_server_.GetURL(
4912 "echoheader?" + std::string(kExtraHeaderToRemove));
4913 GURL original_url = test_server_.GetURL(
4914 "server-redirect?" + destination_url.spec());
4915 RedirectWithHeaderRemovalDelegate d;
4916 scoped_ptr<URLRequest> req(
4917 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
4918 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4919 req->Start();
4920 base::RunLoop().Run();
4922 std::string value;
4923 const HttpRequestHeaders& headers = req->extra_request_headers();
4924 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4925 EXPECT_FALSE(req->is_pending());
4926 EXPECT_FALSE(req->is_redirecting());
4927 EXPECT_EQ("None", d.data_received());
4930 TEST_F(URLRequestTestHTTP, CancelTest) {
4931 TestDelegate d;
4933 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4934 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
4936 r->Start();
4937 EXPECT_TRUE(r->is_pending());
4939 r->Cancel();
4941 base::RunLoop().Run();
4943 // We expect to receive OnResponseStarted even though the request has been
4944 // cancelled.
4945 EXPECT_EQ(1, d.response_started_count());
4946 EXPECT_EQ(0, d.bytes_received());
4947 EXPECT_FALSE(d.received_data_before_response());
4951 TEST_F(URLRequestTestHTTP, CancelTest2) {
4952 ASSERT_TRUE(test_server_.Start());
4954 TestDelegate d;
4956 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4957 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
4959 d.set_cancel_in_response_started(true);
4961 r->Start();
4962 EXPECT_TRUE(r->is_pending());
4964 base::RunLoop().Run();
4966 EXPECT_EQ(1, d.response_started_count());
4967 EXPECT_EQ(0, d.bytes_received());
4968 EXPECT_FALSE(d.received_data_before_response());
4969 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4973 TEST_F(URLRequestTestHTTP, CancelTest3) {
4974 ASSERT_TRUE(test_server_.Start());
4976 TestDelegate d;
4978 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4979 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
4981 d.set_cancel_in_received_data(true);
4983 r->Start();
4984 EXPECT_TRUE(r->is_pending());
4986 base::RunLoop().Run();
4988 EXPECT_EQ(1, d.response_started_count());
4989 // There is no guarantee about how much data was received
4990 // before the cancel was issued. It could have been 0 bytes,
4991 // or it could have been all the bytes.
4992 // EXPECT_EQ(0, d.bytes_received());
4993 EXPECT_FALSE(d.received_data_before_response());
4994 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4998 TEST_F(URLRequestTestHTTP, CancelTest4) {
4999 ASSERT_TRUE(test_server_.Start());
5001 TestDelegate d;
5003 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5004 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
5006 r->Start();
5007 EXPECT_TRUE(r->is_pending());
5009 // The request will be implicitly canceled when it is destroyed. The
5010 // test delegate must not post a quit message when this happens because
5011 // this test doesn't actually have a message loop. The quit message would
5012 // get put on this thread's message queue and the next test would exit
5013 // early, causing problems.
5014 d.set_quit_on_complete(false);
5016 // expect things to just cleanup properly.
5018 // we won't actually get a received reponse here because we've never run the
5019 // message loop
5020 EXPECT_FALSE(d.received_data_before_response());
5021 EXPECT_EQ(0, d.bytes_received());
5024 TEST_F(URLRequestTestHTTP, CancelTest5) {
5025 ASSERT_TRUE(test_server_.Start());
5027 // populate cache
5029 TestDelegate d;
5030 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5031 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
5032 r->Start();
5033 base::RunLoop().Run();
5034 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5037 // cancel read from cache (see bug 990242)
5039 TestDelegate d;
5040 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5041 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
5042 r->Start();
5043 r->Cancel();
5044 base::RunLoop().Run();
5046 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
5047 EXPECT_EQ(1, d.response_started_count());
5048 EXPECT_EQ(0, d.bytes_received());
5049 EXPECT_FALSE(d.received_data_before_response());
5053 TEST_F(URLRequestTestHTTP, PostTest) {
5054 ASSERT_TRUE(test_server_.Start());
5055 HTTPUploadDataOperationTest("POST");
5058 TEST_F(URLRequestTestHTTP, PutTest) {
5059 ASSERT_TRUE(test_server_.Start());
5060 HTTPUploadDataOperationTest("PUT");
5063 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5064 ASSERT_TRUE(test_server_.Start());
5066 TestDelegate d;
5068 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5069 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
5070 r->set_method("POST");
5072 r->Start();
5073 EXPECT_TRUE(r->is_pending());
5075 base::RunLoop().Run();
5077 ASSERT_EQ(1, d.response_started_count())
5078 << "request failed: " << r->status().status()
5079 << ", error: " << r->status().error();
5081 EXPECT_FALSE(d.received_data_before_response());
5082 EXPECT_TRUE(d.data_received().empty());
5086 TEST_F(URLRequestTestHTTP, PostFileTest) {
5087 ASSERT_TRUE(test_server_.Start());
5089 TestDelegate d;
5091 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5092 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
5093 r->set_method("POST");
5095 base::FilePath dir;
5096 PathService::Get(base::DIR_EXE, &dir);
5097 base::SetCurrentDirectory(dir);
5099 ScopedVector<UploadElementReader> element_readers;
5101 base::FilePath path;
5102 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5103 path = path.Append(FILE_PATH_LITERAL("net"));
5104 path = path.Append(FILE_PATH_LITERAL("data"));
5105 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5106 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5107 element_readers.push_back(
5108 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5109 path,
5111 kuint64max,
5112 base::Time()));
5113 r->set_upload(make_scoped_ptr<UploadDataStream>(
5114 new ElementsUploadDataStream(element_readers.Pass(), 0)));
5116 r->Start();
5117 EXPECT_TRUE(r->is_pending());
5119 base::RunLoop().Run();
5121 int64 size64 = 0;
5122 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5123 ASSERT_LE(size64, std::numeric_limits<int>::max());
5124 int size = static_cast<int>(size64);
5125 scoped_ptr<char[]> buf(new char[size]);
5127 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
5129 ASSERT_EQ(1, d.response_started_count())
5130 << "request failed: " << r->status().status()
5131 << ", error: " << r->status().error();
5133 EXPECT_FALSE(d.received_data_before_response());
5135 EXPECT_EQ(size, d.bytes_received());
5136 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
5140 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5141 ASSERT_TRUE(test_server_.Start());
5143 TestDelegate d;
5145 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5146 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
5147 r->set_method("POST");
5149 ScopedVector<UploadElementReader> element_readers;
5151 element_readers.push_back(new UploadFileElementReader(
5152 base::MessageLoopProxy::current().get(),
5153 base::FilePath(FILE_PATH_LITERAL(
5154 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5156 kuint64max,
5157 base::Time()));
5158 r->set_upload(make_scoped_ptr<UploadDataStream>(
5159 new ElementsUploadDataStream(element_readers.Pass(), 0)));
5161 r->Start();
5162 EXPECT_TRUE(r->is_pending());
5164 base::RunLoop().Run();
5166 EXPECT_TRUE(d.request_failed());
5167 EXPECT_FALSE(d.received_data_before_response());
5168 EXPECT_EQ(0, d.bytes_received());
5169 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5170 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
5174 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5175 ASSERT_TRUE(test_server_.Start());
5177 TestDelegate d;
5179 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5180 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
5181 r->EnableChunkedUpload();
5182 r->set_method("POST");
5183 AddChunksToUpload(r.get());
5184 r->Start();
5185 EXPECT_TRUE(r->is_pending());
5187 base::RunLoop().Run();
5189 VerifyReceivedDataMatchesChunks(r.get(), &d);
5193 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5194 ASSERT_TRUE(test_server_.Start());
5196 TestDelegate d;
5198 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5199 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
5200 r->EnableChunkedUpload();
5201 r->set_method("POST");
5202 r->Start();
5203 EXPECT_TRUE(r->is_pending());
5204 AddChunksToUpload(r.get());
5205 base::RunLoop().Run();
5207 VerifyReceivedDataMatchesChunks(r.get(), &d);
5211 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5212 ASSERT_TRUE(test_server_.Start());
5214 TestDelegate d;
5216 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5217 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
5218 r->EnableChunkedUpload();
5219 r->set_method("POST");
5220 r->Start();
5221 EXPECT_TRUE(r->is_pending());
5223 base::RunLoop().RunUntilIdle();
5224 AddChunksToUpload(r.get());
5225 base::RunLoop().Run();
5227 VerifyReceivedDataMatchesChunks(r.get(), &d);
5231 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5232 ASSERT_TRUE(test_server_.Start());
5234 TestDelegate d;
5235 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5236 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
5237 req->Start();
5238 base::RunLoop().Run();
5240 const HttpResponseHeaders* headers = req->response_headers();
5242 // Simple sanity check that response_info() accesses the same data.
5243 EXPECT_EQ(headers, req->response_info().headers.get());
5245 std::string header;
5246 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5247 EXPECT_EQ("private", header);
5249 header.clear();
5250 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5251 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5253 // The response has two "X-Multiple-Entries" headers.
5254 // This verfies our output has them concatenated together.
5255 header.clear();
5256 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5257 EXPECT_EQ("a, b", header);
5260 TEST_F(URLRequestTestHTTP, ProcessSTS) {
5261 SpawnedTestServer::SSLOptions ssl_options;
5262 SpawnedTestServer https_test_server(
5263 SpawnedTestServer::TYPE_HTTPS,
5264 ssl_options,
5265 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5266 ASSERT_TRUE(https_test_server.Start());
5268 TestDelegate d;
5269 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5270 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5271 &d));
5272 request->Start();
5273 base::RunLoop().Run();
5275 TransportSecurityState* security_state =
5276 default_context_.transport_security_state();
5277 TransportSecurityState::DomainState domain_state;
5278 EXPECT_TRUE(security_state->GetDynamicDomainState(
5279 SpawnedTestServer::kLocalhost, &domain_state));
5280 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5281 domain_state.sts.upgrade_mode);
5282 EXPECT_TRUE(domain_state.sts.include_subdomains);
5283 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5284 #if defined(OS_ANDROID)
5285 // Android's CertVerifyProc does not (yet) handle pins.
5286 #else
5287 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5288 #endif
5291 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5292 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5293 // DomainState present because header rejected).
5294 #if defined(OS_ANDROID)
5295 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5296 #else
5297 #define MAYBE_ProcessPKP ProcessPKP
5298 #endif
5300 // Tests that enabling HPKP on a domain does not affect the HSTS
5301 // validity/expiration.
5302 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5303 SpawnedTestServer::SSLOptions ssl_options;
5304 SpawnedTestServer https_test_server(
5305 SpawnedTestServer::TYPE_HTTPS,
5306 ssl_options,
5307 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5308 ASSERT_TRUE(https_test_server.Start());
5310 TestDelegate d;
5311 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5312 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5313 &d));
5314 request->Start();
5315 base::RunLoop().Run();
5317 TransportSecurityState* security_state =
5318 default_context_.transport_security_state();
5319 TransportSecurityState::DomainState domain_state;
5320 EXPECT_TRUE(security_state->GetDynamicDomainState(
5321 SpawnedTestServer::kLocalhost, &domain_state));
5322 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5323 domain_state.sts.upgrade_mode);
5324 EXPECT_FALSE(domain_state.sts.include_subdomains);
5325 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5326 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5327 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5330 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5331 SpawnedTestServer::SSLOptions ssl_options;
5332 SpawnedTestServer https_test_server(
5333 SpawnedTestServer::TYPE_HTTPS,
5334 ssl_options,
5335 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5336 ASSERT_TRUE(https_test_server.Start());
5338 TestDelegate d;
5339 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5340 https_test_server.GetURL("files/hsts-multiple-headers.html"),
5341 DEFAULT_PRIORITY, &d));
5342 request->Start();
5343 base::RunLoop().Run();
5345 // We should have set parameters from the first header, not the second.
5346 TransportSecurityState* security_state =
5347 default_context_.transport_security_state();
5348 TransportSecurityState::DomainState domain_state;
5349 EXPECT_TRUE(security_state->GetDynamicDomainState(
5350 SpawnedTestServer::kLocalhost, &domain_state));
5351 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5352 domain_state.sts.upgrade_mode);
5353 EXPECT_FALSE(domain_state.sts.include_subdomains);
5354 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5357 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5358 SpawnedTestServer::SSLOptions ssl_options;
5359 SpawnedTestServer https_test_server(
5360 SpawnedTestServer::TYPE_HTTPS,
5361 ssl_options,
5362 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5363 ASSERT_TRUE(https_test_server.Start());
5365 TestDelegate d;
5366 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5367 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5368 DEFAULT_PRIORITY, &d));
5369 request->Start();
5370 base::RunLoop().Run();
5372 // We should have set parameters from the first header, not the second.
5373 TransportSecurityState* security_state =
5374 default_context_.transport_security_state();
5375 TransportSecurityState::DomainState domain_state;
5376 EXPECT_TRUE(security_state->GetDynamicDomainState(
5377 SpawnedTestServer::kLocalhost, &domain_state));
5378 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5379 domain_state.sts.upgrade_mode);
5380 #if defined(OS_ANDROID)
5381 // Android's CertVerifyProc does not (yet) handle pins.
5382 #else
5383 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5384 #endif
5385 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5387 // Even though there is an HSTS header asserting includeSubdomains, it is
5388 // the *second* such header, and we MUST process only the first.
5389 EXPECT_FALSE(domain_state.sts.include_subdomains);
5390 // includeSubdomains does not occur in the test HPKP header.
5391 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5394 // Tests that when multiple HPKP headers are present, asserting different
5395 // policies, that only the first such policy is processed.
5396 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5397 SpawnedTestServer::SSLOptions ssl_options;
5398 SpawnedTestServer https_test_server(
5399 SpawnedTestServer::TYPE_HTTPS,
5400 ssl_options,
5401 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5402 ASSERT_TRUE(https_test_server.Start());
5404 TestDelegate d;
5405 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5406 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5407 DEFAULT_PRIORITY, &d));
5408 request->Start();
5409 base::RunLoop().Run();
5411 TransportSecurityState* security_state =
5412 default_context_.transport_security_state();
5413 TransportSecurityState::DomainState domain_state;
5414 EXPECT_TRUE(security_state->GetDynamicDomainState(
5415 SpawnedTestServer::kLocalhost, &domain_state));
5416 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5417 domain_state.sts.upgrade_mode);
5418 #if defined(OS_ANDROID)
5419 // Android's CertVerifyProc does not (yet) handle pins.
5420 #else
5421 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5422 #endif
5423 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5425 EXPECT_TRUE(domain_state.sts.include_subdomains);
5426 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5429 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5430 ASSERT_TRUE(test_server_.Start());
5432 TestDelegate d;
5433 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5434 test_server_.GetURL("files/content-type-normalization.html"),
5435 DEFAULT_PRIORITY, &d));
5436 req->Start();
5437 base::RunLoop().Run();
5439 std::string mime_type;
5440 req->GetMimeType(&mime_type);
5441 EXPECT_EQ("text/html", mime_type);
5443 std::string charset;
5444 req->GetCharset(&charset);
5445 EXPECT_EQ("utf-8", charset);
5446 req->Cancel();
5449 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
5450 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5451 GURL data_url("data:,foo");
5452 DataProtocolHandler data_protocol_handler;
5453 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5455 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5456 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
5459 #if !defined(DISABLE_FILE_SUPPORT)
5460 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5461 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5462 GURL file_url("file:///foo.txt");
5463 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5464 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5466 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5467 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
5470 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5471 ASSERT_TRUE(test_server_.Start());
5473 TestDelegate d;
5474 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5475 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5476 &d));
5477 req->Start();
5478 base::RunLoop().Run();
5480 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5481 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5483 #endif // !defined(DISABLE_FILE_SUPPORT)
5485 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5486 ASSERT_TRUE(test_server_.Start());
5488 TestDelegate d;
5489 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5490 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5491 &d));
5492 req->Start();
5493 base::MessageLoop::current()->Run();
5495 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5496 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5499 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5500 ASSERT_TRUE(test_server_.Start());
5502 TestDelegate d;
5503 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5504 test_server_.GetURL("files/redirect-to-invalid-url.html"),
5505 DEFAULT_PRIORITY, &d));
5506 req->Start();
5507 base::RunLoop().Run();
5509 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5510 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
5513 // Make sure redirects are cached, despite not reading their bodies.
5514 TEST_F(URLRequestTestHTTP, CacheRedirect) {
5515 ASSERT_TRUE(test_server_.Start());
5516 GURL redirect_url =
5517 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5520 TestDelegate d;
5521 scoped_ptr<URLRequest> req(
5522 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
5523 req->Start();
5524 base::RunLoop().Run();
5525 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5526 EXPECT_EQ(1, d.received_redirect_count());
5527 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5531 TestDelegate d;
5532 d.set_quit_on_redirect(true);
5533 scoped_ptr<URLRequest> req(
5534 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
5535 req->Start();
5536 base::RunLoop().Run();
5538 EXPECT_EQ(1, d.received_redirect_count());
5539 EXPECT_EQ(0, d.response_started_count());
5540 EXPECT_TRUE(req->was_cached());
5542 req->FollowDeferredRedirect();
5543 base::RunLoop().Run();
5544 EXPECT_EQ(1, d.received_redirect_count());
5545 EXPECT_EQ(1, d.response_started_count());
5546 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5547 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5551 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5552 // when the headers are read, since the body won't have been read.
5553 TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5554 ASSERT_TRUE(test_server_.Start());
5555 // URL that is normally cached.
5556 GURL initial_url = test_server_.GetURL("cachetime");
5559 // Set up the TestNetworkDelegate tp force a redirect.
5560 GURL redirect_to_url = test_server_.GetURL("echo");
5561 default_network_delegate_.set_redirect_on_headers_received_url(
5562 redirect_to_url);
5564 TestDelegate d;
5565 scoped_ptr<URLRequest> req(
5566 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
5567 req->Start();
5568 base::RunLoop().Run();
5569 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5570 EXPECT_EQ(1, d.received_redirect_count());
5571 EXPECT_EQ(redirect_to_url, req->url());
5575 TestDelegate d;
5576 scoped_ptr<URLRequest> req(
5577 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
5578 req->Start();
5579 base::RunLoop().Run();
5581 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5582 EXPECT_FALSE(req->was_cached());
5583 EXPECT_EQ(0, d.received_redirect_count());
5584 EXPECT_EQ(initial_url, req->url());
5588 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5589 // safe.
5590 TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5591 ASSERT_TRUE(test_server_.Start());
5593 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5594 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5595 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5597 TestDelegate d;
5599 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5600 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
5602 r->Start();
5603 base::RunLoop().Run();
5605 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5607 EXPECT_EQ(2U, r->url_chain().size());
5608 EXPECT_EQ(OK, r->status().error());
5609 EXPECT_EQ(unsafe_url, r->url());
5610 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5614 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5615 // some other URL to the whitelist.
5616 TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5617 ASSERT_TRUE(test_server_.Start());
5619 GURL unsafe_url("data:text/html,something");
5620 GURL different_unsafe_url("data:text/html,something-else");
5621 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5622 default_network_delegate_.set_allowed_unsafe_redirect_url(
5623 different_unsafe_url);
5625 TestDelegate d;
5627 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5628 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
5630 r->Start();
5631 base::RunLoop().Run();
5633 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5634 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
5638 // Redirects from an URL with fragment to an unsafe URL with fragment should
5639 // be allowed, and the reference fragment of the target URL should be preserved.
5640 TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5641 ASSERT_TRUE(test_server_.Start());
5643 GURL original_url(test_server_.GetURL("original#fragment1"));
5644 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5645 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5647 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5648 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5650 TestDelegate d;
5652 scoped_ptr<URLRequest> r(
5653 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
5655 r->Start();
5656 base::RunLoop().Run();
5658 EXPECT_EQ(2U, r->url_chain().size());
5659 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5660 EXPECT_EQ(OK, r->status().error());
5661 EXPECT_EQ(original_url, r->original_url());
5662 EXPECT_EQ(expected_url, r->url());
5666 // When a delegate has specified a safe redirect URL, but it does not match the
5667 // redirect target, then do not prevent the reference fragment from being added.
5668 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
5669 ASSERT_TRUE(test_server_.Start());
5671 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5672 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5673 GURL redirect_url(test_server_.GetURL("target"));
5674 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5676 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5677 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5679 TestDelegate d;
5681 scoped_ptr<URLRequest> r(
5682 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
5684 r->Start();
5685 base::RunLoop().Run();
5687 EXPECT_EQ(2U, r->url_chain().size());
5688 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5689 EXPECT_EQ(OK, r->status().error());
5690 EXPECT_EQ(original_url, r->original_url());
5691 EXPECT_EQ(expected_redirect_url, r->url());
5695 // When a delegate has specified a safe redirect URL, assume that the redirect
5696 // URL should not be changed. In particular, the reference fragment should not
5697 // be modified.
5698 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5699 ASSERT_TRUE(test_server_.Start());
5701 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5702 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5704 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5705 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5707 TestDelegate d;
5709 scoped_ptr<URLRequest> r(
5710 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
5712 r->Start();
5713 base::RunLoop().Run();
5715 EXPECT_EQ(2U, r->url_chain().size());
5716 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5717 EXPECT_EQ(OK, r->status().error());
5718 EXPECT_EQ(original_url, r->original_url());
5719 EXPECT_EQ(redirect_url, r->url());
5723 // When a URLRequestRedirectJob is created, the redirection must be followed and
5724 // the reference fragment of the target URL must not be modified.
5725 TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5726 ASSERT_TRUE(test_server_.Start());
5728 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5729 GURL redirect_url(test_server_.GetURL("echo"));
5731 TestDelegate d;
5732 scoped_ptr<URLRequest> r(
5733 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
5735 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5736 r.get(), &default_network_delegate_, redirect_url,
5737 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5738 AddTestInterceptor()->set_main_intercept_job(job);
5740 r->Start();
5741 base::RunLoop().Run();
5743 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5744 EXPECT_EQ(OK, r->status().error());
5745 EXPECT_EQ(original_url, r->original_url());
5746 EXPECT_EQ(redirect_url, r->url());
5749 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5750 ASSERT_TRUE(test_server_.Start());
5752 TestDelegate d;
5753 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5754 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
5755 req->SetReferrer("http://user:pass@foo.com/");
5756 req->Start();
5757 base::RunLoop().Run();
5759 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5762 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5763 ASSERT_TRUE(test_server_.Start());
5765 TestDelegate d;
5766 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5767 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
5768 req->SetReferrer("http://foo.com/test#fragment");
5769 req->Start();
5770 base::RunLoop().Run();
5772 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5775 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5776 ASSERT_TRUE(test_server_.Start());
5778 TestDelegate d;
5779 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5780 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
5781 req->SetReferrer("http://foo.com/test#fragment");
5782 req->SetReferrer("");
5783 req->Start();
5784 base::RunLoop().Run();
5786 EXPECT_EQ(std::string("None"), d.data_received());
5789 // Defer network start and then resume, checking that the request was a success
5790 // and bytes were received.
5791 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5792 ASSERT_TRUE(test_server_.Start());
5794 TestDelegate d;
5796 d.set_quit_on_network_start(true);
5797 GURL test_url(test_server_.GetURL("echo"));
5798 scoped_ptr<URLRequest> req(
5799 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
5801 req->Start();
5802 base::RunLoop().Run();
5804 EXPECT_EQ(1, d.received_before_network_start_count());
5805 EXPECT_EQ(0, d.response_started_count());
5807 req->ResumeNetworkStart();
5808 base::RunLoop().Run();
5810 EXPECT_EQ(1, d.response_started_count());
5811 EXPECT_NE(0, d.bytes_received());
5812 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5816 // Check that OnBeforeNetworkStart is only called once even if there is a
5817 // redirect.
5818 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5819 ASSERT_TRUE(test_server_.Start());
5821 TestDelegate d;
5823 d.set_quit_on_redirect(true);
5824 d.set_quit_on_network_start(true);
5825 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5826 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
5828 req->Start();
5829 base::RunLoop().Run();
5831 EXPECT_EQ(1, d.received_before_network_start_count());
5832 EXPECT_EQ(0, d.response_started_count());
5833 EXPECT_EQ(0, d.received_redirect_count());
5835 req->ResumeNetworkStart();
5836 base::RunLoop().Run();
5838 EXPECT_EQ(1, d.received_redirect_count());
5839 req->FollowDeferredRedirect();
5840 base::RunLoop().Run();
5842 // Check that the redirect's new network transaction does not get propagated
5843 // to a second OnBeforeNetworkStart() notification.
5844 EXPECT_EQ(1, d.received_before_network_start_count());
5846 EXPECT_EQ(1, d.response_started_count());
5847 EXPECT_NE(0, d.bytes_received());
5848 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5852 // Cancel the request after learning that the request would use the network.
5853 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5854 ASSERT_TRUE(test_server_.Start());
5856 TestDelegate d;
5858 d.set_quit_on_network_start(true);
5859 GURL test_url(test_server_.GetURL("echo"));
5860 scoped_ptr<URLRequest> req(
5861 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
5863 req->Start();
5864 base::RunLoop().Run();
5866 EXPECT_EQ(1, d.received_before_network_start_count());
5867 EXPECT_EQ(0, d.response_started_count());
5869 req->Cancel();
5870 base::RunLoop().Run();
5872 EXPECT_EQ(1, d.response_started_count());
5873 EXPECT_EQ(0, d.bytes_received());
5874 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
5878 TEST_F(URLRequestTestHTTP, CancelRedirect) {
5879 ASSERT_TRUE(test_server_.Start());
5881 TestDelegate d;
5883 d.set_cancel_in_received_redirect(true);
5884 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5885 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
5886 req->Start();
5887 base::RunLoop().Run();
5889 EXPECT_EQ(1, d.response_started_count());
5890 EXPECT_EQ(0, d.bytes_received());
5891 EXPECT_FALSE(d.received_data_before_response());
5892 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
5896 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5897 ASSERT_TRUE(test_server_.Start());
5899 TestDelegate d;
5901 d.set_quit_on_redirect(true);
5902 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5903 scoped_ptr<URLRequest> req(
5904 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
5906 req->Start();
5907 base::RunLoop().Run();
5909 EXPECT_EQ(1, d.received_redirect_count());
5911 req->FollowDeferredRedirect();
5912 base::RunLoop().Run();
5914 EXPECT_EQ(1, d.response_started_count());
5915 EXPECT_FALSE(d.received_data_before_response());
5916 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5918 base::FilePath path;
5919 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5920 path = path.Append(FILE_PATH_LITERAL("net"));
5921 path = path.Append(FILE_PATH_LITERAL("data"));
5922 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5923 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5925 std::string contents;
5926 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5927 EXPECT_EQ(contents, d.data_received());
5931 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5932 ASSERT_TRUE(test_server_.Start());
5934 TestDelegate d;
5936 d.set_quit_on_redirect(true);
5937 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5938 scoped_ptr<URLRequest> req(
5939 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
5941 EXPECT_FALSE(d.have_full_request_headers());
5943 req->Start();
5944 base::RunLoop().Run();
5946 EXPECT_EQ(1, d.received_redirect_count());
5947 EXPECT_TRUE(d.have_full_request_headers());
5948 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5949 d.ClearFullRequestHeaders();
5951 req->FollowDeferredRedirect();
5952 base::RunLoop().Run();
5954 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5955 EXPECT_EQ(1, d.response_started_count());
5956 EXPECT_TRUE(d.have_full_request_headers());
5957 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5958 EXPECT_FALSE(d.received_data_before_response());
5959 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5961 base::FilePath path;
5962 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5963 path = path.Append(FILE_PATH_LITERAL("net"));
5964 path = path.Append(FILE_PATH_LITERAL("data"));
5965 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5966 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5968 std::string contents;
5969 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5970 EXPECT_EQ(contents, d.data_received());
5974 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5975 ASSERT_TRUE(test_server_.Start());
5977 TestDelegate d;
5979 d.set_quit_on_redirect(true);
5980 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5981 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
5982 req->Start();
5983 base::RunLoop().Run();
5985 EXPECT_EQ(1, d.received_redirect_count());
5987 req->Cancel();
5988 base::RunLoop().Run();
5990 EXPECT_EQ(1, d.response_started_count());
5991 EXPECT_EQ(0, d.bytes_received());
5992 EXPECT_FALSE(d.received_data_before_response());
5993 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
5997 TEST_F(URLRequestTestHTTP, VaryHeader) {
5998 ASSERT_TRUE(test_server_.Start());
6000 // Populate the cache.
6002 TestDelegate d;
6003 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6004 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
6005 HttpRequestHeaders headers;
6006 headers.SetHeader("foo", "1");
6007 req->SetExtraRequestHeaders(headers);
6008 req->Start();
6009 base::RunLoop().Run();
6011 LoadTimingInfo load_timing_info;
6012 req->GetLoadTimingInfo(&load_timing_info);
6013 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6016 // Expect a cache hit.
6018 TestDelegate d;
6019 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6020 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
6021 HttpRequestHeaders headers;
6022 headers.SetHeader("foo", "1");
6023 req->SetExtraRequestHeaders(headers);
6024 req->Start();
6025 base::RunLoop().Run();
6027 EXPECT_TRUE(req->was_cached());
6029 LoadTimingInfo load_timing_info;
6030 req->GetLoadTimingInfo(&load_timing_info);
6031 TestLoadTimingCacheHitNoNetwork(load_timing_info);
6034 // Expect a cache miss.
6036 TestDelegate d;
6037 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6038 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
6039 HttpRequestHeaders headers;
6040 headers.SetHeader("foo", "2");
6041 req->SetExtraRequestHeaders(headers);
6042 req->Start();
6043 base::RunLoop().Run();
6045 EXPECT_FALSE(req->was_cached());
6047 LoadTimingInfo load_timing_info;
6048 req->GetLoadTimingInfo(&load_timing_info);
6049 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6053 TEST_F(URLRequestTestHTTP, BasicAuth) {
6054 ASSERT_TRUE(test_server_.Start());
6056 // populate the cache
6058 TestDelegate d;
6059 d.set_credentials(AuthCredentials(kUser, kSecret));
6061 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6062 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
6063 r->Start();
6065 base::RunLoop().Run();
6067 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6070 // repeat request with end-to-end validation. since auth-basic results in a
6071 // cachable page, we expect this test to result in a 304. in which case, the
6072 // response should be fetched from the cache.
6074 TestDelegate d;
6075 d.set_credentials(AuthCredentials(kUser, kSecret));
6077 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6078 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
6079 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6080 r->Start();
6082 base::RunLoop().Run();
6084 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6086 // Should be the same cached document.
6087 EXPECT_TRUE(r->was_cached());
6091 // Check that Set-Cookie headers in 401 responses are respected.
6092 // http://crbug.com/6450
6093 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6094 ASSERT_TRUE(test_server_.Start());
6096 GURL url_requiring_auth =
6097 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6099 // Request a page that will give a 401 containing a Set-Cookie header.
6100 // Verify that when the transaction is restarted, it includes the new cookie.
6102 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6103 TestURLRequestContext context(true);
6104 context.set_network_delegate(&network_delegate);
6105 context.Init();
6107 TestDelegate d;
6108 d.set_credentials(AuthCredentials(kUser, kSecret));
6110 scoped_ptr<URLRequest> r(
6111 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
6112 r->Start();
6114 base::RunLoop().Run();
6116 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6118 // Make sure we sent the cookie in the restarted transaction.
6119 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6120 != std::string::npos);
6123 // Same test as above, except this time the restart is initiated earlier
6124 // (without user intervention since identity is embedded in the URL).
6126 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6127 TestURLRequestContext context(true);
6128 context.set_network_delegate(&network_delegate);
6129 context.Init();
6131 TestDelegate d;
6133 GURL::Replacements replacements;
6134 replacements.SetUsernameStr("user2");
6135 replacements.SetPasswordStr("secret");
6136 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6138 scoped_ptr<URLRequest> r(
6139 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
6140 r->Start();
6142 base::RunLoop().Run();
6144 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6146 // Make sure we sent the cookie in the restarted transaction.
6147 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6148 != std::string::npos);
6152 // Tests that load timing works as expected with auth and the cache.
6153 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6154 ASSERT_TRUE(test_server_.Start());
6156 // populate the cache
6158 TestDelegate d;
6159 d.set_credentials(AuthCredentials(kUser, kSecret));
6161 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6162 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
6163 r->Start();
6165 base::RunLoop().Run();
6167 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6169 LoadTimingInfo load_timing_info_before_auth;
6170 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6171 &load_timing_info_before_auth));
6172 TestLoadTimingNotReused(load_timing_info_before_auth,
6173 CONNECT_TIMING_HAS_DNS_TIMES);
6175 LoadTimingInfo load_timing_info;
6176 r->GetLoadTimingInfo(&load_timing_info);
6177 // The test server does not support keep alive sockets, so the second
6178 // request with auth should use a new socket.
6179 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6180 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6181 load_timing_info.socket_log_id);
6182 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6183 load_timing_info.connect_timing.connect_start);
6186 // Repeat request with end-to-end validation. Since auth-basic results in a
6187 // cachable page, we expect this test to result in a 304. In which case, the
6188 // response should be fetched from the cache.
6190 TestDelegate d;
6191 d.set_credentials(AuthCredentials(kUser, kSecret));
6193 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6194 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
6195 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6196 r->Start();
6198 base::RunLoop().Run();
6200 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6202 // Should be the same cached document.
6203 EXPECT_TRUE(r->was_cached());
6205 // Since there was a request that went over the wire, the load timing
6206 // information should include connection times.
6207 LoadTimingInfo load_timing_info;
6208 r->GetLoadTimingInfo(&load_timing_info);
6209 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6213 // In this test, we do a POST which the server will 302 redirect.
6214 // The subsequent transaction should use GET, and should not send the
6215 // Content-Type header.
6216 // http://code.google.com/p/chromium/issues/detail?id=843
6217 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6218 ASSERT_TRUE(test_server_.Start());
6220 const char kData[] = "hello world";
6222 TestDelegate d;
6223 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6224 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
6225 req->set_method("POST");
6226 req->set_upload(CreateSimpleUploadData(kData));
6228 // Set headers (some of which are specific to the POST).
6229 HttpRequestHeaders headers;
6230 headers.AddHeadersFromString(
6231 "Content-Type: multipart/form-data; "
6232 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6233 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6234 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6235 "Accept-Language: en-US,en\r\n"
6236 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6237 "Content-Length: 11\r\n"
6238 "Origin: http://localhost:1337/");
6239 req->SetExtraRequestHeaders(headers);
6240 req->Start();
6241 base::RunLoop().Run();
6243 std::string mime_type;
6244 req->GetMimeType(&mime_type);
6245 EXPECT_EQ("text/html", mime_type);
6247 const std::string& data = d.data_received();
6249 // Check that the post-specific headers were stripped:
6250 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6251 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6252 EXPECT_FALSE(ContainsString(data, "Origin:"));
6254 // These extra request headers should not have been stripped.
6255 EXPECT_TRUE(ContainsString(data, "Accept:"));
6256 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6257 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6260 // The following tests check that we handle mutating the request for HTTP
6261 // redirects as expected.
6262 // See https://crbug.com/56373, https://crbug.com/102130, and
6263 // https://crbug.com/465517.
6265 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6266 ASSERT_TRUE(test_server_.Start());
6268 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
6269 const GURL https_redirect_url =
6270 test_server_.GetURL("files/redirect301-to-https");
6272 HTTPRedirectMethodTest(url, "POST", "GET", true);
6273 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6274 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6276 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6277 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6278 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6279 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6280 std::string());
6283 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6284 ASSERT_TRUE(test_server_.Start());
6286 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6287 const GURL https_redirect_url =
6288 test_server_.GetURL("files/redirect302-to-https");
6290 HTTPRedirectMethodTest(url, "POST", "GET", true);
6291 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6292 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6294 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6295 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6296 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6297 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6298 std::string());
6301 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6302 ASSERT_TRUE(test_server_.Start());
6304 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6305 const GURL https_redirect_url =
6306 test_server_.GetURL("files/redirect303-to-https");
6308 HTTPRedirectMethodTest(url, "POST", "GET", true);
6309 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6310 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6312 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6313 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6314 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6315 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6316 std::string());
6319 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6320 ASSERT_TRUE(test_server_.Start());
6322 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6323 const GURL https_redirect_url =
6324 test_server_.GetURL("files/redirect307-to-https");
6326 HTTPRedirectMethodTest(url, "POST", "POST", true);
6327 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6328 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6330 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6331 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6332 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6333 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
6336 TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6337 ASSERT_TRUE(test_server_.Start());
6339 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6340 const GURL https_redirect_url =
6341 test_server_.GetURL("files/redirect308-to-https");
6343 HTTPRedirectMethodTest(url, "POST", "POST", true);
6344 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6345 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6347 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6348 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6349 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6350 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
6353 // Make sure that 308 responses without bodies are not treated as redirects.
6354 // Certain legacy apis that pre-date the response code expect this behavior
6355 // (Like Google Drive).
6356 TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6357 ASSERT_TRUE(test_server_.Start());
6359 TestDelegate d;
6360 const GURL url = test_server_.GetURL("files/308-without-location-header");
6362 scoped_ptr<URLRequest> request(
6363 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
6365 request->Start();
6366 base::RunLoop().Run();
6367 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6368 EXPECT_EQ(OK, request->status().error());
6369 EXPECT_EQ(0, d.received_redirect_count());
6370 EXPECT_EQ(308, request->response_headers()->response_code());
6371 EXPECT_EQ("This is not a redirect.", d.data_received());
6374 TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6375 ASSERT_TRUE(test_server_.Start());
6377 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6378 GURL expected_url(test_server_.GetURL("echo#fragment"));
6380 TestDelegate d;
6382 scoped_ptr<URLRequest> r(
6383 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
6385 r->Start();
6386 base::RunLoop().Run();
6388 EXPECT_EQ(2U, r->url_chain().size());
6389 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6390 EXPECT_EQ(OK, r->status().error());
6391 EXPECT_EQ(original_url, r->original_url());
6392 EXPECT_EQ(expected_url, r->url());
6396 TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6397 ASSERT_TRUE(test_server_.Start());
6399 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6400 GURL first_party_url("http://example.com");
6402 TestDelegate d;
6404 scoped_ptr<URLRequest> r(
6405 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
6406 r->set_first_party_for_cookies(first_party_url);
6408 r->Start();
6409 base::RunLoop().Run();
6411 EXPECT_EQ(2U, r->url_chain().size());
6412 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6413 EXPECT_EQ(OK, r->status().error());
6414 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
6418 TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6419 ASSERT_TRUE(test_server_.Start());
6421 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6422 GURL original_first_party_url("http://example.com");
6423 GURL expected_first_party_url(test_server_.GetURL("echo"));
6425 TestDelegate d;
6427 scoped_ptr<URLRequest> r(
6428 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
6429 r->set_first_party_for_cookies(original_first_party_url);
6430 r->set_first_party_url_policy(
6431 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6433 r->Start();
6434 base::RunLoop().Run();
6436 EXPECT_EQ(2U, r->url_chain().size());
6437 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6438 EXPECT_EQ(OK, r->status().error());
6439 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
6443 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6444 ASSERT_TRUE(test_server_.Start());
6446 const char kData[] = "hello world";
6448 TestDelegate d;
6449 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6450 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
6451 req->set_method("POST");
6452 req->set_upload(CreateSimpleUploadData(kData));
6453 HttpRequestHeaders headers;
6454 headers.SetHeader(HttpRequestHeaders::kContentLength,
6455 base::UintToString(arraysize(kData) - 1));
6456 req->SetExtraRequestHeaders(headers);
6458 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6459 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6460 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6461 AddTestInterceptor()->set_main_intercept_job(job);
6463 req->Start();
6464 base::RunLoop().Run();
6465 EXPECT_EQ("GET", req->method());
6468 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6469 ASSERT_TRUE(test_server_.Start());
6471 const char kData[] = "hello world";
6473 TestDelegate d;
6474 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6475 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
6476 req->set_method("POST");
6477 req->set_upload(CreateSimpleUploadData(kData));
6478 HttpRequestHeaders headers;
6479 headers.SetHeader(HttpRequestHeaders::kContentLength,
6480 base::UintToString(arraysize(kData) - 1));
6481 req->SetExtraRequestHeaders(headers);
6483 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6484 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6485 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6486 "Very Good Reason");
6487 AddTestInterceptor()->set_main_intercept_job(job);
6489 req->Start();
6490 base::RunLoop().Run();
6491 EXPECT_EQ("POST", req->method());
6492 EXPECT_EQ(kData, d.data_received());
6495 // Check that default A-L header is sent.
6496 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6497 ASSERT_TRUE(test_server_.Start());
6499 StaticHttpUserAgentSettings settings("en", std::string());
6500 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6501 TestURLRequestContext context(true);
6502 context.set_network_delegate(&network_delegate);
6503 context.set_http_user_agent_settings(&settings);
6504 context.Init();
6506 TestDelegate d;
6507 scoped_ptr<URLRequest> req(context.CreateRequest(
6508 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
6509 req->Start();
6510 base::RunLoop().Run();
6511 EXPECT_EQ("en", d.data_received());
6514 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6515 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6516 ASSERT_TRUE(test_server_.Start());
6518 std::string empty_string; // Avoid most vexing parse on line below.
6519 StaticHttpUserAgentSettings settings(empty_string, empty_string);
6520 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6521 TestURLRequestContext context(true);
6522 context.set_network_delegate(&network_delegate);
6523 context.Init();
6524 // We override the language after initialization because empty entries
6525 // get overridden by Init().
6526 context.set_http_user_agent_settings(&settings);
6528 TestDelegate d;
6529 scoped_ptr<URLRequest> req(context.CreateRequest(
6530 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
6531 req->Start();
6532 base::RunLoop().Run();
6533 EXPECT_EQ("None", d.data_received());
6536 // Check that if request overrides the A-L header, the default is not appended.
6537 // See http://crbug.com/20894
6538 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6539 ASSERT_TRUE(test_server_.Start());
6541 TestDelegate d;
6542 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6543 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
6544 HttpRequestHeaders headers;
6545 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6546 req->SetExtraRequestHeaders(headers);
6547 req->Start();
6548 base::RunLoop().Run();
6549 EXPECT_EQ(std::string("ru"), d.data_received());
6552 // Check that default A-E header is sent.
6553 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6554 ASSERT_TRUE(test_server_.Start());
6556 TestDelegate d;
6557 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6558 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
6559 HttpRequestHeaders headers;
6560 req->SetExtraRequestHeaders(headers);
6561 req->Start();
6562 base::RunLoop().Run();
6563 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6566 // Check that if request overrides the A-E header, the default is not appended.
6567 // See http://crbug.com/47381
6568 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6569 ASSERT_TRUE(test_server_.Start());
6571 TestDelegate d;
6572 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6573 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
6574 HttpRequestHeaders headers;
6575 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6576 req->SetExtraRequestHeaders(headers);
6577 req->Start();
6578 base::RunLoop().Run();
6579 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6580 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6583 // Check that setting the A-C header sends the proper header.
6584 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
6585 ASSERT_TRUE(test_server_.Start());
6587 TestDelegate d;
6588 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6589 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
6590 HttpRequestHeaders headers;
6591 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6592 req->SetExtraRequestHeaders(headers);
6593 req->Start();
6594 base::RunLoop().Run();
6595 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6598 // Check that default User-Agent header is sent.
6599 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6600 ASSERT_TRUE(test_server_.Start());
6602 TestDelegate d;
6603 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6604 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
6605 req->Start();
6606 base::RunLoop().Run();
6607 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
6608 d.data_received());
6611 // Check that if request overrides the User-Agent header,
6612 // the default is not appended.
6613 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6614 ASSERT_TRUE(test_server_.Start());
6616 TestDelegate d;
6617 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6618 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
6619 HttpRequestHeaders headers;
6620 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6621 req->SetExtraRequestHeaders(headers);
6622 req->Start();
6623 base::RunLoop().Run();
6624 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
6627 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6628 // User-Agent header to be sent but does not send the Accept-Language and
6629 // Accept-Charset headers.
6630 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6631 ASSERT_TRUE(test_server_.Start());
6633 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6634 TestURLRequestContext context(true);
6635 context.set_network_delegate(&network_delegate);
6636 context.Init();
6637 // We override the HttpUserAgentSettings after initialization because empty
6638 // entries get overridden by Init().
6639 context.set_http_user_agent_settings(NULL);
6641 struct {
6642 const char* request;
6643 const char* expected_response;
6644 } tests[] = { { "echoheader?Accept-Language", "None" },
6645 { "echoheader?Accept-Charset", "None" },
6646 { "echoheader?User-Agent", "" } };
6648 for (size_t i = 0; i < arraysize(tests); i++) {
6649 TestDelegate d;
6650 scoped_ptr<URLRequest> req(context.CreateRequest(
6651 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
6652 req->Start();
6653 base::RunLoop().Run();
6654 EXPECT_EQ(tests[i].expected_response, d.data_received())
6655 << " Request = \"" << tests[i].request << "\"";
6659 // Make sure that URLRequest passes on its priority updates to
6660 // newly-created jobs after the first one.
6661 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6662 ASSERT_TRUE(test_server_.Start());
6664 TestDelegate d;
6665 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6666 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
6667 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
6669 scoped_refptr<URLRequestRedirectJob> redirect_job =
6670 new URLRequestRedirectJob(
6671 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6672 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6673 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
6675 req->SetPriority(LOW);
6676 req->Start();
6677 EXPECT_TRUE(req->is_pending());
6679 scoped_refptr<URLRequestTestJob> job =
6680 new URLRequestTestJob(req.get(), &default_network_delegate_);
6681 AddTestInterceptor()->set_main_intercept_job(job.get());
6683 // Should trigger |job| to be started.
6684 base::RunLoop().Run();
6685 EXPECT_EQ(LOW, job->priority());
6688 // Check that creating a network request while entering/exiting suspend mode
6689 // fails as it should. This is the only case where an HttpTransactionFactory
6690 // does not return an HttpTransaction.
6691 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6692 // Create a new HttpNetworkLayer that thinks it's suspended.
6693 HttpNetworkSession::Params params;
6694 params.host_resolver = default_context_.host_resolver();
6695 params.cert_verifier = default_context_.cert_verifier();
6696 params.transport_security_state = default_context_.transport_security_state();
6697 params.proxy_service = default_context_.proxy_service();
6698 params.ssl_config_service = default_context_.ssl_config_service();
6699 params.http_auth_handler_factory =
6700 default_context_.http_auth_handler_factory();
6701 params.network_delegate = &default_network_delegate_;
6702 params.http_server_properties = default_context_.http_server_properties();
6703 scoped_ptr<HttpNetworkLayer> network_layer(
6704 new HttpNetworkLayer(new HttpNetworkSession(params)));
6705 network_layer->OnSuspend();
6707 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6708 HttpCache::DefaultBackend::InMemory(0));
6710 TestURLRequestContext context(true);
6711 context.set_http_transaction_factory(&http_cache);
6712 context.Init();
6714 TestDelegate d;
6715 scoped_ptr<URLRequest> req(
6716 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
6717 req->Start();
6718 base::RunLoop().Run();
6720 EXPECT_TRUE(d.request_failed());
6721 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6722 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
6725 // Check that creating a network request while entering/exiting suspend mode
6726 // fails as it should in the case there is no cache. This is the only case
6727 // where an HttpTransactionFactory does not return an HttpTransaction.
6728 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6729 // Create a new HttpNetworkLayer that thinks it's suspended.
6730 HttpNetworkSession::Params params;
6731 params.host_resolver = default_context_.host_resolver();
6732 params.cert_verifier = default_context_.cert_verifier();
6733 params.transport_security_state = default_context_.transport_security_state();
6734 params.proxy_service = default_context_.proxy_service();
6735 params.ssl_config_service = default_context_.ssl_config_service();
6736 params.http_auth_handler_factory =
6737 default_context_.http_auth_handler_factory();
6738 params.network_delegate = &default_network_delegate_;
6739 params.http_server_properties = default_context_.http_server_properties();
6740 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6741 network_layer.OnSuspend();
6743 TestURLRequestContext context(true);
6744 context.set_http_transaction_factory(&network_layer);
6745 context.Init();
6747 TestDelegate d;
6748 scoped_ptr<URLRequest> req(
6749 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
6750 req->Start();
6751 base::RunLoop().Run();
6753 EXPECT_TRUE(d.request_failed());
6754 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6755 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
6758 class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6759 public:
6760 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6761 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6762 // tests into the factory tests.
6763 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6766 void SetUpFactory() override {
6767 interceptor_ = new MockURLRequestInterceptor();
6768 job_factory_.reset(new URLRequestInterceptingJobFactory(
6769 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6772 MockURLRequestInterceptor* interceptor() const {
6773 return interceptor_;
6776 private:
6777 MockURLRequestInterceptor* interceptor_;
6780 TEST_F(URLRequestInterceptorTestHTTP,
6781 NetworkDelegateNotificationOnRedirectIntercept) {
6782 interceptor()->set_intercept_redirect(true);
6783 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6784 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6786 ASSERT_TRUE(test_server()->Start());
6788 TestDelegate d;
6789 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6790 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
6791 req->Start();
6792 base::RunLoop().Run();
6794 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6795 // Check we got one good response
6796 EXPECT_TRUE(req->status().is_success());
6797 if (req->status().is_success())
6798 EXPECT_EQ(200, req->response_headers()->response_code());
6800 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6801 EXPECT_EQ(1, d.response_started_count());
6802 EXPECT_EQ(0, d.received_redirect_count());
6804 EXPECT_EQ(1, default_network_delegate()->created_requests());
6805 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6806 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6809 TEST_F(URLRequestInterceptorTestHTTP,
6810 NetworkDelegateNotificationOnErrorIntercept) {
6811 // Intercept that error and respond with an OK response.
6812 interceptor()->set_intercept_final_response(true);
6813 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6814 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6815 default_network_delegate()->set_can_be_intercepted_on_error(true);
6817 ASSERT_TRUE(test_server()->Start());
6819 TestDelegate d;
6820 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6821 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
6822 &d));
6823 req->set_method("GET");
6824 req->Start();
6825 base::RunLoop().Run();
6827 EXPECT_TRUE(interceptor()->did_intercept_final());
6829 // Check we received one good response.
6830 EXPECT_TRUE(req->status().is_success());
6831 if (req->status().is_success())
6832 EXPECT_EQ(200, req->response_headers()->response_code());
6833 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6834 EXPECT_EQ(1, d.response_started_count());
6835 EXPECT_EQ(0, d.received_redirect_count());
6837 EXPECT_EQ(1, default_network_delegate()->created_requests());
6838 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6839 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
6842 TEST_F(URLRequestInterceptorTestHTTP,
6843 NetworkDelegateNotificationOnResponseIntercept) {
6844 // Intercept that error and respond with an OK response.
6845 interceptor()->set_intercept_final_response(true);
6847 // Intercept with a real URLRequestHttpJob.
6848 interceptor()->set_use_url_request_http_job(true);
6850 ASSERT_TRUE(test_server()->Start());
6852 TestDelegate d;
6853 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6854 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
6855 req->set_method("GET");
6856 req->Start();
6857 base::RunLoop().Run();
6859 EXPECT_TRUE(interceptor()->did_intercept_final());
6861 // Check we received one good response.
6862 EXPECT_TRUE(req->status().is_success());
6863 if (req->status().is_success())
6864 EXPECT_EQ(200, req->response_headers()->response_code());
6865 EXPECT_EQ("hello", d.data_received());
6866 EXPECT_EQ(1, d.response_started_count());
6867 EXPECT_EQ(0, d.received_redirect_count());
6869 EXPECT_EQ(1, default_network_delegate()->created_requests());
6870 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
6871 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
6874 class URLRequestTestReferrerPolicy : public URLRequestTest {
6875 public:
6876 URLRequestTestReferrerPolicy() {}
6878 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
6879 origin_server_.reset(new SpawnedTestServer(
6880 origin_type, SpawnedTestServer::kLocalhost,
6881 origin_type == SpawnedTestServer::TYPE_HTTPS
6882 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6883 : base::FilePath(
6884 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6885 ASSERT_TRUE(origin_server_->Start());
6888 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
6889 SpawnedTestServer::Type destination_type) {
6890 origin_server_.reset(new SpawnedTestServer(
6891 origin_type, SpawnedTestServer::kLocalhost,
6892 origin_type == SpawnedTestServer::TYPE_HTTPS
6893 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6894 : base::FilePath(
6895 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6896 ASSERT_TRUE(origin_server_->Start());
6898 destination_server_.reset(new SpawnedTestServer(
6899 destination_type, SpawnedTestServer::kLocalhost,
6900 destination_type == SpawnedTestServer::TYPE_HTTPS
6901 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6902 : base::FilePath(
6903 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6904 ASSERT_TRUE(destination_server_->Start());
6907 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
6908 const GURL& referrer,
6909 const GURL& expected) {
6910 // Create and execute the request: we'll only have a |destination_server_|
6911 // if the origins are meant to be distinct. Otherwise, we'll use the
6912 // |origin_server_| for both endpoints.
6913 GURL destination_url =
6914 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
6915 : origin_server_->GetURL("echoheader?Referer");
6916 GURL origin_url =
6917 origin_server_->GetURL("server-redirect?" + destination_url.spec());
6919 TestDelegate d;
6920 scoped_ptr<URLRequest> req(
6921 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
6922 req->set_referrer_policy(policy);
6923 req->SetReferrer(referrer.spec());
6924 req->Start();
6925 base::RunLoop().Run();
6927 EXPECT_EQ(1, d.response_started_count());
6928 EXPECT_EQ(1, d.received_redirect_count());
6929 EXPECT_EQ(destination_url, req->url());
6930 EXPECT_TRUE(req->status().is_success());
6931 EXPECT_EQ(200, req->response_headers()->response_code());
6933 EXPECT_EQ(expected.spec(), req->referrer());
6934 if (expected.is_empty())
6935 EXPECT_EQ("None", d.data_received());
6936 else
6937 EXPECT_EQ(expected.spec(), d.data_received());
6940 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
6942 private:
6943 scoped_ptr<SpawnedTestServer> origin_server_;
6944 scoped_ptr<SpawnedTestServer> destination_server_;
6947 TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
6948 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
6950 VerifyReferrerAfterRedirect(
6951 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6952 origin_server()->GetURL("path/to/file.html"),
6953 origin_server()->GetURL("path/to/file.html"));
6955 VerifyReferrerAfterRedirect(
6956 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6957 origin_server()->GetURL("path/to/file.html"),
6958 origin_server()->GetURL("path/to/file.html"));
6960 VerifyReferrerAfterRedirect(
6961 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6962 origin_server()->GetURL("path/to/file.html"),
6963 origin_server()->GetURL("path/to/file.html"));
6965 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6966 origin_server()->GetURL("path/to/file.html"),
6967 origin_server()->GetURL("path/to/file.html"));
6970 TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
6971 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
6972 SpawnedTestServer::TYPE_HTTP);
6974 VerifyReferrerAfterRedirect(
6975 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6976 origin_server()->GetURL("path/to/file.html"),
6977 origin_server()->GetURL("path/to/file.html"));
6979 VerifyReferrerAfterRedirect(
6980 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6981 origin_server()->GetURL("path/to/file.html"),
6982 origin_server()->GetURL(std::string()));
6984 VerifyReferrerAfterRedirect(
6985 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6986 origin_server()->GetURL("path/to/file.html"),
6987 origin_server()->GetURL(std::string()));
6989 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6990 origin_server()->GetURL("path/to/file.html"),
6991 origin_server()->GetURL("path/to/file.html"));
6994 TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
6995 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
6997 VerifyReferrerAfterRedirect(
6998 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6999 origin_server()->GetURL("path/to/file.html"),
7000 origin_server()->GetURL("path/to/file.html"));
7002 VerifyReferrerAfterRedirect(
7003 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7004 origin_server()->GetURL("path/to/file.html"),
7005 origin_server()->GetURL("path/to/file.html"));
7007 VerifyReferrerAfterRedirect(
7008 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7009 origin_server()->GetURL("path/to/file.html"),
7010 origin_server()->GetURL("path/to/file.html"));
7012 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7013 origin_server()->GetURL("path/to/file.html"),
7014 origin_server()->GetURL("path/to/file.html"));
7017 TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7018 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7019 SpawnedTestServer::TYPE_HTTPS);
7021 VerifyReferrerAfterRedirect(
7022 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7023 origin_server()->GetURL("path/to/file.html"),
7024 origin_server()->GetURL("path/to/file.html"));
7026 VerifyReferrerAfterRedirect(
7027 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7028 origin_server()->GetURL("path/to/file.html"),
7029 origin_server()->GetURL(std::string()));
7031 VerifyReferrerAfterRedirect(
7032 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7033 origin_server()->GetURL("path/to/file.html"),
7034 origin_server()->GetURL(std::string()));
7036 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7037 origin_server()->GetURL("path/to/file.html"),
7038 origin_server()->GetURL("path/to/file.html"));
7041 TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7042 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7043 SpawnedTestServer::TYPE_HTTPS);
7045 VerifyReferrerAfterRedirect(
7046 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7047 origin_server()->GetURL("path/to/file.html"),
7048 origin_server()->GetURL("path/to/file.html"));
7050 VerifyReferrerAfterRedirect(
7051 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7052 origin_server()->GetURL("path/to/file.html"),
7053 origin_server()->GetURL(std::string()));
7055 VerifyReferrerAfterRedirect(
7056 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7057 origin_server()->GetURL("path/to/file.html"),
7058 origin_server()->GetURL(std::string()));
7060 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7061 origin_server()->GetURL("path/to/file.html"),
7062 origin_server()->GetURL("path/to/file.html"));
7065 TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7066 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7067 SpawnedTestServer::TYPE_HTTP);
7069 VerifyReferrerAfterRedirect(
7070 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7071 origin_server()->GetURL("path/to/file.html"), GURL());
7073 VerifyReferrerAfterRedirect(
7074 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7075 origin_server()->GetURL("path/to/file.html"), GURL());
7077 VerifyReferrerAfterRedirect(
7078 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7079 origin_server()->GetURL("path/to/file.html"),
7080 origin_server()->GetURL(std::string()));
7082 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7083 origin_server()->GetURL("path/to/file.html"),
7084 origin_server()->GetURL("path/to/file.html"));
7087 class HTTPSRequestTest : public testing::Test {
7088 public:
7089 HTTPSRequestTest() : default_context_(true) {
7090 default_context_.set_network_delegate(&default_network_delegate_);
7091 default_context_.Init();
7093 ~HTTPSRequestTest() override {}
7095 protected:
7096 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7097 TestURLRequestContext default_context_;
7100 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
7101 SpawnedTestServer test_server(
7102 SpawnedTestServer::TYPE_HTTPS,
7103 SpawnedTestServer::kLocalhost,
7104 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7105 ASSERT_TRUE(test_server.Start());
7107 TestDelegate d;
7109 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7110 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7111 r->Start();
7112 EXPECT_TRUE(r->is_pending());
7114 base::RunLoop().Run();
7116 EXPECT_EQ(1, d.response_started_count());
7117 EXPECT_FALSE(d.received_data_before_response());
7118 EXPECT_NE(0, d.bytes_received());
7119 CheckSSLInfo(r->ssl_info());
7120 EXPECT_EQ(test_server.host_port_pair().host(),
7121 r->GetSocketAddress().host());
7122 EXPECT_EQ(test_server.host_port_pair().port(),
7123 r->GetSocketAddress().port());
7127 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
7128 SpawnedTestServer::SSLOptions ssl_options(
7129 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7130 SpawnedTestServer test_server(
7131 SpawnedTestServer::TYPE_HTTPS,
7132 ssl_options,
7133 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7134 ASSERT_TRUE(test_server.Start());
7136 bool err_allowed = true;
7137 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7138 TestDelegate d;
7140 d.set_allow_certificate_errors(err_allowed);
7141 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7142 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7144 r->Start();
7145 EXPECT_TRUE(r->is_pending());
7147 base::RunLoop().Run();
7149 EXPECT_EQ(1, d.response_started_count());
7150 EXPECT_FALSE(d.received_data_before_response());
7151 EXPECT_TRUE(d.have_certificate_errors());
7152 if (err_allowed) {
7153 EXPECT_NE(0, d.bytes_received());
7154 CheckSSLInfo(r->ssl_info());
7155 } else {
7156 EXPECT_EQ(0, d.bytes_received());
7162 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
7163 SpawnedTestServer::SSLOptions ssl_options(
7164 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7165 SpawnedTestServer test_server(
7166 SpawnedTestServer::TYPE_HTTPS,
7167 ssl_options,
7168 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7169 ASSERT_TRUE(test_server.Start());
7171 // Iterate from false to true, just so that we do the opposite of the
7172 // previous test in order to increase test coverage.
7173 bool err_allowed = false;
7174 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7175 TestDelegate d;
7177 d.set_allow_certificate_errors(err_allowed);
7178 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7179 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7181 r->Start();
7182 EXPECT_TRUE(r->is_pending());
7184 base::RunLoop().Run();
7186 EXPECT_EQ(1, d.response_started_count());
7187 EXPECT_FALSE(d.received_data_before_response());
7188 EXPECT_TRUE(d.have_certificate_errors());
7189 if (err_allowed) {
7190 EXPECT_NE(0, d.bytes_received());
7191 CheckSSLInfo(r->ssl_info());
7192 } else {
7193 EXPECT_EQ(0, d.bytes_received());
7199 // Tests that servers which require a deprecated cipher suite still work.
7200 TEST_F(HTTPSRequestTest, CipherFallbackTest) {
7201 CapturingNetLog net_log;
7202 default_context_.set_net_log(&net_log);
7204 SpawnedTestServer::SSLOptions ssl_options;
7205 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7206 SpawnedTestServer test_server(
7207 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7208 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7209 ASSERT_TRUE(test_server.Start());
7211 TestDelegate d;
7212 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7213 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7214 r->Start();
7215 EXPECT_TRUE(r->is_pending());
7217 base::RunLoop().Run();
7219 EXPECT_EQ(1, d.response_started_count());
7220 EXPECT_FALSE(d.received_data_before_response());
7221 EXPECT_NE(0, d.bytes_received());
7222 CheckSSLInfo(r->ssl_info());
7223 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7224 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7226 // No version downgrade should have been necessary.
7227 EXPECT_FALSE(r->ssl_info().connection_status &
7228 SSL_CONNECTION_VERSION_FALLBACK);
7229 int expected_version = SSL_CONNECTION_VERSION_TLS1_2;
7230 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7231 SSL_PROTOCOL_VERSION_TLS1_2) {
7232 expected_version = SSL_CONNECTION_VERSION_TLS1_1;
7234 EXPECT_EQ(expected_version,
7235 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7237 CapturingNetLog::CapturedEntryList entries;
7238 net_log.GetEntries(&entries);
7239 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7240 NetLog::PHASE_NONE);
7243 // This tests that a load of www.google.com with a certificate error sets
7244 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
7245 // the interstitial to be fatal.
7246 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
7247 SpawnedTestServer::SSLOptions ssl_options(
7248 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7249 SpawnedTestServer test_server(
7250 SpawnedTestServer::TYPE_HTTPS,
7251 ssl_options,
7252 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7253 ASSERT_TRUE(test_server.Start());
7255 // We require that the URL be www.google.com in order to pick up the
7256 // preloaded HSTS entries in the TransportSecurityState. This means that we
7257 // have to use a MockHostResolver in order to direct www.google.com to the
7258 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7260 MockHostResolver host_resolver;
7261 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7262 TestURLRequestContext context(true);
7263 context.set_network_delegate(&network_delegate);
7264 context.set_host_resolver(&host_resolver);
7265 TransportSecurityState transport_security_state;
7266 context.set_transport_security_state(&transport_security_state);
7267 context.Init();
7269 TestDelegate d;
7270 scoped_ptr<URLRequest> r(context.CreateRequest(
7271 GURL(base::StringPrintf("https://www.google.com:%d",
7272 test_server.host_port_pair().port())),
7273 DEFAULT_PRIORITY, &d));
7275 r->Start();
7276 EXPECT_TRUE(r->is_pending());
7278 base::RunLoop().Run();
7280 EXPECT_EQ(1, d.response_started_count());
7281 EXPECT_FALSE(d.received_data_before_response());
7282 EXPECT_TRUE(d.have_certificate_errors());
7283 EXPECT_TRUE(d.certificate_errors_are_fatal());
7286 // This tests that cached HTTPS page loads do not cause any updates to the
7287 // TransportSecurityState.
7288 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7289 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7290 // matter. It just has to be any error.
7291 SpawnedTestServer::SSLOptions ssl_options(
7292 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7293 SpawnedTestServer test_server(
7294 SpawnedTestServer::TYPE_HTTPS,
7295 ssl_options,
7296 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7297 ASSERT_TRUE(test_server.Start());
7299 // We require that the URL be www.google.com in order to pick up the static
7300 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7301 // that we have to use a MockHostResolver in order to direct www.google.com to
7302 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
7304 MockHostResolver host_resolver;
7305 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7306 TestURLRequestContext context(true);
7307 context.set_network_delegate(&network_delegate);
7308 context.set_host_resolver(&host_resolver);
7309 TransportSecurityState transport_security_state;
7311 TransportSecurityState::DomainState static_domain_state;
7312 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
7313 "www.google.com", &static_domain_state));
7314 context.set_transport_security_state(&transport_security_state);
7315 context.Init();
7317 TransportSecurityState::DomainState dynamic_domain_state;
7318 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7319 "www.google.com", &dynamic_domain_state));
7321 TestDelegate d;
7322 scoped_ptr<URLRequest> r(context.CreateRequest(
7323 GURL(base::StringPrintf("https://www.google.com:%d",
7324 test_server.host_port_pair().port())),
7325 DEFAULT_PRIORITY, &d));
7327 r->Start();
7328 EXPECT_TRUE(r->is_pending());
7330 base::RunLoop().Run();
7332 EXPECT_EQ(1, d.response_started_count());
7333 EXPECT_FALSE(d.received_data_before_response());
7334 EXPECT_TRUE(d.have_certificate_errors());
7335 EXPECT_TRUE(d.certificate_errors_are_fatal());
7337 // Get a fresh copy of the states, and check that they haven't changed.
7338 TransportSecurityState::DomainState new_static_domain_state;
7339 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
7340 "www.google.com", &new_static_domain_state));
7341 TransportSecurityState::DomainState new_dynamic_domain_state;
7342 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7343 "www.google.com", &new_dynamic_domain_state));
7345 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7346 static_domain_state.sts.upgrade_mode);
7347 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7348 static_domain_state.sts.include_subdomains);
7349 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7350 static_domain_state.pkp.include_subdomains);
7351 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7352 static_domain_state.pkp.spki_hashes));
7353 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7354 static_domain_state.pkp.bad_spki_hashes));
7357 // Make sure HSTS preserves a POST request's method and body.
7358 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7359 static const char kData[] = "hello world";
7361 SpawnedTestServer::SSLOptions ssl_options(
7362 SpawnedTestServer::SSLOptions::CERT_OK);
7363 SpawnedTestServer test_server(
7364 SpawnedTestServer::TYPE_HTTPS,
7365 ssl_options,
7366 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7367 ASSERT_TRUE(test_server.Start());
7370 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7371 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
7372 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7373 // to 127.0.0.1.
7374 MockHostResolver host_resolver;
7376 // Force https for www.somewhere.com.
7377 TransportSecurityState transport_security_state;
7378 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7379 bool include_subdomains = false;
7380 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7381 include_subdomains);
7383 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7385 TestURLRequestContext context(true);
7386 context.set_host_resolver(&host_resolver);
7387 context.set_transport_security_state(&transport_security_state);
7388 context.set_network_delegate(&network_delegate);
7389 context.Init();
7391 TestDelegate d;
7392 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7393 // cause a certificate error. Ignore the error.
7394 d.set_allow_certificate_errors(true);
7396 scoped_ptr<URLRequest> req(context.CreateRequest(
7397 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
7398 test_server.host_port_pair().port())),
7399 DEFAULT_PRIORITY, &d));
7400 req->set_method("POST");
7401 req->set_upload(CreateSimpleUploadData(kData));
7403 req->Start();
7404 base::RunLoop().Run();
7406 EXPECT_EQ("https", req->url().scheme());
7407 EXPECT_EQ("POST", req->method());
7408 EXPECT_EQ(kData, d.data_received());
7410 LoadTimingInfo load_timing_info;
7411 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7412 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7413 TestLoadTimingCacheHitNoNetwork(load_timing_info);
7416 // Make sure that the CORS headers are added to cross-origin HSTS redirects.
7417 TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7418 static const char kOriginHeaderValue[] = "http://www.example.com";
7420 SpawnedTestServer::SSLOptions ssl_options(
7421 SpawnedTestServer::SSLOptions::CERT_OK);
7422 SpawnedTestServer test_server(
7423 SpawnedTestServer::TYPE_HTTPS,
7424 ssl_options,
7425 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7426 ASSERT_TRUE(test_server.Start());
7428 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7429 // address, so a MockHostResolver is needed to redirect example.net to the
7430 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7431 MockHostResolver host_resolver;
7433 TransportSecurityState transport_security_state;
7434 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7435 bool include_subdomains = false;
7436 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7438 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7440 MockCertVerifier cert_verifier;
7441 cert_verifier.set_default_result(OK);
7443 TestURLRequestContext context(true);
7444 context.set_host_resolver(&host_resolver);
7445 context.set_transport_security_state(&transport_security_state);
7446 context.set_network_delegate(&network_delegate);
7447 context.set_cert_verifier(&cert_verifier);
7448 context.Init();
7450 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7451 test_server.host_port_pair().port()));
7452 url::Replacements<char> replacements;
7453 const char kNewScheme[] = "https";
7454 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7455 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7457 TestDelegate d;
7458 // Quit on redirect to allow response header inspection upon redirect.
7459 d.set_quit_on_redirect(true);
7461 scoped_ptr<URLRequest> req(
7462 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
7463 // Set Origin header to simulate a cross-origin request.
7464 HttpRequestHeaders request_headers;
7465 request_headers.SetHeader("Origin", kOriginHeaderValue);
7466 req->SetExtraRequestHeaders(request_headers);
7468 req->Start();
7469 base::RunLoop().Run();
7471 EXPECT_EQ(1, d.received_redirect_count());
7473 const HttpResponseHeaders* headers = req->response_headers();
7474 std::string redirect_location;
7475 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7476 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7478 std::string received_cors_header;
7479 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7480 &received_cors_header));
7481 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7484 // This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7485 // are performed in net/websockets/websocket_end_to_end_test.cc.
7486 TEST(WebSocketURLRequestTest, HSTSApplied) {
7487 TestNetworkDelegate network_delegate;
7488 TransportSecurityState transport_security_state;
7489 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7490 bool include_subdomains = false;
7491 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7492 TestURLRequestContext context(true);
7493 context.set_transport_security_state(&transport_security_state);
7494 context.set_network_delegate(&network_delegate);
7495 context.Init();
7496 GURL ws_url("ws://example.net/echo");
7497 TestDelegate delegate;
7498 scoped_ptr<URLRequest> request(
7499 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
7500 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7501 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7504 namespace {
7506 class SSLClientAuthTestDelegate : public TestDelegate {
7507 public:
7508 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7510 void OnCertificateRequested(URLRequest* request,
7511 SSLCertRequestInfo* cert_request_info) override {
7512 on_certificate_requested_count_++;
7513 base::MessageLoop::current()->Quit();
7515 int on_certificate_requested_count() {
7516 return on_certificate_requested_count_;
7518 private:
7519 int on_certificate_requested_count_;
7522 } // namespace
7524 // TODO(davidben): Test the rest of the code. Specifically,
7525 // - Filtering which certificates to select.
7526 // - Sending a certificate back.
7527 // - Getting a certificate request in an SSL renegotiation sending the
7528 // HTTP request.
7529 TEST_F(HTTPSRequestTest, ClientAuthTest) {
7530 SpawnedTestServer::SSLOptions ssl_options;
7531 ssl_options.request_client_certificate = true;
7532 SpawnedTestServer test_server(
7533 SpawnedTestServer::TYPE_HTTPS,
7534 ssl_options,
7535 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7536 ASSERT_TRUE(test_server.Start());
7538 SSLClientAuthTestDelegate d;
7540 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7541 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7543 r->Start();
7544 EXPECT_TRUE(r->is_pending());
7546 base::RunLoop().Run();
7548 EXPECT_EQ(1, d.on_certificate_requested_count());
7549 EXPECT_FALSE(d.received_data_before_response());
7550 EXPECT_EQ(0, d.bytes_received());
7552 // Send no certificate.
7553 // TODO(davidben): Get temporary client cert import (with keys) working on
7554 // all platforms so we can test sending a cert as well.
7555 r->ContinueWithCertificate(NULL);
7557 base::RunLoop().Run();
7559 EXPECT_EQ(1, d.response_started_count());
7560 EXPECT_FALSE(d.received_data_before_response());
7561 EXPECT_NE(0, d.bytes_received());
7565 TEST_F(HTTPSRequestTest, ResumeTest) {
7566 // Test that we attempt a session resume when making two connections to the
7567 // same host.
7568 SpawnedTestServer::SSLOptions ssl_options;
7569 ssl_options.record_resume = true;
7570 SpawnedTestServer test_server(
7571 SpawnedTestServer::TYPE_HTTPS,
7572 ssl_options,
7573 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7574 ASSERT_TRUE(test_server.Start());
7576 SSLClientSocket::ClearSessionCache();
7579 TestDelegate d;
7580 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7581 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
7583 r->Start();
7584 EXPECT_TRUE(r->is_pending());
7586 base::RunLoop().Run();
7588 EXPECT_EQ(1, d.response_started_count());
7591 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7592 CloseAllConnections();
7595 TestDelegate d;
7596 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7597 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
7599 r->Start();
7600 EXPECT_TRUE(r->is_pending());
7602 base::RunLoop().Run();
7604 // The response will look like;
7605 // insert abc
7606 // lookup abc
7607 // insert xyz
7609 // With a newline at the end which makes the split think that there are
7610 // four lines.
7612 EXPECT_EQ(1, d.response_started_count());
7613 std::vector<std::string> lines;
7614 base::SplitString(d.data_received(), '\n', &lines);
7615 ASSERT_EQ(4u, lines.size()) << d.data_received();
7617 std::string session_id;
7619 for (size_t i = 0; i < 2; i++) {
7620 std::vector<std::string> parts;
7621 base::SplitString(lines[i], '\t', &parts);
7622 ASSERT_EQ(2u, parts.size());
7623 if (i == 0) {
7624 EXPECT_EQ("insert", parts[0]);
7625 session_id = parts[1];
7626 } else {
7627 EXPECT_EQ("lookup", parts[0]);
7628 EXPECT_EQ(session_id, parts[1]);
7634 // AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7635 // the result of fetching "ssl-session-cache" from the test server, indicates
7636 // that exactly two different sessions were inserted, with no lookups etc.
7637 static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7638 std::vector<std::string> lines;
7639 base::SplitString(session_info, '\n', &lines);
7640 ASSERT_EQ(3u, lines.size()) << session_info;
7642 std::string session_id;
7643 for (size_t i = 0; i < 2; i++) {
7644 std::vector<std::string> parts;
7645 base::SplitString(lines[i], '\t', &parts);
7646 ASSERT_EQ(2u, parts.size());
7647 EXPECT_EQ("insert", parts[0]);
7648 if (i == 0) {
7649 session_id = parts[1];
7650 } else {
7651 EXPECT_NE(session_id, parts[1]);
7656 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7657 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7658 // differs.
7659 SpawnedTestServer::SSLOptions ssl_options;
7660 ssl_options.record_resume = true;
7661 SpawnedTestServer test_server(
7662 SpawnedTestServer::TYPE_HTTPS,
7663 ssl_options,
7664 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7665 ASSERT_TRUE(test_server.Start());
7667 SSLClientSocket::ClearSessionCache();
7670 TestDelegate d;
7671 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7672 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
7674 r->Start();
7675 EXPECT_TRUE(r->is_pending());
7677 base::RunLoop().Run();
7679 EXPECT_EQ(1, d.response_started_count());
7682 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7683 HttpNetworkSession::Params params;
7684 params.host_resolver = default_context_.host_resolver();
7685 params.cert_verifier = default_context_.cert_verifier();
7686 params.transport_security_state = default_context_.transport_security_state();
7687 params.proxy_service = default_context_.proxy_service();
7688 params.ssl_config_service = default_context_.ssl_config_service();
7689 params.http_auth_handler_factory =
7690 default_context_.http_auth_handler_factory();
7691 params.network_delegate = &default_network_delegate_;
7692 params.http_server_properties = default_context_.http_server_properties();
7693 params.ssl_session_cache_shard = "alternate";
7695 scoped_ptr<HttpCache> cache(new HttpCache(
7696 new HttpNetworkSession(params),
7697 HttpCache::DefaultBackend::InMemory(0)));
7699 default_context_.set_http_transaction_factory(cache.get());
7702 TestDelegate d;
7703 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7704 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
7706 r->Start();
7707 EXPECT_TRUE(r->is_pending());
7709 base::RunLoop().Run();
7711 // The response will look like;
7712 // insert abc
7713 // insert xyz
7715 // With a newline at the end which makes the split think that there are
7716 // three lines.
7718 EXPECT_EQ(1, d.response_started_count());
7719 AssertTwoDistinctSessionsInserted(d.data_received());
7723 #if defined(OS_WIN)
7725 namespace {
7727 bool IsECDSACipherSuite(uint16_t cipher_suite) {
7728 const char* key_exchange;
7729 const char* cipher;
7730 const char* mac;
7731 bool is_aead;
7732 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7733 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7736 } // namespace
7738 // Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7739 // verified.
7740 TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
7741 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7742 LOG(INFO) << "Skipping test on this version.";
7743 return;
7746 SpawnedTestServer test_server(
7747 SpawnedTestServer::TYPE_HTTPS,
7748 SpawnedTestServer::kLocalhost,
7749 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7750 ASSERT_TRUE(test_server.Start());
7752 TestDelegate d;
7753 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7754 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
7755 r->Start();
7756 EXPECT_TRUE(r->is_pending());
7758 base::RunLoop().Run();
7760 EXPECT_EQ(1, d.response_started_count());
7761 std::vector<std::string> lines;
7762 base::SplitString(d.data_received(), '\n', &lines);
7764 for (size_t i = 0; i < lines.size(); i++) {
7765 int cipher_suite;
7766 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7767 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7768 << "ClientHello advertised " << cipher_suite;
7772 #endif // OS_WIN
7774 class TestSSLConfigService : public SSLConfigService {
7775 public:
7776 TestSSLConfigService(bool ev_enabled,
7777 bool online_rev_checking,
7778 bool rev_checking_required_local_anchors)
7779 : ev_enabled_(ev_enabled),
7780 online_rev_checking_(online_rev_checking),
7781 rev_checking_required_local_anchors_(
7782 rev_checking_required_local_anchors),
7783 min_version_(kDefaultSSLVersionMin),
7784 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7786 void set_min_version(uint16 version) {
7787 min_version_ = version;
7790 void set_fallback_min_version(uint16 version) {
7791 fallback_min_version_ = version;
7794 // SSLConfigService:
7795 void GetSSLConfig(SSLConfig* config) override {
7796 *config = SSLConfig();
7797 config->rev_checking_enabled = online_rev_checking_;
7798 config->verify_ev_cert = ev_enabled_;
7799 config->rev_checking_required_local_anchors =
7800 rev_checking_required_local_anchors_;
7801 if (fallback_min_version_) {
7802 config->version_fallback_min = fallback_min_version_;
7804 if (min_version_) {
7805 config->version_min = min_version_;
7809 protected:
7810 ~TestSSLConfigService() override {}
7812 private:
7813 const bool ev_enabled_;
7814 const bool online_rev_checking_;
7815 const bool rev_checking_required_local_anchors_;
7816 uint16 min_version_;
7817 uint16 fallback_min_version_;
7820 class FallbackTestURLRequestContext : public TestURLRequestContext {
7821 public:
7822 explicit FallbackTestURLRequestContext(bool delay_initialization)
7823 : TestURLRequestContext(delay_initialization) {}
7825 void set_fallback_min_version(uint16 version) {
7826 TestSSLConfigService *ssl_config_service =
7827 new TestSSLConfigService(true /* check for EV */,
7828 false /* online revocation checking */,
7829 false /* require rev. checking for local
7830 anchors */);
7831 ssl_config_service->set_min_version(SSL_PROTOCOL_VERSION_SSL3);
7832 ssl_config_service->set_fallback_min_version(version);
7833 set_ssl_config_service(ssl_config_service);
7837 class HTTPSFallbackTest : public testing::Test {
7838 public:
7839 HTTPSFallbackTest() : context_(true) {}
7840 ~HTTPSFallbackTest() override {}
7842 protected:
7843 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7844 DCHECK(!request_);
7845 context_.Init();
7846 delegate_.set_allow_certificate_errors(true);
7848 SpawnedTestServer test_server(
7849 SpawnedTestServer::TYPE_HTTPS,
7850 ssl_options,
7851 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7852 ASSERT_TRUE(test_server.Start());
7854 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
7855 DEFAULT_PRIORITY, &delegate_);
7856 request_->Start();
7858 base::RunLoop().Run();
7861 void set_fallback_min_version(uint16 version) {
7862 context_.set_fallback_min_version(version);
7865 void ExpectConnection(int version) {
7866 EXPECT_EQ(1, delegate_.response_started_count());
7867 EXPECT_NE(0, delegate_.bytes_received());
7868 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7869 request_->ssl_info().connection_status));
7870 EXPECT_TRUE(request_->ssl_info().connection_status &
7871 SSL_CONNECTION_VERSION_FALLBACK);
7874 void ExpectFailure(int error) {
7875 EXPECT_EQ(1, delegate_.response_started_count());
7876 EXPECT_FALSE(request_->status().is_success());
7877 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7878 EXPECT_EQ(error, request_->status().error());
7881 private:
7882 TestDelegate delegate_;
7883 FallbackTestURLRequestContext context_;
7884 scoped_ptr<URLRequest> request_;
7887 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7888 // than necessary.
7889 TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7890 SpawnedTestServer::SSLOptions ssl_options(
7891 SpawnedTestServer::SSLOptions::CERT_OK);
7892 ssl_options.tls_intolerant =
7893 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7895 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7896 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7899 // This test is disabled on Android because the remote test server doesn't cause
7900 // a TCP reset.
7901 #if !defined(OS_ANDROID)
7902 // Tests fallback to TLS 1.0 on connection reset.
7903 TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7904 SpawnedTestServer::SSLOptions ssl_options(
7905 SpawnedTestServer::SSLOptions::CERT_OK);
7906 ssl_options.tls_intolerant =
7907 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7908 ssl_options.tls_intolerance_type =
7909 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7911 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7912 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7914 #endif // !OS_ANDROID
7916 // Tests that we don't fallback on handshake failure with servers that implement
7917 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7918 TEST_F(HTTPSFallbackTest, FallbackSCSV) {
7919 SpawnedTestServer::SSLOptions ssl_options(
7920 SpawnedTestServer::SSLOptions::CERT_OK);
7921 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
7922 // a version fallback.
7923 ssl_options.tls_intolerant =
7924 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7925 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7926 // connections are rejected.
7927 ssl_options.fallback_scsv_enabled = true;
7929 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7931 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7932 // intolerance. If the fallback SCSV is processed when the original error
7933 // that caused the fallback should be returned, which should be
7934 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7935 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7938 // Tests that we don't fallback on connection closed with servers that implement
7939 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7940 TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
7941 SpawnedTestServer::SSLOptions ssl_options(
7942 SpawnedTestServer::SSLOptions::CERT_OK);
7943 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
7944 // a version fallback.
7945 ssl_options.tls_intolerant =
7946 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7947 ssl_options.tls_intolerance_type =
7948 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7949 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7950 // connections are rejected.
7951 ssl_options.fallback_scsv_enabled = true;
7953 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7955 // The original error should be replayed on rejected fallback.
7956 ExpectFailure(ERR_CONNECTION_CLOSED);
7959 // Tests that the SSLv3 fallback doesn't happen by default.
7960 TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7961 SpawnedTestServer::SSLOptions ssl_options(
7962 SpawnedTestServer::SSLOptions::CERT_OK);
7963 ssl_options.tls_intolerant =
7964 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7966 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7967 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7970 // Tests that the SSLv3 fallback works when explicitly enabled.
7971 TEST_F(HTTPSFallbackTest, SSLv3FallbackEnabled) {
7972 SpawnedTestServer::SSLOptions ssl_options(
7973 SpawnedTestServer::SSLOptions::CERT_OK);
7974 ssl_options.tls_intolerant =
7975 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7976 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7978 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7979 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7982 // Tests that the SSLv3 fallback triggers on closed connections when explicitly
7983 // enabled.
7984 TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
7985 SpawnedTestServer::SSLOptions ssl_options(
7986 SpawnedTestServer::SSLOptions::CERT_OK);
7987 ssl_options.tls_intolerant =
7988 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7989 ssl_options.tls_intolerance_type =
7990 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7991 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7993 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7994 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7997 // Test that SSLv3 fallback probe connections don't cause sessions to be cached.
7998 TEST_F(HTTPSRequestTest, SSLv3FallbackNoCache) {
7999 SpawnedTestServer::SSLOptions ssl_options(
8000 SpawnedTestServer::SSLOptions::CERT_OK);
8001 ssl_options.tls_intolerant =
8002 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8003 ssl_options.tls_intolerance_type =
8004 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8005 ssl_options.record_resume = true;
8007 SpawnedTestServer test_server(
8008 SpawnedTestServer::TYPE_HTTPS,
8009 ssl_options,
8010 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8011 ASSERT_TRUE(test_server.Start());
8013 SSLClientSocket::ClearSessionCache();
8015 // Make a connection that does a probe fallback to SSLv3 but fails because
8016 // SSLv3 fallback is disabled. We don't wish a session for this connection to
8017 // be inserted locally.
8019 TestDelegate delegate;
8020 FallbackTestURLRequestContext context(true);
8022 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
8023 context.Init();
8024 scoped_ptr<URLRequest> request(context.CreateRequest(
8025 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
8026 request->Start();
8028 base::RunLoop().Run();
8030 EXPECT_EQ(1, delegate.response_started_count());
8031 EXPECT_FALSE(request->status().is_success());
8032 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8033 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8034 request->status().error());
8037 // Now allow SSLv3 connections and request the session cache log.
8039 TestDelegate delegate;
8040 FallbackTestURLRequestContext context(true);
8041 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
8043 context.Init();
8044 scoped_ptr<URLRequest> request(context.CreateRequest(
8045 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
8046 request->Start();
8048 base::RunLoop().Run();
8050 EXPECT_EQ(1, delegate.response_started_count());
8051 EXPECT_NE(0, delegate.bytes_received());
8052 EXPECT_EQ(SSL_CONNECTION_VERSION_SSL3, SSLConnectionStatusToVersion(
8053 request->ssl_info().connection_status));
8054 EXPECT_TRUE(request->ssl_info().connection_status &
8055 SSL_CONNECTION_VERSION_FALLBACK);
8057 std::vector<std::string> lines;
8058 // If no sessions were cached then the server should have seen two sessions
8059 // inserted with no lookups.
8060 AssertTwoDistinctSessionsInserted(delegate.data_received());
8064 // This test is disabled on Android because the remote test server doesn't cause
8065 // a TCP reset.
8066 #if !defined(OS_ANDROID)
8067 // Tests that a reset connection does not fallback down to SSL3.
8068 TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
8069 SpawnedTestServer::SSLOptions ssl_options(
8070 SpawnedTestServer::SSLOptions::CERT_OK);
8071 ssl_options.tls_intolerant =
8072 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8073 ssl_options.tls_intolerance_type =
8074 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8076 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8077 ExpectFailure(ERR_CONNECTION_RESET);
8079 #endif // !OS_ANDROID
8081 class HTTPSSessionTest : public testing::Test {
8082 public:
8083 HTTPSSessionTest() : default_context_(true) {
8084 cert_verifier_.set_default_result(OK);
8086 default_context_.set_network_delegate(&default_network_delegate_);
8087 default_context_.set_cert_verifier(&cert_verifier_);
8088 default_context_.Init();
8090 ~HTTPSSessionTest() override {}
8092 protected:
8093 MockCertVerifier cert_verifier_;
8094 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8095 TestURLRequestContext default_context_;
8098 // Tests that session resumption is not attempted if an invalid certificate
8099 // is presented.
8100 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8101 SpawnedTestServer::SSLOptions ssl_options;
8102 ssl_options.record_resume = true;
8103 SpawnedTestServer test_server(
8104 SpawnedTestServer::TYPE_HTTPS,
8105 ssl_options,
8106 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8107 ASSERT_TRUE(test_server.Start());
8109 SSLClientSocket::ClearSessionCache();
8111 // Simulate the certificate being expired and attempt a connection.
8112 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
8114 TestDelegate d;
8115 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8116 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
8118 r->Start();
8119 EXPECT_TRUE(r->is_pending());
8121 base::RunLoop().Run();
8123 EXPECT_EQ(1, d.response_started_count());
8126 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8127 CloseAllConnections();
8129 // Now change the certificate to be acceptable (so that the response is
8130 // loaded), and ensure that no session id is presented to the peer.
8131 cert_verifier_.set_default_result(OK);
8133 TestDelegate d;
8134 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8135 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
8137 r->Start();
8138 EXPECT_TRUE(r->is_pending());
8140 base::RunLoop().Run();
8142 // The response will look like;
8143 // insert abc
8144 // insert xyz
8146 // With a newline at the end which makes the split think that there are
8147 // three lines.
8149 // If a session was presented (eg: a bug), then the response would look
8150 // like;
8151 // insert abc
8152 // lookup abc
8153 // insert xyz
8155 EXPECT_EQ(1, d.response_started_count());
8156 AssertTwoDistinctSessionsInserted(d.data_received());
8160 // This the fingerprint of the "Testing CA" certificate used by the testserver.
8161 // See net/data/ssl/certificates/ocsp-test-root.pem.
8162 static const SHA1HashValue kOCSPTestCertFingerprint =
8163 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8164 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8166 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8167 // testserver.
8168 static const SHA256HashValue kOCSPTestCertSPKI = { {
8169 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8170 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8171 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8172 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8173 } };
8175 // This is the policy OID contained in the certificates that testserver
8176 // generates.
8177 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8179 class HTTPSOCSPTest : public HTTPSRequestTest {
8180 public:
8181 HTTPSOCSPTest()
8182 : context_(true),
8183 ev_test_policy_(
8184 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8185 kOCSPTestCertFingerprint,
8186 kOCSPTestCertPolicy)) {
8189 void SetUp() override {
8190 SetupContext(&context_);
8191 context_.Init();
8193 scoped_refptr<X509Certificate> root_cert =
8194 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
8195 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
8196 test_root_.reset(new ScopedTestRoot(root_cert.get()));
8198 #if defined(USE_NSS) || defined(OS_IOS)
8199 SetURLRequestContextForNSSHttpIO(&context_);
8200 EnsureNSSHttpIOInit();
8201 #endif
8204 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
8205 CertStatus* out_cert_status) {
8206 // We always overwrite out_cert_status.
8207 *out_cert_status = 0;
8208 SpawnedTestServer test_server(
8209 SpawnedTestServer::TYPE_HTTPS,
8210 ssl_options,
8211 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8212 ASSERT_TRUE(test_server.Start());
8214 TestDelegate d;
8215 d.set_allow_certificate_errors(true);
8216 scoped_ptr<URLRequest> r(context_.CreateRequest(
8217 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
8218 r->Start();
8220 base::RunLoop().Run();
8222 EXPECT_EQ(1, d.response_started_count());
8223 *out_cert_status = r->ssl_info().cert_status;
8226 ~HTTPSOCSPTest() override {
8227 #if defined(USE_NSS) || defined(OS_IOS)
8228 ShutdownNSSHttpIO();
8229 #endif
8232 protected:
8233 // SetupContext configures the URLRequestContext that will be used for making
8234 // connetions to testserver. This can be overridden in test subclasses for
8235 // different behaviour.
8236 virtual void SetupContext(URLRequestContext* context) {
8237 context->set_ssl_config_service(
8238 new TestSSLConfigService(true /* check for EV */,
8239 true /* online revocation checking */,
8240 false /* require rev. checking for local
8241 anchors */));
8244 scoped_ptr<ScopedTestRoot> test_root_;
8245 TestURLRequestContext context_;
8246 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
8249 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
8250 #if defined(OS_WIN)
8251 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8252 // have that ability on other platforms.
8253 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8254 #else
8255 return 0;
8256 #endif
8259 // SystemSupportsHardFailRevocationChecking returns true iff the current
8260 // operating system supports revocation checking and can distinguish between
8261 // situations where a given certificate lacks any revocation information (eg:
8262 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8263 // revocation information cannot be obtained (eg: the CRL was unreachable).
8264 // If it does not, then tests which rely on 'hard fail' behaviour should be
8265 // skipped.
8266 static bool SystemSupportsHardFailRevocationChecking() {
8267 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
8268 return true;
8269 #else
8270 return false;
8271 #endif
8274 // SystemUsesChromiumEVMetadata returns true iff the current operating system
8275 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8276 // several tests are effected because our testing EV certificate won't be
8277 // recognised as EV.
8278 static bool SystemUsesChromiumEVMetadata() {
8279 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
8280 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8281 return false;
8282 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8283 // On OS X and Android, we use the system to tell us whether a certificate is
8284 // EV or not and the system won't recognise our testing root.
8285 return false;
8286 #else
8287 return true;
8288 #endif
8291 static bool SystemSupportsOCSP() {
8292 #if defined(USE_OPENSSL_CERTS)
8293 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8294 return false;
8295 #elif defined(OS_WIN)
8296 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8297 #elif defined(OS_ANDROID)
8298 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8299 return false;
8300 #else
8301 return true;
8302 #endif
8305 static bool SystemSupportsOCSPStapling() {
8306 #if defined(USE_NSS)
8307 return true;
8308 #elif defined(OS_WIN)
8309 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8310 #else
8311 return false;
8312 #endif
8315 TEST_F(HTTPSOCSPTest, Valid) {
8316 if (!SystemSupportsOCSP()) {
8317 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8318 return;
8321 SpawnedTestServer::SSLOptions ssl_options(
8322 SpawnedTestServer::SSLOptions::CERT_AUTO);
8323 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8325 CertStatus cert_status;
8326 DoConnection(ssl_options, &cert_status);
8328 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8330 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8331 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8333 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8336 TEST_F(HTTPSOCSPTest, Revoked) {
8337 if (!SystemSupportsOCSP()) {
8338 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8339 return;
8342 SpawnedTestServer::SSLOptions ssl_options(
8343 SpawnedTestServer::SSLOptions::CERT_AUTO);
8344 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8346 CertStatus cert_status;
8347 DoConnection(ssl_options, &cert_status);
8349 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
8350 // Doesn't pass on OS X yet for reasons that need to be investigated.
8351 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8352 #endif
8353 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8354 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8357 TEST_F(HTTPSOCSPTest, Invalid) {
8358 if (!SystemSupportsOCSP()) {
8359 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8360 return;
8363 SpawnedTestServer::SSLOptions ssl_options(
8364 SpawnedTestServer::SSLOptions::CERT_AUTO);
8365 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8367 CertStatus cert_status;
8368 DoConnection(ssl_options, &cert_status);
8370 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8371 cert_status & CERT_STATUS_ALL_ERRORS);
8373 // Without a positive OCSP response, we shouldn't show the EV status.
8374 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8375 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8378 TEST_F(HTTPSOCSPTest, ValidStapled) {
8379 if (!SystemSupportsOCSPStapling()) {
8380 LOG(WARNING)
8381 << "Skipping test because system doesn't support OCSP stapling";
8382 return;
8385 SpawnedTestServer::SSLOptions ssl_options(
8386 SpawnedTestServer::SSLOptions::CERT_AUTO);
8387 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8388 ssl_options.staple_ocsp_response = true;
8389 ssl_options.ocsp_server_unavailable = true;
8391 CertStatus cert_status;
8392 DoConnection(ssl_options, &cert_status);
8394 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8396 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8397 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8399 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8402 // Disabled on NSS ports. See https://crbug.com/431716.
8403 #if defined(USE_NSS)
8404 #define MAYBE_RevokedStapled DISABLED_RevokedStapled
8405 #else
8406 #define MAYBE_RevokedStapled RevokedStapled
8407 #endif
8408 TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
8409 if (!SystemSupportsOCSPStapling()) {
8410 LOG(WARNING)
8411 << "Skipping test because system doesn't support OCSP stapling";
8412 return;
8415 SpawnedTestServer::SSLOptions ssl_options(
8416 SpawnedTestServer::SSLOptions::CERT_AUTO);
8417 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8418 ssl_options.staple_ocsp_response = true;
8419 ssl_options.ocsp_server_unavailable = true;
8421 CertStatus cert_status;
8422 DoConnection(ssl_options, &cert_status);
8424 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8425 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8426 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8429 class HTTPSHardFailTest : public HTTPSOCSPTest {
8430 protected:
8431 void SetupContext(URLRequestContext* context) override {
8432 context->set_ssl_config_service(
8433 new TestSSLConfigService(false /* check for EV */,
8434 false /* online revocation checking */,
8435 true /* require rev. checking for local
8436 anchors */));
8440 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8441 if (!SystemSupportsOCSP()) {
8442 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8443 return;
8446 if (!SystemSupportsHardFailRevocationChecking()) {
8447 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8448 << "revocation checking";
8449 return;
8452 SpawnedTestServer::SSLOptions ssl_options(
8453 SpawnedTestServer::SSLOptions::CERT_AUTO);
8454 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8456 CertStatus cert_status;
8457 DoConnection(ssl_options, &cert_status);
8459 EXPECT_EQ(CERT_STATUS_REVOKED,
8460 cert_status & CERT_STATUS_REVOKED);
8462 // Without a positive OCSP response, we shouldn't show the EV status.
8463 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8466 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8467 protected:
8468 void SetupContext(URLRequestContext* context) override {
8469 context->set_ssl_config_service(
8470 new TestSSLConfigService(true /* check for EV */,
8471 false /* online revocation checking */,
8472 false /* require rev. checking for local
8473 anchors */));
8477 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8478 if (!SystemSupportsOCSP()) {
8479 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8480 return;
8483 SpawnedTestServer::SSLOptions ssl_options(
8484 SpawnedTestServer::SSLOptions::CERT_AUTO);
8485 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8486 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8488 CertStatus cert_status;
8489 DoConnection(ssl_options, &cert_status);
8491 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8492 cert_status & CERT_STATUS_ALL_ERRORS);
8494 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8495 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8496 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8499 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8500 if (!SystemSupportsOCSP()) {
8501 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8502 return;
8505 SpawnedTestServer::SSLOptions ssl_options(
8506 SpawnedTestServer::SSLOptions::CERT_AUTO);
8507 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8508 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8510 CertStatus cert_status;
8511 DoConnection(ssl_options, &cert_status);
8513 // Currently only works for Windows. When using NSS or OS X, it's not
8514 // possible to determine whether the check failed because of actual
8515 // revocation or because there was an OCSP failure.
8516 #if defined(OS_WIN)
8517 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8518 #else
8519 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8520 #endif
8522 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8523 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8524 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8527 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8528 if (!SystemSupportsOCSP()) {
8529 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8530 return;
8533 SpawnedTestServer::SSLOptions ssl_options(
8534 SpawnedTestServer::SSLOptions::CERT_AUTO);
8535 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8536 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8538 CertStatus cert_status;
8539 DoConnection(ssl_options, &cert_status);
8541 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8543 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8544 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8545 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8546 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8549 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8550 if (!SystemSupportsOCSP()) {
8551 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8552 return;
8555 SpawnedTestServer::SSLOptions ssl_options(
8556 SpawnedTestServer::SSLOptions::CERT_AUTO);
8557 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8558 SSLConfigService::SetCRLSet(
8559 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8561 CertStatus cert_status;
8562 DoConnection(ssl_options, &cert_status);
8564 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8565 cert_status & CERT_STATUS_ALL_ERRORS);
8567 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8568 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8569 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8572 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8573 if (!SystemSupportsOCSP()) {
8574 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8575 return;
8578 SpawnedTestServer::SSLOptions ssl_options(
8579 SpawnedTestServer::SSLOptions::CERT_AUTO);
8580 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8581 SSLConfigService::SetCRLSet(
8582 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8583 false, &kOCSPTestCertSPKI, "")));
8585 CertStatus cert_status;
8586 DoConnection(ssl_options, &cert_status);
8588 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8589 // revocation check for EV.
8590 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8591 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8592 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8593 EXPECT_FALSE(
8594 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8597 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8598 if (!SystemSupportsOCSP()) {
8599 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8600 return;
8603 SpawnedTestServer::SSLOptions ssl_options(
8604 SpawnedTestServer::SSLOptions::CERT_AUTO);
8605 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8606 SSLConfigService::SetCRLSet(
8607 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8609 CertStatus cert_status = 0;
8610 DoConnection(ssl_options, &cert_status);
8612 // Even with a fresh CRLSet, we should still do online revocation checks when
8613 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8614 // test.
8615 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8616 cert_status & CERT_STATUS_ALL_ERRORS);
8618 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8619 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8620 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8623 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8624 // Test that when EV verification is requested, but online revocation
8625 // checking is disabled, and the leaf certificate is not in fact EV, that
8626 // no revocation checking actually happens.
8627 if (!SystemSupportsOCSP()) {
8628 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8629 return;
8632 // Unmark the certificate's OID as EV, which should disable revocation
8633 // checking (as per the user preference)
8634 ev_test_policy_.reset();
8636 SpawnedTestServer::SSLOptions ssl_options(
8637 SpawnedTestServer::SSLOptions::CERT_AUTO);
8638 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8639 SSLConfigService::SetCRLSet(
8640 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8642 CertStatus cert_status;
8643 DoConnection(ssl_options, &cert_status);
8645 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8647 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8648 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8651 class HTTPSCRLSetTest : public HTTPSOCSPTest {
8652 protected:
8653 void SetupContext(URLRequestContext* context) override {
8654 context->set_ssl_config_service(
8655 new TestSSLConfigService(false /* check for EV */,
8656 false /* online revocation checking */,
8657 false /* require rev. checking for local
8658 anchors */));
8662 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
8663 SpawnedTestServer::SSLOptions ssl_options(
8664 SpawnedTestServer::SSLOptions::CERT_AUTO);
8665 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8666 SSLConfigService::SetCRLSet(
8667 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8669 CertStatus cert_status;
8670 DoConnection(ssl_options, &cert_status);
8672 // If we're not trying EV verification then, even if the CRLSet has expired,
8673 // we don't fall back to online revocation checks.
8674 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8675 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8676 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8679 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
8680 #if defined(OS_ANDROID)
8681 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8682 return;
8683 #endif
8685 SpawnedTestServer::SSLOptions ssl_options(
8686 SpawnedTestServer::SSLOptions::CERT_AUTO);
8687 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8688 ssl_options.cert_serial = 10;
8689 SSLConfigService::SetCRLSet(
8690 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8691 false, &kOCSPTestCertSPKI, "\x0a")));
8693 CertStatus cert_status = 0;
8694 DoConnection(ssl_options, &cert_status);
8696 // If the certificate is recorded as revoked in the CRLSet, that should be
8697 // reflected without online revocation checking.
8698 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8699 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8700 EXPECT_FALSE(
8701 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8703 #endif // !defined(OS_IOS)
8705 #if !defined(DISABLE_FTP_SUPPORT)
8706 class URLRequestTestFTP : public URLRequestTest {
8707 public:
8708 URLRequestTestFTP()
8709 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
8710 base::FilePath()) {
8713 protected:
8714 SpawnedTestServer test_server_;
8717 // Make sure an FTP request using an unsafe ports fails.
8718 TEST_F(URLRequestTestFTP, UnsafePort) {
8719 ASSERT_TRUE(test_server_.Start());
8721 URLRequestJobFactoryImpl job_factory;
8722 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
8724 GURL url("ftp://127.0.0.1:7");
8725 job_factory.SetProtocolHandler(
8726 "ftp",
8727 new FtpProtocolHandler(&ftp_transaction_factory));
8728 default_context_.set_job_factory(&job_factory);
8730 TestDelegate d;
8732 scoped_ptr<URLRequest> r(
8733 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
8734 r->Start();
8735 EXPECT_TRUE(r->is_pending());
8737 base::RunLoop().Run();
8739 EXPECT_FALSE(r->is_pending());
8740 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8741 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
8745 // Flaky, see http://crbug.com/25045.
8746 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
8747 ASSERT_TRUE(test_server_.Start());
8749 TestDelegate d;
8751 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8752 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
8753 r->Start();
8754 EXPECT_TRUE(r->is_pending());
8756 base::RunLoop().Run();
8758 EXPECT_FALSE(r->is_pending());
8759 EXPECT_EQ(1, d.response_started_count());
8760 EXPECT_FALSE(d.received_data_before_response());
8761 EXPECT_LT(0, d.bytes_received());
8762 EXPECT_EQ(test_server_.host_port_pair().host(),
8763 r->GetSocketAddress().host());
8764 EXPECT_EQ(test_server_.host_port_pair().port(),
8765 r->GetSocketAddress().port());
8769 // Flaky, see http://crbug.com/25045.
8770 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
8771 ASSERT_TRUE(test_server_.Start());
8773 base::FilePath app_path;
8774 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8775 app_path = app_path.AppendASCII("LICENSE");
8776 TestDelegate d;
8778 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8779 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d));
8780 r->Start();
8781 EXPECT_TRUE(r->is_pending());
8783 base::RunLoop().Run();
8785 int64 file_size = 0;
8786 base::GetFileSize(app_path, &file_size);
8788 EXPECT_FALSE(r->is_pending());
8789 EXPECT_EQ(1, d.response_started_count());
8790 EXPECT_FALSE(d.received_data_before_response());
8791 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8792 EXPECT_EQ(test_server_.host_port_pair().host(),
8793 r->GetSocketAddress().host());
8794 EXPECT_EQ(test_server_.host_port_pair().port(),
8795 r->GetSocketAddress().port());
8799 // Flaky, see http://crbug.com/25045.
8800 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
8801 ASSERT_TRUE(test_server_.Start());
8803 base::FilePath app_path;
8804 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8805 app_path = app_path.AppendASCII("LICENSE");
8806 TestDelegate d;
8808 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8809 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8810 DEFAULT_PRIORITY, &d));
8811 r->Start();
8812 EXPECT_TRUE(r->is_pending());
8814 base::RunLoop().Run();
8816 int64 file_size = 0;
8817 base::GetFileSize(app_path, &file_size);
8819 EXPECT_FALSE(r->is_pending());
8820 EXPECT_EQ(test_server_.host_port_pair().host(),
8821 r->GetSocketAddress().host());
8822 EXPECT_EQ(test_server_.host_port_pair().port(),
8823 r->GetSocketAddress().port());
8824 EXPECT_EQ(1, d.response_started_count());
8825 EXPECT_FALSE(d.received_data_before_response());
8826 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8828 LoadTimingInfo load_timing_info;
8829 r->GetLoadTimingInfo(&load_timing_info);
8830 TestLoadTimingNoHttpResponse(load_timing_info);
8834 // Flaky, see http://crbug.com/25045.
8835 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
8836 ASSERT_TRUE(test_server_.Start());
8838 base::FilePath app_path;
8839 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8840 app_path = app_path.AppendASCII("LICENSE");
8841 TestDelegate d;
8843 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8844 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8845 "wrong_password"),
8846 DEFAULT_PRIORITY, &d));
8847 r->Start();
8848 EXPECT_TRUE(r->is_pending());
8850 base::RunLoop().Run();
8852 int64 file_size = 0;
8853 base::GetFileSize(app_path, &file_size);
8855 EXPECT_FALSE(r->is_pending());
8856 EXPECT_EQ(1, d.response_started_count());
8857 EXPECT_FALSE(d.received_data_before_response());
8858 EXPECT_EQ(d.bytes_received(), 0);
8862 // Flaky, see http://crbug.com/25045.
8863 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
8864 ASSERT_TRUE(test_server_.Start());
8866 base::FilePath app_path;
8867 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8868 app_path = app_path.AppendASCII("LICENSE");
8869 TestDelegate d;
8870 // Set correct login credentials. The delegate will be asked for them when
8871 // the initial login with wrong credentials will fail.
8872 d.set_credentials(AuthCredentials(kChrome, kChrome));
8874 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8875 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8876 "wrong_password"),
8877 DEFAULT_PRIORITY, &d));
8878 r->Start();
8879 EXPECT_TRUE(r->is_pending());
8881 base::RunLoop().Run();
8883 int64 file_size = 0;
8884 base::GetFileSize(app_path, &file_size);
8886 EXPECT_FALSE(r->is_pending());
8887 EXPECT_EQ(1, d.response_started_count());
8888 EXPECT_FALSE(d.received_data_before_response());
8889 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8893 // Flaky, see http://crbug.com/25045.
8894 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
8895 ASSERT_TRUE(test_server_.Start());
8897 base::FilePath app_path;
8898 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8899 app_path = app_path.AppendASCII("LICENSE");
8900 TestDelegate d;
8902 scoped_ptr<URLRequest> r(
8903 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8904 "/LICENSE", "wrong_user", "chrome"),
8905 DEFAULT_PRIORITY, &d));
8906 r->Start();
8907 EXPECT_TRUE(r->is_pending());
8909 base::RunLoop().Run();
8911 int64 file_size = 0;
8912 base::GetFileSize(app_path, &file_size);
8914 EXPECT_FALSE(r->is_pending());
8915 EXPECT_EQ(1, d.response_started_count());
8916 EXPECT_FALSE(d.received_data_before_response());
8917 EXPECT_EQ(d.bytes_received(), 0);
8921 // Flaky, see http://crbug.com/25045.
8922 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
8923 ASSERT_TRUE(test_server_.Start());
8925 base::FilePath app_path;
8926 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8927 app_path = app_path.AppendASCII("LICENSE");
8928 TestDelegate d;
8929 // Set correct login credentials. The delegate will be asked for them when
8930 // the initial login with wrong credentials will fail.
8931 d.set_credentials(AuthCredentials(kChrome, kChrome));
8933 scoped_ptr<URLRequest> r(
8934 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8935 "/LICENSE", "wrong_user", "chrome"),
8936 DEFAULT_PRIORITY, &d));
8937 r->Start();
8938 EXPECT_TRUE(r->is_pending());
8940 base::RunLoop().Run();
8942 int64 file_size = 0;
8943 base::GetFileSize(app_path, &file_size);
8945 EXPECT_FALSE(r->is_pending());
8946 EXPECT_EQ(1, d.response_started_count());
8947 EXPECT_FALSE(d.received_data_before_response());
8948 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8952 // Flaky, see http://crbug.com/25045.
8953 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
8954 ASSERT_TRUE(test_server_.Start());
8956 base::FilePath app_path;
8957 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8958 app_path = app_path.AppendASCII("LICENSE");
8960 scoped_ptr<TestDelegate> d(new TestDelegate);
8962 // Pass correct login identity in the URL.
8963 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8964 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8965 DEFAULT_PRIORITY, d.get()));
8966 r->Start();
8967 EXPECT_TRUE(r->is_pending());
8969 base::RunLoop().Run();
8971 int64 file_size = 0;
8972 base::GetFileSize(app_path, &file_size);
8974 EXPECT_FALSE(r->is_pending());
8975 EXPECT_EQ(1, d->response_started_count());
8976 EXPECT_FALSE(d->received_data_before_response());
8977 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8980 d.reset(new TestDelegate);
8982 // This request should use cached identity from previous request.
8983 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8984 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
8985 r->Start();
8986 EXPECT_TRUE(r->is_pending());
8988 base::RunLoop().Run();
8990 int64 file_size = 0;
8991 base::GetFileSize(app_path, &file_size);
8993 EXPECT_FALSE(r->is_pending());
8994 EXPECT_EQ(1, d->response_started_count());
8995 EXPECT_FALSE(d->received_data_before_response());
8996 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9000 // Flaky, see http://crbug.com/25045.
9001 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
9002 ASSERT_TRUE(test_server_.Start());
9004 base::FilePath app_path;
9005 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9006 app_path = app_path.AppendASCII("LICENSE");
9008 scoped_ptr<TestDelegate> d(new TestDelegate);
9009 // Set correct login credentials. The delegate will be asked for them when
9010 // the initial login with wrong credentials will fail.
9011 d->set_credentials(AuthCredentials(kChrome, kChrome));
9013 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9014 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
9015 "wrong_password"),
9016 DEFAULT_PRIORITY, d.get()));
9017 r->Start();
9018 EXPECT_TRUE(r->is_pending());
9020 base::RunLoop().Run();
9022 int64 file_size = 0;
9023 base::GetFileSize(app_path, &file_size);
9025 EXPECT_FALSE(r->is_pending());
9026 EXPECT_EQ(1, d->response_started_count());
9027 EXPECT_FALSE(d->received_data_before_response());
9028 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9031 // Use a new delegate without explicit credentials. The cached ones should be
9032 // used.
9033 d.reset(new TestDelegate);
9035 // Don't pass wrong credentials in the URL, they would override valid cached
9036 // ones.
9037 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9038 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
9039 r->Start();
9040 EXPECT_TRUE(r->is_pending());
9042 base::RunLoop().Run();
9044 int64 file_size = 0;
9045 base::GetFileSize(app_path, &file_size);
9047 EXPECT_FALSE(r->is_pending());
9048 EXPECT_EQ(1, d->response_started_count());
9049 EXPECT_FALSE(d->received_data_before_response());
9050 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9053 #endif // !defined(DISABLE_FTP_SUPPORT)
9055 } // namespace net