Disable signin-to-Chrome when using Guest profile.
[chromium-blink-merge.git] / net / url_request / url_request_unittest.cc
blobb85da781e14b8d56ef6f25eb3efefb4e64345256
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "build/build_config.h"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shlobj.h>
10 #endif
12 #include <algorithm>
13 #include <string>
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/format_macros.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/message_loop/message_loop.h"
23 #include "base/message_loop/message_loop_proxy.h"
24 #include "base/path_service.h"
25 #include "base/run_loop.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/stringprintf.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "net/base/capturing_net_log.h"
33 #include "net/base/load_flags.h"
34 #include "net/base/load_timing_info.h"
35 #include "net/base/load_timing_info_test_util.h"
36 #include "net/base/net_errors.h"
37 #include "net/base/net_log.h"
38 #include "net/base/net_log_unittest.h"
39 #include "net/base/net_module.h"
40 #include "net/base/net_util.h"
41 #include "net/base/request_priority.h"
42 #include "net/base/test_data_directory.h"
43 #include "net/base/upload_bytes_element_reader.h"
44 #include "net/base/upload_data_stream.h"
45 #include "net/base/upload_file_element_reader.h"
46 #include "net/cert/ev_root_ca_metadata.h"
47 #include "net/cert/mock_cert_verifier.h"
48 #include "net/cert/test_root_certs.h"
49 #include "net/cookies/cookie_monster.h"
50 #include "net/cookies/cookie_store_test_helpers.h"
51 #include "net/disk_cache/disk_cache.h"
52 #include "net/dns/mock_host_resolver.h"
53 #include "net/ftp/ftp_network_layer.h"
54 #include "net/http/http_byte_range.h"
55 #include "net/http/http_cache.h"
56 #include "net/http/http_network_layer.h"
57 #include "net/http/http_network_session.h"
58 #include "net/http/http_request_headers.h"
59 #include "net/http/http_response_headers.h"
60 #include "net/ocsp/nss_ocsp.h"
61 #include "net/proxy/proxy_service.h"
62 #include "net/socket/ssl_client_socket.h"
63 #include "net/ssl/ssl_connection_status_flags.h"
64 #include "net/test/cert_test_util.h"
65 #include "net/test/spawned_test_server/spawned_test_server.h"
66 #include "net/url_request/data_protocol_handler.h"
67 #include "net/url_request/file_protocol_handler.h"
68 #include "net/url_request/ftp_protocol_handler.h"
69 #include "net/url_request/static_http_user_agent_settings.h"
70 #include "net/url_request/url_request.h"
71 #include "net/url_request/url_request_file_dir_job.h"
72 #include "net/url_request/url_request_http_job.h"
73 #include "net/url_request/url_request_job_factory_impl.h"
74 #include "net/url_request/url_request_redirect_job.h"
75 #include "net/url_request/url_request_test_job.h"
76 #include "net/url_request/url_request_test_util.h"
77 #include "testing/gtest/include/gtest/gtest.h"
78 #include "testing/platform_test.h"
80 #if defined(OS_WIN)
81 #include "base/win/scoped_com_initializer.h"
82 #include "base/win/scoped_comptr.h"
83 #include "base/win/windows_version.h"
84 #endif
86 using base::ASCIIToUTF16;
87 using base::Time;
89 namespace net {
91 namespace {
93 const base::string16 kChrome(ASCIIToUTF16("chrome"));
94 const base::string16 kSecret(ASCIIToUTF16("secret"));
95 const base::string16 kUser(ASCIIToUTF16("user"));
97 // Tests load timing information in the case a fresh connection was used, with
98 // no proxy.
99 void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
100 int connect_timing_flags) {
101 EXPECT_FALSE(load_timing_info.socket_reused);
102 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
104 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
105 EXPECT_FALSE(load_timing_info.request_start.is_null());
107 EXPECT_LE(load_timing_info.request_start,
108 load_timing_info.connect_timing.connect_start);
109 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
110 connect_timing_flags);
111 EXPECT_LE(load_timing_info.connect_timing.connect_end,
112 load_timing_info.send_start);
113 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
114 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
116 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
117 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
120 // Same as above, but with proxy times.
121 void TestLoadTimingNotReusedWithProxy(
122 const net::LoadTimingInfo& load_timing_info,
123 int connect_timing_flags) {
124 EXPECT_FALSE(load_timing_info.socket_reused);
125 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
127 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
128 EXPECT_FALSE(load_timing_info.request_start.is_null());
130 EXPECT_LE(load_timing_info.request_start,
131 load_timing_info.proxy_resolve_start);
132 EXPECT_LE(load_timing_info.proxy_resolve_start,
133 load_timing_info.proxy_resolve_end);
134 EXPECT_LE(load_timing_info.proxy_resolve_end,
135 load_timing_info.connect_timing.connect_start);
136 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
137 connect_timing_flags);
138 EXPECT_LE(load_timing_info.connect_timing.connect_end,
139 load_timing_info.send_start);
140 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
141 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
144 // Same as above, but with a reused socket and proxy times.
145 void TestLoadTimingReusedWithProxy(
146 const net::LoadTimingInfo& load_timing_info) {
147 EXPECT_TRUE(load_timing_info.socket_reused);
148 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
150 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
151 EXPECT_FALSE(load_timing_info.request_start.is_null());
153 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
155 EXPECT_LE(load_timing_info.request_start,
156 load_timing_info.proxy_resolve_start);
157 EXPECT_LE(load_timing_info.proxy_resolve_start,
158 load_timing_info.proxy_resolve_end);
159 EXPECT_LE(load_timing_info.proxy_resolve_end,
160 load_timing_info.send_start);
161 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
162 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
165 // Tests load timing information in the case of a cache hit, when no cache
166 // validation request was sent over the wire.
167 base::StringPiece TestNetResourceProvider(int key) {
168 return "header";
171 void FillBuffer(char* buffer, size_t len) {
172 static bool called = false;
173 if (!called) {
174 called = true;
175 int seed = static_cast<int>(Time::Now().ToInternalValue());
176 srand(seed);
179 for (size_t i = 0; i < len; i++) {
180 buffer[i] = static_cast<char>(rand());
181 if (!buffer[i])
182 buffer[i] = 'g';
186 #if !defined(OS_IOS)
187 void TestLoadTimingCacheHitNoNetwork(
188 const net::LoadTimingInfo& load_timing_info) {
189 EXPECT_FALSE(load_timing_info.socket_reused);
190 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
192 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
193 EXPECT_FALSE(load_timing_info.request_start.is_null());
195 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
196 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
197 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
198 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
200 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
201 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
204 // Tests load timing in the case that there is no HTTP response. This can be
205 // used to test in the case of errors or non-HTTP requests.
206 void TestLoadTimingNoHttpResponse(
207 const net::LoadTimingInfo& load_timing_info) {
208 EXPECT_FALSE(load_timing_info.socket_reused);
209 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
211 // Only the request times should be non-null.
212 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
213 EXPECT_FALSE(load_timing_info.request_start.is_null());
215 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
217 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
218 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
219 EXPECT_TRUE(load_timing_info.send_start.is_null());
220 EXPECT_TRUE(load_timing_info.send_end.is_null());
221 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
224 // Do a case-insensitive search through |haystack| for |needle|.
225 bool ContainsString(const std::string& haystack, const char* needle) {
226 std::string::const_iterator it =
227 std::search(haystack.begin(),
228 haystack.end(),
229 needle,
230 needle + strlen(needle),
231 base::CaseInsensitiveCompare<char>());
232 return it != haystack.end();
235 UploadDataStream* CreateSimpleUploadData(const char* data) {
236 scoped_ptr<UploadElementReader> reader(
237 new UploadBytesElementReader(data, strlen(data)));
238 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
241 // Verify that the SSLInfo of a successful SSL connection has valid values.
242 void CheckSSLInfo(const SSLInfo& ssl_info) {
243 // -1 means unknown. 0 means no encryption.
244 EXPECT_GT(ssl_info.security_bits, 0);
246 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
247 int cipher_suite = SSLConnectionStatusToCipherSuite(
248 ssl_info.connection_status);
249 EXPECT_NE(0, cipher_suite);
252 void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
253 const GURL& host_url) {
254 std::string sent_value;
256 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
257 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
259 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
260 EXPECT_EQ("keep-alive", sent_value);
263 bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
264 size_t size = a.size();
266 if (size != b.size())
267 return false;
269 for (size_t i = 0; i < size; ++i) {
270 if (!a[i].Equals(b[i]))
271 return false;
274 return true;
276 #endif // !defined(OS_IOS)
278 // A network delegate that allows the user to choose a subset of request stages
279 // to block in. When blocking, the delegate can do one of the following:
280 // * synchronously return a pre-specified error code, or
281 // * asynchronously return that value via an automatically called callback,
282 // or
283 // * block and wait for the user to do a callback.
284 // Additionally, the user may also specify a redirect URL -- then each request
285 // with the current URL different from the redirect target will be redirected
286 // to that target, in the on-before-URL-request stage, independent of whether
287 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
288 class BlockingNetworkDelegate : public TestNetworkDelegate {
289 public:
290 // Stages in which the delegate can block.
291 enum Stage {
292 NOT_BLOCKED = 0,
293 ON_BEFORE_URL_REQUEST = 1 << 0,
294 ON_BEFORE_SEND_HEADERS = 1 << 1,
295 ON_HEADERS_RECEIVED = 1 << 2,
296 ON_AUTH_REQUIRED = 1 << 3
299 // Behavior during blocked stages. During other stages, just
300 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
301 enum BlockMode {
302 SYNCHRONOUS, // No callback, returns specified return values.
303 AUTO_CALLBACK, // |this| posts a task to run the callback using the
304 // specified return codes.
305 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
306 // |auth_retval_| are ignored. In every blocking stage the
307 // message loop is quit.
310 // Creates a delegate which does not block at all.
311 explicit BlockingNetworkDelegate(BlockMode block_mode);
313 // For users to trigger a callback returning |response|.
314 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
315 // Only call if |block_mode_| == USER_CALLBACK.
316 void DoCallback(int response);
317 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
319 // Setters.
320 void set_retval(int retval) {
321 ASSERT_NE(USER_CALLBACK, block_mode_);
322 ASSERT_NE(ERR_IO_PENDING, retval);
323 ASSERT_NE(OK, retval);
324 retval_ = retval;
327 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
328 // |auth_credentials_| will be passed with the response.
329 void set_auth_retval(AuthRequiredResponse auth_retval) {
330 ASSERT_NE(USER_CALLBACK, block_mode_);
331 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
332 auth_retval_ = auth_retval;
334 void set_auth_credentials(const AuthCredentials& auth_credentials) {
335 auth_credentials_ = auth_credentials;
338 void set_redirect_url(const GURL& url) {
339 redirect_url_ = url;
342 void set_block_on(int block_on) {
343 block_on_ = block_on;
346 // Allows the user to check in which state did we block.
347 Stage stage_blocked_for_callback() const {
348 EXPECT_EQ(USER_CALLBACK, block_mode_);
349 return stage_blocked_for_callback_;
352 private:
353 void RunCallback(int response, const CompletionCallback& callback);
354 void RunAuthCallback(AuthRequiredResponse response,
355 const AuthCallback& callback);
357 // TestNetworkDelegate implementation.
358 virtual int OnBeforeURLRequest(URLRequest* request,
359 const CompletionCallback& callback,
360 GURL* new_url) OVERRIDE;
362 virtual int OnBeforeSendHeaders(URLRequest* request,
363 const CompletionCallback& callback,
364 HttpRequestHeaders* headers) OVERRIDE;
366 virtual int OnHeadersReceived(
367 URLRequest* request,
368 const CompletionCallback& callback,
369 const HttpResponseHeaders* original_response_headers,
370 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE;
372 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
373 URLRequest* request,
374 const AuthChallengeInfo& auth_info,
375 const AuthCallback& callback,
376 AuthCredentials* credentials) OVERRIDE;
378 // Resets the callbacks and |stage_blocked_for_callback_|.
379 void Reset();
381 // Checks whether we should block in |stage|. If yes, returns an error code
382 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
383 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
385 // Configuration parameters, can be adjusted by public methods:
386 const BlockMode block_mode_;
388 // Values returned on blocking stages when mode is SYNCHRONOUS or
389 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
390 int retval_; // To be returned in non-auth stages.
391 AuthRequiredResponse auth_retval_;
393 GURL redirect_url_; // Used if non-empty.
394 int block_on_; // Bit mask: in which stages to block.
396 // |auth_credentials_| will be copied to |*target_auth_credential_| on
397 // callback.
398 AuthCredentials auth_credentials_;
399 AuthCredentials* target_auth_credentials_;
401 // Internal variables, not set by not the user:
402 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
403 // USER_CALLBACK).
404 Stage stage_blocked_for_callback_;
406 // Callback objects stored during blocking stages.
407 CompletionCallback callback_;
408 AuthCallback auth_callback_;
410 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
412 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
415 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
416 : block_mode_(block_mode),
417 retval_(OK),
418 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
419 block_on_(0),
420 target_auth_credentials_(NULL),
421 stage_blocked_for_callback_(NOT_BLOCKED),
422 weak_factory_(this) {
425 void BlockingNetworkDelegate::DoCallback(int response) {
426 ASSERT_EQ(USER_CALLBACK, block_mode_);
427 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
428 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
429 CompletionCallback callback = callback_;
430 Reset();
431 RunCallback(response, callback);
434 void BlockingNetworkDelegate::DoAuthCallback(
435 NetworkDelegate::AuthRequiredResponse response) {
436 ASSERT_EQ(USER_CALLBACK, block_mode_);
437 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
438 AuthCallback auth_callback = auth_callback_;
439 Reset();
440 RunAuthCallback(response, auth_callback);
443 void BlockingNetworkDelegate::RunCallback(int response,
444 const CompletionCallback& callback) {
445 callback.Run(response);
448 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
449 const AuthCallback& callback) {
450 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
451 ASSERT_TRUE(target_auth_credentials_ != NULL);
452 *target_auth_credentials_ = auth_credentials_;
454 callback.Run(response);
457 int BlockingNetworkDelegate::OnBeforeURLRequest(
458 URLRequest* request,
459 const CompletionCallback& callback,
460 GURL* new_url) {
461 if (redirect_url_ == request->url())
462 return OK; // We've already seen this request and redirected elsewhere.
464 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
466 if (!redirect_url_.is_empty())
467 *new_url = redirect_url_;
469 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
472 int BlockingNetworkDelegate::OnBeforeSendHeaders(
473 URLRequest* request,
474 const CompletionCallback& callback,
475 HttpRequestHeaders* headers) {
476 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
478 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
481 int BlockingNetworkDelegate::OnHeadersReceived(
482 URLRequest* request,
483 const CompletionCallback& callback,
484 const HttpResponseHeaders* original_response_headers,
485 scoped_refptr<HttpResponseHeaders>* override_response_headers) {
486 TestNetworkDelegate::OnHeadersReceived(
487 request, callback, original_response_headers,
488 override_response_headers);
490 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
493 NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
494 URLRequest* request,
495 const AuthChallengeInfo& auth_info,
496 const AuthCallback& callback,
497 AuthCredentials* credentials) {
498 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
499 credentials);
500 // Check that the user has provided callback for the previous blocked stage.
501 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
503 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
504 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
507 target_auth_credentials_ = credentials;
509 switch (block_mode_) {
510 case SYNCHRONOUS:
511 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
512 *target_auth_credentials_ = auth_credentials_;
513 return auth_retval_;
515 case AUTO_CALLBACK:
516 base::MessageLoop::current()->PostTask(
517 FROM_HERE,
518 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
519 weak_factory_.GetWeakPtr(), auth_retval_, callback));
520 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
522 case USER_CALLBACK:
523 auth_callback_ = callback;
524 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
525 base::MessageLoop::current()->PostTask(FROM_HERE,
526 base::MessageLoop::QuitClosure());
527 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
529 NOTREACHED();
530 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
533 void BlockingNetworkDelegate::Reset() {
534 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
535 stage_blocked_for_callback_ = NOT_BLOCKED;
536 callback_.Reset();
537 auth_callback_.Reset();
540 int BlockingNetworkDelegate::MaybeBlockStage(
541 BlockingNetworkDelegate::Stage stage,
542 const CompletionCallback& callback) {
543 // Check that the user has provided callback for the previous blocked stage.
544 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
546 if ((block_on_ & stage) == 0) {
547 return OK;
550 switch (block_mode_) {
551 case SYNCHRONOUS:
552 EXPECT_NE(OK, retval_);
553 return retval_;
555 case AUTO_CALLBACK:
556 base::MessageLoop::current()->PostTask(
557 FROM_HERE,
558 base::Bind(&BlockingNetworkDelegate::RunCallback,
559 weak_factory_.GetWeakPtr(), retval_, callback));
560 return ERR_IO_PENDING;
562 case USER_CALLBACK:
563 callback_ = callback;
564 stage_blocked_for_callback_ = stage;
565 base::MessageLoop::current()->PostTask(FROM_HERE,
566 base::MessageLoop::QuitClosure());
567 return ERR_IO_PENDING;
569 NOTREACHED();
570 return 0;
573 class TestURLRequestContextWithProxy : public TestURLRequestContext {
574 public:
575 // Does not own |delegate|.
576 TestURLRequestContextWithProxy(const std::string& proxy,
577 NetworkDelegate* delegate)
578 : TestURLRequestContext(true) {
579 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
580 set_network_delegate(delegate);
581 Init();
583 virtual ~TestURLRequestContextWithProxy() {}
586 } // namespace
588 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
589 class URLRequestTest : public PlatformTest {
590 public:
591 URLRequestTest() : default_context_(true) {
592 default_context_.set_network_delegate(&default_network_delegate_);
593 default_context_.set_net_log(&net_log_);
594 job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
595 job_factory_.SetProtocolHandler(
596 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
597 default_context_.set_job_factory(&job_factory_);
598 default_context_.Init();
600 virtual ~URLRequestTest() {
601 // URLRequestJobs may post clean-up tasks on destruction.
602 base::RunLoop().RunUntilIdle();
605 // Adds the TestJobInterceptor to the default context.
606 TestJobInterceptor* AddTestInterceptor() {
607 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
608 job_factory_.SetProtocolHandler("http", NULL);
609 job_factory_.SetProtocolHandler("http", protocol_handler_);
610 return protocol_handler_;
613 protected:
614 CapturingNetLog net_log_;
615 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
616 URLRequestJobFactoryImpl job_factory_;
617 TestURLRequestContext default_context_;
620 TEST_F(URLRequestTest, AboutBlankTest) {
621 TestDelegate d;
623 URLRequest r(GURL("about:blank"), DEFAULT_PRIORITY, &d, &default_context_);
625 r.Start();
626 EXPECT_TRUE(r.is_pending());
628 base::RunLoop().Run();
630 EXPECT_TRUE(!r.is_pending());
631 EXPECT_FALSE(d.received_data_before_response());
632 EXPECT_EQ(d.bytes_received(), 0);
633 EXPECT_EQ("", r.GetSocketAddress().host());
634 EXPECT_EQ(0, r.GetSocketAddress().port());
636 HttpRequestHeaders headers;
637 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
641 TEST_F(URLRequestTest, DataURLImageTest) {
642 TestDelegate d;
644 // Use our nice little Chrome logo.
645 URLRequest r(
646 GURL(
647 "data:image/png;base64,"
648 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
649 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
650 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
651 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
652 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
653 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
654 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
655 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
656 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
657 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
658 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
659 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
660 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
661 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
662 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
663 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
664 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
665 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
666 DEFAULT_PRIORITY,
668 &default_context_);
670 r.Start();
671 EXPECT_TRUE(r.is_pending());
673 base::RunLoop().Run();
675 EXPECT_TRUE(!r.is_pending());
676 EXPECT_FALSE(d.received_data_before_response());
677 EXPECT_EQ(d.bytes_received(), 911);
678 EXPECT_EQ("", r.GetSocketAddress().host());
679 EXPECT_EQ(0, r.GetSocketAddress().port());
681 HttpRequestHeaders headers;
682 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
686 TEST_F(URLRequestTest, FileTest) {
687 base::FilePath app_path;
688 PathService::Get(base::FILE_EXE, &app_path);
689 GURL app_url = FilePathToFileURL(app_path);
691 TestDelegate d;
693 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
695 r.Start();
696 EXPECT_TRUE(r.is_pending());
698 base::RunLoop().Run();
700 int64 file_size = -1;
701 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
703 EXPECT_TRUE(!r.is_pending());
704 EXPECT_EQ(1, d.response_started_count());
705 EXPECT_FALSE(d.received_data_before_response());
706 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
707 EXPECT_EQ("", r.GetSocketAddress().host());
708 EXPECT_EQ(0, r.GetSocketAddress().port());
710 HttpRequestHeaders headers;
711 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
715 TEST_F(URLRequestTest, FileTestCancel) {
716 base::FilePath app_path;
717 PathService::Get(base::FILE_EXE, &app_path);
718 GURL app_url = FilePathToFileURL(app_path);
720 TestDelegate d;
722 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
724 r.Start();
725 EXPECT_TRUE(r.is_pending());
726 r.Cancel();
728 // Async cancellation should be safe even when URLRequest has been already
729 // destroyed.
730 base::RunLoop().RunUntilIdle();
733 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
734 const size_t buffer_size = 4000;
735 scoped_ptr<char[]> buffer(new char[buffer_size]);
736 FillBuffer(buffer.get(), buffer_size);
738 base::FilePath temp_path;
739 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
740 GURL temp_url = FilePathToFileURL(temp_path);
741 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
743 int64 file_size;
744 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
746 const size_t first_byte_position = 500;
747 const size_t last_byte_position = buffer_size - first_byte_position;
748 const size_t content_length = last_byte_position - first_byte_position + 1;
749 std::string partial_buffer_string(buffer.get() + first_byte_position,
750 buffer.get() + last_byte_position + 1);
752 TestDelegate d;
754 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
756 HttpRequestHeaders headers;
757 headers.SetHeader(
758 HttpRequestHeaders::kRange,
759 net::HttpByteRange::Bounded(
760 first_byte_position, last_byte_position).GetHeaderValue());
761 r.SetExtraRequestHeaders(headers);
762 r.Start();
763 EXPECT_TRUE(r.is_pending());
765 base::RunLoop().Run();
766 EXPECT_TRUE(!r.is_pending());
767 EXPECT_EQ(1, d.response_started_count());
768 EXPECT_FALSE(d.received_data_before_response());
769 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
770 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
771 EXPECT_TRUE(partial_buffer_string == d.data_received());
774 EXPECT_TRUE(base::DeleteFile(temp_path, false));
777 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
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 - 1;
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 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
800 HttpRequestHeaders headers;
801 headers.SetHeader(HttpRequestHeaders::kRange,
802 net::HttpByteRange::RightUnbounded(
803 first_byte_position).GetHeaderValue());
804 r.SetExtraRequestHeaders(headers);
805 r.Start();
806 EXPECT_TRUE(r.is_pending());
808 base::RunLoop().Run();
809 EXPECT_TRUE(!r.is_pending());
810 EXPECT_EQ(1, d.response_started_count());
811 EXPECT_FALSE(d.received_data_before_response());
812 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
813 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
814 EXPECT_TRUE(partial_buffer_string == d.data_received());
817 EXPECT_TRUE(base::DeleteFile(temp_path, false));
820 TEST_F(URLRequestTest, FileTestMultipleRanges) {
821 const size_t buffer_size = 400000;
822 scoped_ptr<char[]> buffer(new char[buffer_size]);
823 FillBuffer(buffer.get(), buffer_size);
825 base::FilePath temp_path;
826 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
827 GURL temp_url = FilePathToFileURL(temp_path);
828 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
830 int64 file_size;
831 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
833 TestDelegate d;
835 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
837 HttpRequestHeaders headers;
838 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
839 r.SetExtraRequestHeaders(headers);
840 r.Start();
841 EXPECT_TRUE(r.is_pending());
843 base::RunLoop().Run();
844 EXPECT_TRUE(d.request_failed());
847 EXPECT_TRUE(base::DeleteFile(temp_path, false));
850 TEST_F(URLRequestTest, AllowFileURLs) {
851 base::ScopedTempDir temp_dir;
852 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
853 base::FilePath test_file;
854 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
855 std::string test_data("monkey");
856 base::WriteFile(test_file, test_data.data(), test_data.size());
857 GURL test_file_url = net::FilePathToFileURL(test_file);
860 TestDelegate d;
861 TestNetworkDelegate network_delegate;
862 network_delegate.set_can_access_files(true);
863 default_context_.set_network_delegate(&network_delegate);
864 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
865 r.Start();
866 base::RunLoop().Run();
867 EXPECT_FALSE(d.request_failed());
868 EXPECT_EQ(test_data, d.data_received());
872 TestDelegate d;
873 TestNetworkDelegate network_delegate;
874 network_delegate.set_can_access_files(false);
875 default_context_.set_network_delegate(&network_delegate);
876 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
877 r.Start();
878 base::RunLoop().Run();
879 EXPECT_TRUE(d.request_failed());
880 EXPECT_EQ("", d.data_received());
884 TEST_F(URLRequestTest, InvalidUrlTest) {
885 TestDelegate d;
887 URLRequest r(GURL("invalid url"), DEFAULT_PRIORITY, &d, &default_context_);
889 r.Start();
890 EXPECT_TRUE(r.is_pending());
892 base::RunLoop().Run();
893 EXPECT_TRUE(d.request_failed());
897 #if defined(OS_WIN)
898 TEST_F(URLRequestTest, ResolveShortcutTest) {
899 base::FilePath app_path;
900 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
901 app_path = app_path.AppendASCII("net");
902 app_path = app_path.AppendASCII("data");
903 app_path = app_path.AppendASCII("url_request_unittest");
904 app_path = app_path.AppendASCII("with-headers.html");
906 std::wstring lnk_path = app_path.value() + L".lnk";
908 base::win::ScopedCOMInitializer com_initializer;
910 // Temporarily create a shortcut for test
912 base::win::ScopedComPtr<IShellLink> shell;
913 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
914 CLSCTX_INPROC_SERVER)));
915 base::win::ScopedComPtr<IPersistFile> persist;
916 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
917 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
918 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
919 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
922 TestDelegate d;
924 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)),
925 DEFAULT_PRIORITY,
927 &default_context_);
929 r.Start();
930 EXPECT_TRUE(r.is_pending());
932 base::RunLoop().Run();
934 WIN32_FILE_ATTRIBUTE_DATA data;
935 GetFileAttributesEx(app_path.value().c_str(),
936 GetFileExInfoStandard, &data);
937 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
938 FILE_SHARE_READ, NULL, OPEN_EXISTING,
939 FILE_ATTRIBUTE_NORMAL, NULL);
940 EXPECT_NE(INVALID_HANDLE_VALUE, file);
941 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
942 DWORD read_size;
943 BOOL result;
944 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
945 &read_size, NULL);
946 std::string content(buffer.get(), read_size);
947 CloseHandle(file);
949 EXPECT_TRUE(!r.is_pending());
950 EXPECT_EQ(1, d.received_redirect_count());
951 EXPECT_EQ(content, d.data_received());
954 // Clean the shortcut
955 DeleteFile(lnk_path.c_str());
957 #endif // defined(OS_WIN)
959 TEST_F(URLRequestTest, FileDirCancelTest) {
960 // Put in mock resource provider.
961 NetModule::SetResourceProvider(TestNetResourceProvider);
963 TestDelegate d;
965 base::FilePath file_path;
966 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
967 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
968 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
970 URLRequest req(
971 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, &default_context_);
972 req.Start();
973 EXPECT_TRUE(req.is_pending());
975 d.set_cancel_in_received_data_pending(true);
977 base::RunLoop().Run();
980 // Take out mock resource provider.
981 NetModule::SetResourceProvider(NULL);
984 TEST_F(URLRequestTest, FileDirOutputSanity) {
985 // Verify the general sanity of the the output of the file:
986 // directory lister by checking for the output of a known existing
987 // file.
988 const char sentinel_name[] = "filedir-sentinel";
990 base::FilePath path;
991 PathService::Get(base::DIR_SOURCE_ROOT, &path);
992 path = path.Append(FILE_PATH_LITERAL("net"));
993 path = path.Append(FILE_PATH_LITERAL("data"));
994 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
996 TestDelegate d;
997 URLRequest req(
998 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
999 req.Start();
1000 base::RunLoop().Run();
1002 // Generate entry for the sentinel file.
1003 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
1004 base::File::Info info;
1005 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
1006 EXPECT_GT(info.size, 0);
1007 std::string sentinel_output = GetDirectoryListingEntry(
1008 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1009 std::string(sentinel_name),
1010 false /* is_dir */,
1011 info.size,
1012 info.last_modified);
1014 ASSERT_LT(0, d.bytes_received());
1015 ASSERT_FALSE(d.request_failed());
1016 ASSERT_TRUE(req.status().is_success());
1017 // Check for the entry generated for the "sentinel" file.
1018 const std::string& data = d.data_received();
1019 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1022 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1023 // There is an implicit redirect when loading a file path that matches a
1024 // directory and does not end with a slash. Ensure that following such
1025 // redirects does not crash. See http://crbug.com/18686.
1027 base::FilePath path;
1028 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1029 path = path.Append(FILE_PATH_LITERAL("net"));
1030 path = path.Append(FILE_PATH_LITERAL("data"));
1031 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1033 TestDelegate d;
1034 URLRequest req(
1035 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
1036 req.Start();
1037 base::RunLoop().Run();
1039 ASSERT_EQ(1, d.received_redirect_count());
1040 ASSERT_LT(0, d.bytes_received());
1041 ASSERT_FALSE(d.request_failed());
1042 ASSERT_TRUE(req.status().is_success());
1045 #if defined(OS_WIN)
1046 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1047 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1048 TestDelegate d;
1049 URLRequest req(GURL("file:///"), DEFAULT_PRIORITY, &d, &default_context_);
1050 req.Start();
1051 base::RunLoop().Run();
1053 ASSERT_EQ(1, d.received_redirect_count());
1054 ASSERT_FALSE(req.status().is_success());
1056 #endif
1058 // Custom URLRequestJobs for use with interceptor tests
1059 class RestartTestJob : public URLRequestTestJob {
1060 public:
1061 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1062 : URLRequestTestJob(request, network_delegate, true) {}
1063 protected:
1064 virtual void StartAsync() OVERRIDE {
1065 this->NotifyRestartRequired();
1067 private:
1068 virtual ~RestartTestJob() {}
1071 class CancelTestJob : public URLRequestTestJob {
1072 public:
1073 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1074 : URLRequestTestJob(request, network_delegate, true) {}
1075 protected:
1076 virtual void StartAsync() OVERRIDE {
1077 request_->Cancel();
1079 private:
1080 virtual ~CancelTestJob() {}
1083 class CancelThenRestartTestJob : public URLRequestTestJob {
1084 public:
1085 explicit CancelThenRestartTestJob(URLRequest* request,
1086 NetworkDelegate* network_delegate)
1087 : URLRequestTestJob(request, network_delegate, true) {
1089 protected:
1090 virtual void StartAsync() OVERRIDE {
1091 request_->Cancel();
1092 this->NotifyRestartRequired();
1094 private:
1095 virtual ~CancelThenRestartTestJob() {}
1098 // An Interceptor for use with interceptor tests
1099 class TestInterceptor : URLRequest::Interceptor {
1100 public:
1101 TestInterceptor()
1102 : intercept_main_request_(false), restart_main_request_(false),
1103 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1104 simulate_main_network_error_(false),
1105 intercept_redirect_(false), cancel_redirect_request_(false),
1106 intercept_final_response_(false), cancel_final_request_(false),
1107 did_intercept_main_(false), did_restart_main_(false),
1108 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1109 did_simulate_error_main_(false),
1110 did_intercept_redirect_(false), did_cancel_redirect_(false),
1111 did_intercept_final_(false), did_cancel_final_(false) {
1112 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1115 virtual ~TestInterceptor() {
1116 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1119 virtual URLRequestJob* MaybeIntercept(
1120 URLRequest* request,
1121 NetworkDelegate* network_delegate) OVERRIDE {
1122 if (restart_main_request_) {
1123 restart_main_request_ = false;
1124 did_restart_main_ = true;
1125 return new RestartTestJob(request, network_delegate);
1127 if (cancel_main_request_) {
1128 cancel_main_request_ = false;
1129 did_cancel_main_ = true;
1130 return new CancelTestJob(request, network_delegate);
1132 if (cancel_then_restart_main_request_) {
1133 cancel_then_restart_main_request_ = false;
1134 did_cancel_then_restart_main_ = true;
1135 return new CancelThenRestartTestJob(request, network_delegate);
1137 if (simulate_main_network_error_) {
1138 simulate_main_network_error_ = false;
1139 did_simulate_error_main_ = true;
1140 // will error since the requeted url is not one of its canned urls
1141 return new URLRequestTestJob(request, network_delegate, true);
1143 if (!intercept_main_request_)
1144 return NULL;
1145 intercept_main_request_ = false;
1146 did_intercept_main_ = true;
1147 URLRequestTestJob* job = new URLRequestTestJob(request,
1148 network_delegate,
1149 main_headers_,
1150 main_data_,
1151 true);
1152 job->set_load_timing_info(main_request_load_timing_info_);
1153 return job;
1156 virtual URLRequestJob* MaybeInterceptRedirect(
1157 URLRequest* request,
1158 NetworkDelegate* network_delegate,
1159 const GURL& location) OVERRIDE {
1160 if (cancel_redirect_request_) {
1161 cancel_redirect_request_ = false;
1162 did_cancel_redirect_ = true;
1163 return new CancelTestJob(request, network_delegate);
1165 if (!intercept_redirect_)
1166 return NULL;
1167 intercept_redirect_ = false;
1168 did_intercept_redirect_ = true;
1169 return new URLRequestTestJob(request,
1170 network_delegate,
1171 redirect_headers_,
1172 redirect_data_,
1173 true);
1176 virtual URLRequestJob* MaybeInterceptResponse(
1177 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
1178 if (cancel_final_request_) {
1179 cancel_final_request_ = false;
1180 did_cancel_final_ = true;
1181 return new CancelTestJob(request, network_delegate);
1183 if (!intercept_final_response_)
1184 return NULL;
1185 intercept_final_response_ = false;
1186 did_intercept_final_ = true;
1187 return new URLRequestTestJob(request,
1188 network_delegate,
1189 final_headers_,
1190 final_data_,
1191 true);
1194 // Whether to intercept the main request, and if so the response to return and
1195 // the LoadTimingInfo to use.
1196 bool intercept_main_request_;
1197 std::string main_headers_;
1198 std::string main_data_;
1199 LoadTimingInfo main_request_load_timing_info_;
1201 // Other actions we take at MaybeIntercept time
1202 bool restart_main_request_;
1203 bool cancel_main_request_;
1204 bool cancel_then_restart_main_request_;
1205 bool simulate_main_network_error_;
1207 // Whether to intercept redirects, and if so the response to return.
1208 bool intercept_redirect_;
1209 std::string redirect_headers_;
1210 std::string redirect_data_;
1212 // Other actions we can take at MaybeInterceptRedirect time
1213 bool cancel_redirect_request_;
1215 // Whether to intercept final response, and if so the response to return.
1216 bool intercept_final_response_;
1217 std::string final_headers_;
1218 std::string final_data_;
1220 // Other actions we can take at MaybeInterceptResponse time
1221 bool cancel_final_request_;
1223 // If we did something or not
1224 bool did_intercept_main_;
1225 bool did_restart_main_;
1226 bool did_cancel_main_;
1227 bool did_cancel_then_restart_main_;
1228 bool did_simulate_error_main_;
1229 bool did_intercept_redirect_;
1230 bool did_cancel_redirect_;
1231 bool did_intercept_final_;
1232 bool did_cancel_final_;
1234 // Static getters for canned response header and data strings
1236 static std::string ok_data() {
1237 return URLRequestTestJob::test_data_1();
1240 static std::string ok_headers() {
1241 return URLRequestTestJob::test_headers();
1244 static std::string redirect_data() {
1245 return std::string();
1248 static std::string redirect_headers() {
1249 return URLRequestTestJob::test_redirect_headers();
1252 static std::string error_data() {
1253 return std::string("ohhh nooooo mr. bill!");
1256 static std::string error_headers() {
1257 return URLRequestTestJob::test_error_headers();
1261 TEST_F(URLRequestTest, Intercept) {
1262 TestInterceptor interceptor;
1264 // intercept the main request and respond with a simple response
1265 interceptor.intercept_main_request_ = true;
1266 interceptor.main_headers_ = TestInterceptor::ok_headers();
1267 interceptor.main_data_ = TestInterceptor::ok_data();
1269 TestDelegate d;
1270 URLRequest req(GURL("http://test_intercept/foo"),
1271 DEFAULT_PRIORITY,
1273 &default_context_);
1274 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1275 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1276 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1277 req.SetUserData(NULL, user_data0);
1278 req.SetUserData(&user_data1, user_data1);
1279 req.SetUserData(&user_data2, user_data2);
1280 req.set_method("GET");
1281 req.Start();
1282 base::RunLoop().Run();
1284 // Make sure we can retrieve our specific user data
1285 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1286 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1287 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1289 // Check the interceptor got called as expected
1290 EXPECT_TRUE(interceptor.did_intercept_main_);
1292 // Check we got one good response
1293 EXPECT_TRUE(req.status().is_success());
1294 EXPECT_EQ(200, req.response_headers()->response_code());
1295 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1296 EXPECT_EQ(1, d.response_started_count());
1297 EXPECT_EQ(0, d.received_redirect_count());
1300 TEST_F(URLRequestTest, InterceptRedirect) {
1301 TestInterceptor interceptor;
1303 // intercept the main request and respond with a redirect
1304 interceptor.intercept_main_request_ = true;
1305 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1306 interceptor.main_data_ = TestInterceptor::redirect_data();
1308 // intercept that redirect and respond a final OK response
1309 interceptor.intercept_redirect_ = true;
1310 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1311 interceptor.redirect_data_ = TestInterceptor::ok_data();
1313 TestDelegate d;
1314 URLRequest req(GURL("http://test_intercept/foo"),
1315 DEFAULT_PRIORITY,
1317 &default_context_);
1318 req.set_method("GET");
1319 req.Start();
1320 base::RunLoop().Run();
1322 // Check the interceptor got called as expected
1323 EXPECT_TRUE(interceptor.did_intercept_main_);
1324 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1326 // Check we got one good response
1327 EXPECT_TRUE(req.status().is_success());
1328 if (req.status().is_success()) {
1329 EXPECT_EQ(200, req.response_headers()->response_code());
1331 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1332 EXPECT_EQ(1, d.response_started_count());
1333 EXPECT_EQ(0, d.received_redirect_count());
1336 TEST_F(URLRequestTest, InterceptServerError) {
1337 TestInterceptor interceptor;
1339 // intercept the main request to generate a server error response
1340 interceptor.intercept_main_request_ = true;
1341 interceptor.main_headers_ = TestInterceptor::error_headers();
1342 interceptor.main_data_ = TestInterceptor::error_data();
1344 // intercept that error and respond with an OK response
1345 interceptor.intercept_final_response_ = true;
1346 interceptor.final_headers_ = TestInterceptor::ok_headers();
1347 interceptor.final_data_ = TestInterceptor::ok_data();
1349 TestDelegate d;
1350 URLRequest req(GURL("http://test_intercept/foo"),
1351 DEFAULT_PRIORITY,
1353 &default_context_);
1354 req.set_method("GET");
1355 req.Start();
1356 base::RunLoop().Run();
1358 // Check the interceptor got called as expected
1359 EXPECT_TRUE(interceptor.did_intercept_main_);
1360 EXPECT_TRUE(interceptor.did_intercept_final_);
1362 // Check we got one good response
1363 EXPECT_TRUE(req.status().is_success());
1364 EXPECT_EQ(200, req.response_headers()->response_code());
1365 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1366 EXPECT_EQ(1, d.response_started_count());
1367 EXPECT_EQ(0, d.received_redirect_count());
1370 TEST_F(URLRequestTest, InterceptNetworkError) {
1371 TestInterceptor interceptor;
1373 // intercept the main request to simulate a network error
1374 interceptor.simulate_main_network_error_ = true;
1376 // intercept that error and respond with an OK response
1377 interceptor.intercept_final_response_ = true;
1378 interceptor.final_headers_ = TestInterceptor::ok_headers();
1379 interceptor.final_data_ = TestInterceptor::ok_data();
1381 TestDelegate d;
1382 URLRequest req(GURL("http://test_intercept/foo"),
1383 DEFAULT_PRIORITY,
1385 &default_context_);
1386 req.set_method("GET");
1387 req.Start();
1388 base::RunLoop().Run();
1390 // Check the interceptor got called as expected
1391 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1392 EXPECT_TRUE(interceptor.did_intercept_final_);
1394 // Check we received one good response
1395 EXPECT_TRUE(req.status().is_success());
1396 EXPECT_EQ(200, req.response_headers()->response_code());
1397 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1398 EXPECT_EQ(1, d.response_started_count());
1399 EXPECT_EQ(0, d.received_redirect_count());
1402 TEST_F(URLRequestTest, InterceptRestartRequired) {
1403 TestInterceptor interceptor;
1405 // restart the main request
1406 interceptor.restart_main_request_ = true;
1408 // then intercept the new main request and respond with an OK response
1409 interceptor.intercept_main_request_ = true;
1410 interceptor.main_headers_ = TestInterceptor::ok_headers();
1411 interceptor.main_data_ = TestInterceptor::ok_data();
1413 TestDelegate d;
1414 URLRequest req(GURL("http://test_intercept/foo"),
1415 DEFAULT_PRIORITY,
1417 &default_context_);
1418 req.set_method("GET");
1419 req.Start();
1420 base::RunLoop().Run();
1422 // Check the interceptor got called as expected
1423 EXPECT_TRUE(interceptor.did_restart_main_);
1424 EXPECT_TRUE(interceptor.did_intercept_main_);
1426 // Check we received one good response
1427 EXPECT_TRUE(req.status().is_success());
1428 if (req.status().is_success()) {
1429 EXPECT_EQ(200, req.response_headers()->response_code());
1431 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1432 EXPECT_EQ(1, d.response_started_count());
1433 EXPECT_EQ(0, d.received_redirect_count());
1436 TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1437 TestInterceptor interceptor;
1439 // intercept the main request and cancel from within the restarted job
1440 interceptor.cancel_main_request_ = true;
1442 // setup to intercept final response and override it with an OK response
1443 interceptor.intercept_final_response_ = true;
1444 interceptor.final_headers_ = TestInterceptor::ok_headers();
1445 interceptor.final_data_ = TestInterceptor::ok_data();
1447 TestDelegate d;
1448 URLRequest req(GURL("http://test_intercept/foo"),
1449 DEFAULT_PRIORITY,
1451 &default_context_);
1452 req.set_method("GET");
1453 req.Start();
1454 base::RunLoop().Run();
1456 // Check the interceptor got called as expected
1457 EXPECT_TRUE(interceptor.did_cancel_main_);
1458 EXPECT_FALSE(interceptor.did_intercept_final_);
1460 // Check we see a canceled request
1461 EXPECT_FALSE(req.status().is_success());
1462 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1465 TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1466 TestInterceptor interceptor;
1468 // intercept the main request and respond with a redirect
1469 interceptor.intercept_main_request_ = true;
1470 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1471 interceptor.main_data_ = TestInterceptor::redirect_data();
1473 // intercept the redirect and cancel from within that job
1474 interceptor.cancel_redirect_request_ = true;
1476 // setup to intercept final response and override it with an OK response
1477 interceptor.intercept_final_response_ = true;
1478 interceptor.final_headers_ = TestInterceptor::ok_headers();
1479 interceptor.final_data_ = TestInterceptor::ok_data();
1481 TestDelegate d;
1482 URLRequest req(GURL("http://test_intercept/foo"),
1483 DEFAULT_PRIORITY,
1485 &default_context_);
1486 req.set_method("GET");
1487 req.Start();
1488 base::RunLoop().Run();
1490 // Check the interceptor got called as expected
1491 EXPECT_TRUE(interceptor.did_intercept_main_);
1492 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1493 EXPECT_FALSE(interceptor.did_intercept_final_);
1495 // Check we see a canceled request
1496 EXPECT_FALSE(req.status().is_success());
1497 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1500 TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1501 TestInterceptor interceptor;
1503 // intercept the main request to simulate a network error
1504 interceptor.simulate_main_network_error_ = true;
1506 // setup to intercept final response and cancel from within that job
1507 interceptor.cancel_final_request_ = true;
1509 TestDelegate d;
1510 URLRequest req(GURL("http://test_intercept/foo"),
1511 DEFAULT_PRIORITY,
1513 &default_context_);
1514 req.set_method("GET");
1515 req.Start();
1516 base::RunLoop().Run();
1518 // Check the interceptor got called as expected
1519 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1520 EXPECT_TRUE(interceptor.did_cancel_final_);
1522 // Check we see a canceled request
1523 EXPECT_FALSE(req.status().is_success());
1524 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1527 TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1528 TestInterceptor interceptor;
1530 // intercept the main request and cancel then restart from within that job
1531 interceptor.cancel_then_restart_main_request_ = true;
1533 // setup to intercept final response and override it with an OK response
1534 interceptor.intercept_final_response_ = true;
1535 interceptor.final_headers_ = TestInterceptor::ok_headers();
1536 interceptor.final_data_ = TestInterceptor::ok_data();
1538 TestDelegate d;
1539 URLRequest req(GURL("http://test_intercept/foo"),
1540 DEFAULT_PRIORITY,
1542 &default_context_);
1543 req.set_method("GET");
1544 req.Start();
1545 base::RunLoop().Run();
1547 // Check the interceptor got called as expected
1548 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1549 EXPECT_FALSE(interceptor.did_intercept_final_);
1551 // Check we see a canceled request
1552 EXPECT_FALSE(req.status().is_success());
1553 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1556 LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1557 URLRequestContext* context) {
1558 TestInterceptor interceptor;
1559 interceptor.intercept_main_request_ = true;
1560 interceptor.main_request_load_timing_info_ = job_load_timing;
1561 TestDelegate d;
1562 URLRequest req(
1563 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, context);
1564 req.Start();
1565 base::RunLoop().Run();
1567 LoadTimingInfo resulting_load_timing;
1568 req.GetLoadTimingInfo(&resulting_load_timing);
1570 // None of these should be modified by the URLRequest.
1571 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1572 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1573 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1574 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1575 EXPECT_EQ(job_load_timing.receive_headers_end,
1576 resulting_load_timing.receive_headers_end);
1578 return resulting_load_timing;
1581 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1582 // reused. |connect_time_flags| is used to indicate if there should be dns
1583 // or SSL times, and |used_proxy| is used for proxy times.
1584 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1585 int connect_time_flags,
1586 bool used_proxy) {
1587 LoadTimingInfo load_timing;
1588 load_timing.socket_log_id = 1;
1590 if (used_proxy) {
1591 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1592 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1595 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1596 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1597 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1598 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1600 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1601 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1602 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1603 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1605 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1607 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1608 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1609 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1610 return load_timing;
1613 // Same as above, but in the case of a reused socket.
1614 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1615 bool used_proxy) {
1616 LoadTimingInfo load_timing;
1617 load_timing.socket_log_id = 1;
1618 load_timing.socket_reused = true;
1620 if (used_proxy) {
1621 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1622 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1625 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1626 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1627 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1628 return load_timing;
1631 // Basic test that the intercept + load timing tests work.
1632 TEST_F(URLRequestTest, InterceptLoadTiming) {
1633 base::TimeTicks now = base::TimeTicks::Now();
1634 LoadTimingInfo job_load_timing =
1635 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1637 LoadTimingInfo load_timing_result =
1638 RunLoadTimingTest(job_load_timing, &default_context_);
1640 // Nothing should have been changed by the URLRequest.
1641 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1642 load_timing_result.proxy_resolve_start);
1643 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1644 load_timing_result.proxy_resolve_end);
1645 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1646 load_timing_result.connect_timing.dns_start);
1647 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1648 load_timing_result.connect_timing.dns_end);
1649 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1650 load_timing_result.connect_timing.connect_start);
1651 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1652 load_timing_result.connect_timing.connect_end);
1653 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1654 load_timing_result.connect_timing.ssl_start);
1655 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1656 load_timing_result.connect_timing.ssl_end);
1658 // Redundant sanity check.
1659 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1662 // Another basic test, with proxy and SSL times, but no DNS times.
1663 TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1664 base::TimeTicks now = base::TimeTicks::Now();
1665 LoadTimingInfo job_load_timing =
1666 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1668 LoadTimingInfo load_timing_result =
1669 RunLoadTimingTest(job_load_timing, &default_context_);
1671 // Nothing should have been changed by the URLRequest.
1672 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1673 load_timing_result.proxy_resolve_start);
1674 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1675 load_timing_result.proxy_resolve_end);
1676 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1677 load_timing_result.connect_timing.dns_start);
1678 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1679 load_timing_result.connect_timing.dns_end);
1680 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1681 load_timing_result.connect_timing.connect_start);
1682 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1683 load_timing_result.connect_timing.connect_end);
1684 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1685 load_timing_result.connect_timing.ssl_start);
1686 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1687 load_timing_result.connect_timing.ssl_end);
1689 // Redundant sanity check.
1690 TestLoadTimingNotReusedWithProxy(load_timing_result,
1691 CONNECT_TIMING_HAS_SSL_TIMES);
1694 // Make sure that URLRequest correctly adjusts proxy times when they're before
1695 // |request_start|, due to already having a connected socket. This happens in
1696 // the case of reusing a SPDY session or HTTP pipeline. The connected socket is
1697 // not considered reused in this test (May be a preconnect).
1699 // To mix things up from the test above, assumes DNS times but no SSL times.
1700 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1701 base::TimeTicks now = base::TimeTicks::Now();
1702 LoadTimingInfo job_load_timing =
1703 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1704 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1705 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1706 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1707 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1708 job_load_timing.connect_timing.connect_start =
1709 now - base::TimeDelta::FromDays(2);
1710 job_load_timing.connect_timing.connect_end =
1711 now - base::TimeDelta::FromDays(1);
1713 LoadTimingInfo load_timing_result =
1714 RunLoadTimingTest(job_load_timing, &default_context_);
1716 // Proxy times, connect times, and DNS times should all be replaced with
1717 // request_start.
1718 EXPECT_EQ(load_timing_result.request_start,
1719 load_timing_result.proxy_resolve_start);
1720 EXPECT_EQ(load_timing_result.request_start,
1721 load_timing_result.proxy_resolve_end);
1722 EXPECT_EQ(load_timing_result.request_start,
1723 load_timing_result.connect_timing.dns_start);
1724 EXPECT_EQ(load_timing_result.request_start,
1725 load_timing_result.connect_timing.dns_end);
1726 EXPECT_EQ(load_timing_result.request_start,
1727 load_timing_result.connect_timing.connect_start);
1728 EXPECT_EQ(load_timing_result.request_start,
1729 load_timing_result.connect_timing.connect_end);
1731 // Other times should have been left null.
1732 TestLoadTimingNotReusedWithProxy(load_timing_result,
1733 CONNECT_TIMING_HAS_DNS_TIMES);
1736 // Same as above, but in the reused case.
1737 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1738 base::TimeTicks now = base::TimeTicks::Now();
1739 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1740 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1741 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1743 LoadTimingInfo load_timing_result =
1744 RunLoadTimingTest(job_load_timing, &default_context_);
1746 // Proxy times and connect times should all be replaced with request_start.
1747 EXPECT_EQ(load_timing_result.request_start,
1748 load_timing_result.proxy_resolve_start);
1749 EXPECT_EQ(load_timing_result.request_start,
1750 load_timing_result.proxy_resolve_end);
1752 // Other times should have been left null.
1753 TestLoadTimingReusedWithProxy(load_timing_result);
1756 // Make sure that URLRequest correctly adjusts connect times when they're before
1757 // |request_start|, due to reusing a connected socket. The connected socket is
1758 // not considered reused in this test (May be a preconnect).
1760 // To mix things up, the request has SSL times, but no DNS times.
1761 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1762 base::TimeTicks now = base::TimeTicks::Now();
1763 LoadTimingInfo job_load_timing =
1764 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1765 job_load_timing.connect_timing.connect_start =
1766 now - base::TimeDelta::FromDays(1);
1767 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1768 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1769 job_load_timing.connect_timing.connect_end =
1770 now - base::TimeDelta::FromDays(4);
1772 LoadTimingInfo load_timing_result =
1773 RunLoadTimingTest(job_load_timing, &default_context_);
1775 // Connect times, and SSL times should be replaced with request_start.
1776 EXPECT_EQ(load_timing_result.request_start,
1777 load_timing_result.connect_timing.connect_start);
1778 EXPECT_EQ(load_timing_result.request_start,
1779 load_timing_result.connect_timing.ssl_start);
1780 EXPECT_EQ(load_timing_result.request_start,
1781 load_timing_result.connect_timing.ssl_end);
1782 EXPECT_EQ(load_timing_result.request_start,
1783 load_timing_result.connect_timing.connect_end);
1785 // Other times should have been left null.
1786 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1789 // Make sure that URLRequest correctly adjusts connect times when they're before
1790 // |request_start|, due to reusing a connected socket in the case that there
1791 // are also proxy times. The connected socket is not considered reused in this
1792 // test (May be a preconnect).
1794 // In this test, there are no SSL or DNS times.
1795 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1796 base::TimeTicks now = base::TimeTicks::Now();
1797 LoadTimingInfo job_load_timing =
1798 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1799 job_load_timing.connect_timing.connect_start =
1800 now - base::TimeDelta::FromDays(1);
1801 job_load_timing.connect_timing.connect_end =
1802 now - base::TimeDelta::FromDays(2);
1804 LoadTimingInfo load_timing_result =
1805 RunLoadTimingTest(job_load_timing, &default_context_);
1807 // Connect times should be replaced with proxy_resolve_end.
1808 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1809 load_timing_result.connect_timing.connect_start);
1810 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1811 load_timing_result.connect_timing.connect_end);
1813 // Other times should have been left null.
1814 TestLoadTimingNotReusedWithProxy(load_timing_result,
1815 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1818 // Check that two different URL requests have different identifiers.
1819 TEST_F(URLRequestTest, Identifiers) {
1820 TestDelegate d;
1821 TestURLRequestContext context;
1822 TestURLRequest req(
1823 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1824 TestURLRequest other_req(
1825 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1827 ASSERT_NE(req.identifier(), other_req.identifier());
1830 // Check that a failure to connect to the proxy is reported to the network
1831 // delegate.
1832 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1833 MockHostResolver host_resolver;
1834 host_resolver.rules()->AddSimulatedFailure("*");
1836 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
1837 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1839 TestDelegate d;
1840 URLRequest req(GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1841 req.set_method("GET");
1843 req.Start();
1844 base::RunLoop().Run();
1846 // Check we see a failed request.
1847 EXPECT_FALSE(req.status().is_success());
1848 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1849 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1851 EXPECT_EQ(1, network_delegate.error_count());
1852 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1853 EXPECT_EQ(1, network_delegate.completed_requests());
1856 // Make sure that net::NetworkDelegate::NotifyCompleted is called if
1857 // content is empty.
1858 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1859 TestDelegate d;
1860 URLRequest req(GURL("data:,"), DEFAULT_PRIORITY, &d, &default_context_);
1861 req.Start();
1862 base::RunLoop().Run();
1863 EXPECT_EQ("", d.data_received());
1864 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1867 // Make sure that SetPriority actually sets the URLRequest's priority
1868 // correctly, both before and after start.
1869 TEST_F(URLRequestTest, SetPriorityBasic) {
1870 TestDelegate d;
1871 URLRequest req(GURL("http://test_intercept/foo"),
1872 DEFAULT_PRIORITY,
1874 &default_context_);
1875 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1877 req.SetPriority(LOW);
1878 EXPECT_EQ(LOW, req.priority());
1880 req.Start();
1881 EXPECT_EQ(LOW, req.priority());
1883 req.SetPriority(MEDIUM);
1884 EXPECT_EQ(MEDIUM, req.priority());
1887 // Make sure that URLRequest calls SetPriority on a job before calling
1888 // Start on it.
1889 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1890 TestDelegate d;
1891 URLRequest req(GURL("http://test_intercept/foo"),
1892 DEFAULT_PRIORITY,
1894 &default_context_);
1895 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1897 scoped_refptr<URLRequestTestJob> job =
1898 new URLRequestTestJob(&req, &default_network_delegate_);
1899 AddTestInterceptor()->set_main_intercept_job(job.get());
1900 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1902 req.SetPriority(LOW);
1904 req.Start();
1905 EXPECT_EQ(LOW, job->priority());
1908 // Make sure that URLRequest passes on its priority updates to its
1909 // job.
1910 TEST_F(URLRequestTest, SetJobPriority) {
1911 TestDelegate d;
1912 URLRequest req(GURL("http://test_intercept/foo"),
1913 DEFAULT_PRIORITY,
1915 &default_context_);
1917 scoped_refptr<URLRequestTestJob> job =
1918 new URLRequestTestJob(&req, &default_network_delegate_);
1919 AddTestInterceptor()->set_main_intercept_job(job.get());
1921 req.SetPriority(LOW);
1922 req.Start();
1923 EXPECT_EQ(LOW, job->priority());
1925 req.SetPriority(MEDIUM);
1926 EXPECT_EQ(MEDIUM, req.priority());
1927 EXPECT_EQ(MEDIUM, job->priority());
1930 // Setting the IGNORE_LIMITS load flag should be okay if the priority
1931 // is MAXIMUM_PRIORITY.
1932 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1933 TestDelegate d;
1934 URLRequest req(GURL("http://test_intercept/foo"),
1935 MAXIMUM_PRIORITY,
1937 &default_context_);
1938 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1940 scoped_refptr<URLRequestTestJob> job =
1941 new URLRequestTestJob(&req, &default_network_delegate_);
1942 AddTestInterceptor()->set_main_intercept_job(job.get());
1944 req.SetLoadFlags(LOAD_IGNORE_LIMITS);
1945 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1947 req.SetPriority(MAXIMUM_PRIORITY);
1948 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1950 req.Start();
1951 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1952 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1955 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1956 #if !defined(OS_IOS)
1957 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
1958 // This is to work around mysterious failures in chrome_frame_net_tests. See:
1959 // http://crbug.com/114369
1960 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1961 class LocalHttpTestServer : public SpawnedTestServer {
1962 public:
1963 explicit LocalHttpTestServer(const base::FilePath& document_root)
1964 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1965 ScopedCustomUrlRequestTestHttpHost::value(),
1966 document_root) {}
1967 LocalHttpTestServer()
1968 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1969 ScopedCustomUrlRequestTestHttpHost::value(),
1970 base::FilePath()) {}
1973 TEST_F(URLRequestTest, DelayedCookieCallback) {
1974 LocalHttpTestServer test_server;
1975 ASSERT_TRUE(test_server.Start());
1977 TestURLRequestContext context;
1978 scoped_refptr<DelayedCookieMonster> delayed_cm =
1979 new DelayedCookieMonster();
1980 scoped_refptr<CookieStore> cookie_store = delayed_cm;
1981 context.set_cookie_store(delayed_cm.get());
1983 // Set up a cookie.
1985 TestNetworkDelegate network_delegate;
1986 context.set_network_delegate(&network_delegate);
1987 TestDelegate d;
1988 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1989 DEFAULT_PRIORITY,
1991 &context);
1992 req.Start();
1993 base::RunLoop().Run();
1994 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1995 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1996 EXPECT_EQ(1, network_delegate.set_cookie_count());
1999 // Verify that the cookie is set.
2001 TestNetworkDelegate network_delegate;
2002 context.set_network_delegate(&network_delegate);
2003 TestDelegate d;
2004 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2005 DEFAULT_PRIORITY,
2007 &context);
2008 req.Start();
2009 base::RunLoop().Run();
2011 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2012 != std::string::npos);
2013 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2014 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2018 TEST_F(URLRequestTest, DoNotSendCookies) {
2019 LocalHttpTestServer test_server;
2020 ASSERT_TRUE(test_server.Start());
2022 // Set up a cookie.
2024 TestNetworkDelegate network_delegate;
2025 default_context_.set_network_delegate(&network_delegate);
2026 TestDelegate d;
2027 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2028 DEFAULT_PRIORITY,
2030 &default_context_);
2031 req.Start();
2032 base::RunLoop().Run();
2033 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2034 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2037 // Verify that the cookie is set.
2039 TestNetworkDelegate network_delegate;
2040 default_context_.set_network_delegate(&network_delegate);
2041 TestDelegate d;
2042 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2043 DEFAULT_PRIORITY,
2045 &default_context_);
2046 req.Start();
2047 base::RunLoop().Run();
2049 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2050 != std::string::npos);
2051 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2052 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2055 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2057 TestNetworkDelegate network_delegate;
2058 default_context_.set_network_delegate(&network_delegate);
2059 TestDelegate d;
2060 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2061 DEFAULT_PRIORITY,
2063 &default_context_);
2064 req.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2065 req.Start();
2066 base::RunLoop().Run();
2068 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2069 == std::string::npos);
2071 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2072 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2073 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2077 TEST_F(URLRequestTest, DoNotSaveCookies) {
2078 LocalHttpTestServer test_server;
2079 ASSERT_TRUE(test_server.Start());
2081 // Set up a cookie.
2083 TestNetworkDelegate network_delegate;
2084 default_context_.set_network_delegate(&network_delegate);
2085 TestDelegate d;
2086 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2087 DEFAULT_PRIORITY,
2089 &default_context_);
2090 req.Start();
2091 base::RunLoop().Run();
2093 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2094 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2095 EXPECT_EQ(1, network_delegate.set_cookie_count());
2098 // Try to set-up another cookie and update the previous cookie.
2100 TestNetworkDelegate network_delegate;
2101 default_context_.set_network_delegate(&network_delegate);
2102 TestDelegate d;
2103 URLRequest req(
2104 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2105 DEFAULT_PRIORITY,
2107 &default_context_);
2108 req.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2109 req.Start();
2111 base::RunLoop().Run();
2113 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2114 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2115 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2116 EXPECT_EQ(0, network_delegate.set_cookie_count());
2119 // Verify the cookies weren't saved or updated.
2121 TestNetworkDelegate network_delegate;
2122 default_context_.set_network_delegate(&network_delegate);
2123 TestDelegate d;
2124 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2125 DEFAULT_PRIORITY,
2127 &default_context_);
2128 req.Start();
2129 base::RunLoop().Run();
2131 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2132 == std::string::npos);
2133 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2134 != std::string::npos);
2136 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2137 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2138 EXPECT_EQ(0, network_delegate.set_cookie_count());
2142 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2143 LocalHttpTestServer test_server;
2144 ASSERT_TRUE(test_server.Start());
2146 // Set up a cookie.
2148 TestNetworkDelegate network_delegate;
2149 default_context_.set_network_delegate(&network_delegate);
2150 TestDelegate d;
2151 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2152 DEFAULT_PRIORITY,
2154 &default_context_);
2155 req.Start();
2156 base::RunLoop().Run();
2158 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2159 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2162 // Verify that the cookie is set.
2164 TestNetworkDelegate network_delegate;
2165 default_context_.set_network_delegate(&network_delegate);
2166 TestDelegate d;
2167 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2168 DEFAULT_PRIORITY,
2170 &default_context_);
2171 req.Start();
2172 base::RunLoop().Run();
2174 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2175 != std::string::npos);
2177 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2178 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2181 // Verify that the cookie isn't sent.
2183 TestNetworkDelegate network_delegate;
2184 default_context_.set_network_delegate(&network_delegate);
2185 TestDelegate d;
2186 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2187 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2188 DEFAULT_PRIORITY,
2190 &default_context_);
2191 req.Start();
2192 base::RunLoop().Run();
2194 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2195 == std::string::npos);
2197 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2198 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2202 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2203 LocalHttpTestServer test_server;
2204 ASSERT_TRUE(test_server.Start());
2206 // Set up a cookie.
2208 TestNetworkDelegate network_delegate;
2209 default_context_.set_network_delegate(&network_delegate);
2210 TestDelegate d;
2211 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2212 DEFAULT_PRIORITY,
2214 &default_context_);
2215 req.Start();
2216 base::RunLoop().Run();
2218 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2219 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2222 // Try to set-up another cookie and update the previous cookie.
2224 TestNetworkDelegate network_delegate;
2225 default_context_.set_network_delegate(&network_delegate);
2226 TestDelegate d;
2227 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2228 URLRequest req(
2229 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2230 DEFAULT_PRIORITY,
2232 &default_context_);
2233 req.Start();
2235 base::RunLoop().Run();
2237 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2238 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2241 // Verify the cookies weren't saved or updated.
2243 TestNetworkDelegate network_delegate;
2244 default_context_.set_network_delegate(&network_delegate);
2245 TestDelegate d;
2246 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2247 DEFAULT_PRIORITY,
2249 &default_context_);
2250 req.Start();
2251 base::RunLoop().Run();
2253 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2254 == std::string::npos);
2255 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2256 != std::string::npos);
2258 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2259 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2263 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2264 LocalHttpTestServer test_server;
2265 ASSERT_TRUE(test_server.Start());
2267 // Set up an empty cookie.
2269 TestNetworkDelegate network_delegate;
2270 default_context_.set_network_delegate(&network_delegate);
2271 TestDelegate d;
2272 URLRequest req(test_server.GetURL("set-cookie"),
2273 DEFAULT_PRIORITY,
2275 &default_context_);
2276 req.Start();
2277 base::RunLoop().Run();
2279 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2280 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2281 EXPECT_EQ(0, network_delegate.set_cookie_count());
2285 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2286 LocalHttpTestServer test_server;
2287 ASSERT_TRUE(test_server.Start());
2289 // Set up a cookie.
2291 TestNetworkDelegate network_delegate;
2292 default_context_.set_network_delegate(&network_delegate);
2293 TestDelegate d;
2294 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2295 DEFAULT_PRIORITY,
2297 &default_context_);
2298 req.Start();
2299 base::RunLoop().Run();
2301 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2302 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2305 // Verify that the cookie is set.
2307 TestNetworkDelegate network_delegate;
2308 default_context_.set_network_delegate(&network_delegate);
2309 TestDelegate d;
2310 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2311 DEFAULT_PRIORITY,
2313 &default_context_);
2314 req.Start();
2315 base::RunLoop().Run();
2317 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2318 != std::string::npos);
2320 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2321 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2324 // Verify that the cookie isn't sent.
2326 TestNetworkDelegate network_delegate;
2327 default_context_.set_network_delegate(&network_delegate);
2328 TestDelegate d;
2329 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2330 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2331 DEFAULT_PRIORITY,
2333 &default_context_);
2334 req.Start();
2335 base::RunLoop().Run();
2337 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2338 == std::string::npos);
2340 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2341 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2345 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2346 LocalHttpTestServer test_server;
2347 ASSERT_TRUE(test_server.Start());
2349 // Set up a cookie.
2351 TestNetworkDelegate network_delegate;
2352 default_context_.set_network_delegate(&network_delegate);
2353 TestDelegate d;
2354 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2355 DEFAULT_PRIORITY,
2357 &default_context_);
2358 req.Start();
2359 base::RunLoop().Run();
2361 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2362 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2365 // Try to set-up another cookie and update the previous cookie.
2367 TestNetworkDelegate network_delegate;
2368 default_context_.set_network_delegate(&network_delegate);
2369 TestDelegate d;
2370 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2371 URLRequest req(
2372 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2373 DEFAULT_PRIORITY,
2375 &default_context_);
2376 req.Start();
2378 base::RunLoop().Run();
2380 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2381 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2384 // Verify the cookies weren't saved or updated.
2386 TestNetworkDelegate network_delegate;
2387 default_context_.set_network_delegate(&network_delegate);
2388 TestDelegate d;
2389 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2390 DEFAULT_PRIORITY,
2392 &default_context_);
2393 req.Start();
2394 base::RunLoop().Run();
2396 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2397 == std::string::npos);
2398 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2399 != std::string::npos);
2401 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2402 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2406 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2407 // value for the |fixed_date| argument given to the constructor.
2408 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2409 public:
2410 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2411 : fixed_date_(fixed_date) {}
2412 virtual ~FixedDateNetworkDelegate() {}
2414 // net::NetworkDelegate implementation
2415 virtual int OnHeadersReceived(
2416 net::URLRequest* request,
2417 const net::CompletionCallback& callback,
2418 const net::HttpResponseHeaders* original_response_headers,
2419 scoped_refptr<net::HttpResponseHeaders>* override_response_headers)
2420 OVERRIDE;
2422 private:
2423 std::string fixed_date_;
2425 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2428 int FixedDateNetworkDelegate::OnHeadersReceived(
2429 net::URLRequest* request,
2430 const net::CompletionCallback& callback,
2431 const net::HttpResponseHeaders* original_response_headers,
2432 scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
2433 net::HttpResponseHeaders* new_response_headers =
2434 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2436 new_response_headers->RemoveHeader("Date");
2437 new_response_headers->AddHeader("Date: " + fixed_date_);
2439 *override_response_headers = new_response_headers;
2440 return TestNetworkDelegate::OnHeadersReceived(request,
2441 callback,
2442 original_response_headers,
2443 override_response_headers);
2446 // Test that cookie expiration times are adjusted for server/client clock
2447 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2448 // headers by defaulting to GMT. (crbug.com/135131)
2449 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2450 LocalHttpTestServer test_server;
2451 ASSERT_TRUE(test_server.Start());
2453 // Set up an expired cookie.
2455 TestNetworkDelegate network_delegate;
2456 default_context_.set_network_delegate(&network_delegate);
2457 TestDelegate d;
2458 URLRequest req(
2459 test_server.GetURL(
2460 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2461 DEFAULT_PRIORITY,
2463 &default_context_);
2464 req.Start();
2465 base::RunLoop().Run();
2467 // Verify that the cookie is not set.
2469 TestNetworkDelegate network_delegate;
2470 default_context_.set_network_delegate(&network_delegate);
2471 TestDelegate d;
2472 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2473 DEFAULT_PRIORITY,
2475 &default_context_);
2476 req.Start();
2477 base::RunLoop().Run();
2479 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2481 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2483 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2484 default_context_.set_network_delegate(&network_delegate);
2485 TestDelegate d;
2486 URLRequest req(
2487 test_server.GetURL(
2488 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2489 DEFAULT_PRIORITY,
2491 &default_context_);
2492 req.Start();
2493 base::RunLoop().Run();
2495 // Verify that the cookie is set.
2497 TestNetworkDelegate network_delegate;
2498 default_context_.set_network_delegate(&network_delegate);
2499 TestDelegate d;
2500 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2501 DEFAULT_PRIORITY,
2503 &default_context_);
2504 req.Start();
2505 base::RunLoop().Run();
2507 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2512 // Check that it is impossible to change the referrer in the extra headers of
2513 // an URLRequest.
2514 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2515 LocalHttpTestServer test_server;
2516 ASSERT_TRUE(test_server.Start());
2518 // If extra headers contain referer and the request contains a referer,
2519 // only the latter shall be respected.
2521 TestDelegate d;
2522 URLRequest req(test_server.GetURL("echoheader?Referer"),
2523 DEFAULT_PRIORITY,
2525 &default_context_);
2526 req.SetReferrer("http://foo.com/");
2528 HttpRequestHeaders headers;
2529 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2530 req.SetExtraRequestHeaders(headers);
2532 req.Start();
2533 base::RunLoop().Run();
2535 EXPECT_EQ("http://foo.com/", d.data_received());
2538 // If extra headers contain a referer but the request does not, no referer
2539 // shall be sent in the header.
2541 TestDelegate d;
2542 URLRequest req(test_server.GetURL("echoheader?Referer"),
2543 DEFAULT_PRIORITY,
2545 &default_context_);
2547 HttpRequestHeaders headers;
2548 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2549 req.SetExtraRequestHeaders(headers);
2550 req.SetLoadFlags(LOAD_VALIDATE_CACHE);
2552 req.Start();
2553 base::RunLoop().Run();
2555 EXPECT_EQ("None", d.data_received());
2559 class URLRequestTestHTTP : public URLRequestTest {
2560 public:
2561 URLRequestTestHTTP()
2562 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2563 "net/data/url_request_unittest"))) {
2566 protected:
2567 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2568 // |request_method| is the method to use for the initial request.
2569 // |redirect_method| is the method that is expected to be used for the second
2570 // request, after redirection.
2571 // If |include_data| is true, data is uploaded with the request. The
2572 // response body is expected to match it exactly, if and only if
2573 // |request_method| == |redirect_method|.
2574 void HTTPRedirectMethodTest(const GURL& redirect_url,
2575 const std::string& request_method,
2576 const std::string& redirect_method,
2577 bool include_data) {
2578 static const char kData[] = "hello world";
2579 TestDelegate d;
2580 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
2581 req.set_method(request_method);
2582 if (include_data) {
2583 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2584 HttpRequestHeaders headers;
2585 headers.SetHeader(HttpRequestHeaders::kContentLength,
2586 base::UintToString(arraysize(kData) - 1));
2587 req.SetExtraRequestHeaders(headers);
2589 req.Start();
2590 base::RunLoop().Run();
2591 EXPECT_EQ(redirect_method, req.method());
2592 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2593 EXPECT_EQ(OK, req.status().error());
2594 if (include_data) {
2595 if (request_method == redirect_method) {
2596 EXPECT_EQ(kData, d.data_received());
2597 } else {
2598 EXPECT_NE(kData, d.data_received());
2601 if (HasFailure())
2602 LOG(WARNING) << "Request method was: " << request_method;
2605 void HTTPUploadDataOperationTest(const std::string& method) {
2606 const int kMsgSize = 20000; // multiple of 10
2607 const int kIterations = 50;
2608 char* uploadBytes = new char[kMsgSize+1];
2609 char* ptr = uploadBytes;
2610 char marker = 'a';
2611 for (int idx = 0; idx < kMsgSize/10; idx++) {
2612 memcpy(ptr, "----------", 10);
2613 ptr += 10;
2614 if (idx % 100 == 0) {
2615 ptr--;
2616 *ptr++ = marker;
2617 if (++marker > 'z')
2618 marker = 'a';
2621 uploadBytes[kMsgSize] = '\0';
2623 for (int i = 0; i < kIterations; ++i) {
2624 TestDelegate d;
2625 URLRequest r(
2626 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
2627 r.set_method(method.c_str());
2629 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
2631 r.Start();
2632 EXPECT_TRUE(r.is_pending());
2634 base::RunLoop().Run();
2636 ASSERT_EQ(1, d.response_started_count())
2637 << "request failed: " << r.status().status()
2638 << ", os error: " << r.status().error();
2640 EXPECT_FALSE(d.received_data_before_response());
2641 EXPECT_EQ(uploadBytes, d.data_received());
2643 delete[] uploadBytes;
2646 void AddChunksToUpload(URLRequest* r) {
2647 r->AppendChunkToUpload("a", 1, false);
2648 r->AppendChunkToUpload("bcd", 3, false);
2649 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2650 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2651 r->AppendChunkToUpload("0", 1, false);
2652 r->AppendChunkToUpload("2323", 4, true);
2655 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2656 // This should match the chunks sent by AddChunksToUpload().
2657 const std::string expected_data =
2658 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2660 ASSERT_EQ(1, d->response_started_count())
2661 << "request failed: " << r->status().status()
2662 << ", os error: " << r->status().error();
2664 EXPECT_FALSE(d->received_data_before_response());
2666 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2667 EXPECT_EQ(expected_data, d->data_received());
2670 bool DoManyCookiesRequest(int num_cookies) {
2671 TestDelegate d;
2672 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2673 base::IntToString(num_cookies)),
2674 DEFAULT_PRIORITY,
2676 &default_context_);
2678 r.Start();
2679 EXPECT_TRUE(r.is_pending());
2681 base::RunLoop().Run();
2683 bool is_success = r.status().is_success();
2685 if (!is_success) {
2686 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2687 // The test server appears to be unable to handle subsequent requests
2688 // after this error is triggered. Force it to restart.
2689 EXPECT_TRUE(test_server_.Stop());
2690 EXPECT_TRUE(test_server_.Start());
2693 return is_success;
2696 LocalHttpTestServer test_server_;
2699 // In this unit test, we're using the HTTPTestServer as a proxy server and
2700 // issuing a CONNECT request with the magic host name "www.redirect.com".
2701 // The HTTPTestServer will return a 302 response, which we should not
2702 // follow.
2703 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2704 ASSERT_TRUE(test_server_.Start());
2706 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2707 TestURLRequestContextWithProxy context(
2708 test_server_.host_port_pair().ToString(), &network_delegate);
2710 TestDelegate d;
2712 URLRequest r(
2713 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2714 r.Start();
2715 EXPECT_TRUE(r.is_pending());
2717 base::RunLoop().Run();
2719 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2720 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2721 EXPECT_EQ(1, d.response_started_count());
2722 // We should not have followed the redirect.
2723 EXPECT_EQ(0, d.received_redirect_count());
2727 // This is the same as the previous test, but checks that the network delegate
2728 // registers the error.
2729 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
2730 ASSERT_TRUE(test_server_.Start());
2732 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2733 TestURLRequestContextWithProxy context(
2734 test_server_.host_port_pair().ToString(), &network_delegate);
2736 TestDelegate d;
2738 URLRequest r(
2739 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2740 r.Start();
2741 EXPECT_TRUE(r.is_pending());
2743 base::RunLoop().Run();
2745 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2746 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2747 EXPECT_EQ(1, d.response_started_count());
2748 // We should not have followed the redirect.
2749 EXPECT_EQ(0, d.received_redirect_count());
2751 EXPECT_EQ(1, network_delegate.error_count());
2752 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
2756 // Tests that we can block and asynchronously return OK in various stages.
2757 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2758 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2759 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2760 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2761 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2763 static const size_t blocking_stages_length = arraysize(blocking_stages);
2765 ASSERT_TRUE(test_server_.Start());
2767 TestDelegate d;
2768 BlockingNetworkDelegate network_delegate(
2769 BlockingNetworkDelegate::USER_CALLBACK);
2770 network_delegate.set_block_on(
2771 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2772 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2773 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2775 TestURLRequestContext context(true);
2776 context.set_network_delegate(&network_delegate);
2777 context.Init();
2780 URLRequest r(
2781 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, &context);
2783 r.Start();
2784 for (size_t i = 0; i < blocking_stages_length; ++i) {
2785 base::RunLoop().Run();
2786 EXPECT_EQ(blocking_stages[i],
2787 network_delegate.stage_blocked_for_callback());
2788 network_delegate.DoCallback(OK);
2790 base::RunLoop().Run();
2791 EXPECT_EQ(200, r.GetResponseCode());
2792 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2793 EXPECT_EQ(1, network_delegate.created_requests());
2794 EXPECT_EQ(0, network_delegate.destroyed_requests());
2796 EXPECT_EQ(1, network_delegate.destroyed_requests());
2799 // Tests that the network delegate can block and cancel a request.
2800 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2801 ASSERT_TRUE(test_server_.Start());
2803 TestDelegate d;
2804 BlockingNetworkDelegate network_delegate(
2805 BlockingNetworkDelegate::AUTO_CALLBACK);
2806 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2807 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
2809 TestURLRequestContextWithProxy context(
2810 test_server_.host_port_pair().ToString(), &network_delegate);
2813 URLRequest r(
2814 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
2816 r.Start();
2817 base::RunLoop().Run();
2819 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2820 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
2821 EXPECT_EQ(1, network_delegate.created_requests());
2822 EXPECT_EQ(0, network_delegate.destroyed_requests());
2824 EXPECT_EQ(1, network_delegate.destroyed_requests());
2827 // Helper function for NetworkDelegateCancelRequestAsynchronously and
2828 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2829 // delegate operating in |block_mode| and a request for |url|. It blocks the
2830 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2831 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2832 BlockingNetworkDelegate::Stage stage,
2833 const GURL& url) {
2834 TestDelegate d;
2835 BlockingNetworkDelegate network_delegate(block_mode);
2836 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2837 network_delegate.set_block_on(stage);
2839 TestURLRequestContext context(true);
2840 context.set_network_delegate(&network_delegate);
2841 context.Init();
2844 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
2846 r.Start();
2847 base::RunLoop().Run();
2849 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2850 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
2851 EXPECT_EQ(1, network_delegate.created_requests());
2852 EXPECT_EQ(0, network_delegate.destroyed_requests());
2854 EXPECT_EQ(1, network_delegate.destroyed_requests());
2857 // The following 3 tests check that the network delegate can cancel a request
2858 // synchronously in various stages of the request.
2859 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2860 ASSERT_TRUE(test_server_.Start());
2861 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2862 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2863 test_server_.GetURL(std::string()));
2866 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2867 ASSERT_TRUE(test_server_.Start());
2868 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2869 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2870 test_server_.GetURL(std::string()));
2873 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2874 ASSERT_TRUE(test_server_.Start());
2875 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2876 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2877 test_server_.GetURL(std::string()));
2880 // The following 3 tests check that the network delegate can cancel a request
2881 // asynchronously in various stages of the request.
2882 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2883 ASSERT_TRUE(test_server_.Start());
2884 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2885 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2886 test_server_.GetURL(std::string()));
2889 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2890 ASSERT_TRUE(test_server_.Start());
2891 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2892 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2893 test_server_.GetURL(std::string()));
2896 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2897 ASSERT_TRUE(test_server_.Start());
2898 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2899 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2900 test_server_.GetURL(std::string()));
2903 // Tests that the network delegate can block and redirect a request to a new
2904 // URL.
2905 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2906 ASSERT_TRUE(test_server_.Start());
2908 TestDelegate d;
2909 BlockingNetworkDelegate network_delegate(
2910 BlockingNetworkDelegate::AUTO_CALLBACK);
2911 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2912 GURL redirect_url(test_server_.GetURL("simple.html"));
2913 network_delegate.set_redirect_url(redirect_url);
2915 TestURLRequestContextWithProxy context(
2916 test_server_.host_port_pair().ToString(), &network_delegate);
2919 GURL original_url(test_server_.GetURL("empty.html"));
2920 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2922 r.Start();
2923 base::RunLoop().Run();
2925 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2926 EXPECT_EQ(0, r.status().error());
2927 EXPECT_EQ(redirect_url, r.url());
2928 EXPECT_EQ(original_url, r.original_url());
2929 EXPECT_EQ(2U, r.url_chain().size());
2930 EXPECT_EQ(1, network_delegate.created_requests());
2931 EXPECT_EQ(0, network_delegate.destroyed_requests());
2933 EXPECT_EQ(1, network_delegate.destroyed_requests());
2936 // Tests that the network delegate can block and redirect a request to a new
2937 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2938 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2939 ASSERT_TRUE(test_server_.Start());
2941 TestDelegate d;
2942 BlockingNetworkDelegate network_delegate(
2943 BlockingNetworkDelegate::SYNCHRONOUS);
2944 GURL redirect_url(test_server_.GetURL("simple.html"));
2945 network_delegate.set_redirect_url(redirect_url);
2947 TestURLRequestContextWithProxy context(
2948 test_server_.host_port_pair().ToString(), &network_delegate);
2951 GURL original_url(test_server_.GetURL("empty.html"));
2952 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2954 r.Start();
2955 base::RunLoop().Run();
2957 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2958 EXPECT_EQ(0, r.status().error());
2959 EXPECT_EQ(redirect_url, r.url());
2960 EXPECT_EQ(original_url, r.original_url());
2961 EXPECT_EQ(2U, r.url_chain().size());
2962 EXPECT_EQ(1, network_delegate.created_requests());
2963 EXPECT_EQ(0, network_delegate.destroyed_requests());
2965 EXPECT_EQ(1, network_delegate.destroyed_requests());
2968 // Tests that redirects caused by the network delegate preserve POST data.
2969 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2970 ASSERT_TRUE(test_server_.Start());
2972 const char kData[] = "hello world";
2974 TestDelegate d;
2975 BlockingNetworkDelegate network_delegate(
2976 BlockingNetworkDelegate::AUTO_CALLBACK);
2977 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2978 GURL redirect_url(test_server_.GetURL("echo"));
2979 network_delegate.set_redirect_url(redirect_url);
2981 TestURLRequestContext context(true);
2982 context.set_network_delegate(&network_delegate);
2983 context.Init();
2986 GURL original_url(test_server_.GetURL("empty.html"));
2987 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2988 r.set_method("POST");
2989 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2990 HttpRequestHeaders headers;
2991 headers.SetHeader(HttpRequestHeaders::kContentLength,
2992 base::UintToString(arraysize(kData) - 1));
2993 r.SetExtraRequestHeaders(headers);
2994 r.Start();
2995 base::RunLoop().Run();
2997 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2998 EXPECT_EQ(0, r.status().error());
2999 EXPECT_EQ(redirect_url, r.url());
3000 EXPECT_EQ(original_url, r.original_url());
3001 EXPECT_EQ(2U, r.url_chain().size());
3002 EXPECT_EQ(1, network_delegate.created_requests());
3003 EXPECT_EQ(0, network_delegate.destroyed_requests());
3004 EXPECT_EQ("POST", r.method());
3005 EXPECT_EQ(kData, d.data_received());
3007 EXPECT_EQ(1, network_delegate.destroyed_requests());
3010 // Tests that the network delegate can synchronously complete OnAuthRequired
3011 // by taking no action. This indicates that the NetworkDelegate does not want to
3012 // handle the challenge, and is passing the buck along to the
3013 // URLRequest::Delegate.
3014 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3015 ASSERT_TRUE(test_server_.Start());
3017 TestDelegate d;
3018 BlockingNetworkDelegate network_delegate(
3019 BlockingNetworkDelegate::SYNCHRONOUS);
3021 TestURLRequestContext context(true);
3022 context.set_network_delegate(&network_delegate);
3023 context.Init();
3025 d.set_credentials(AuthCredentials(kUser, kSecret));
3028 GURL url(test_server_.GetURL("auth-basic"));
3029 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3030 r.Start();
3032 base::RunLoop().Run();
3034 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3035 EXPECT_EQ(0, r.status().error());
3036 EXPECT_EQ(200, r.GetResponseCode());
3037 EXPECT_TRUE(d.auth_required_called());
3038 EXPECT_EQ(1, network_delegate.created_requests());
3039 EXPECT_EQ(0, network_delegate.destroyed_requests());
3041 EXPECT_EQ(1, network_delegate.destroyed_requests());
3044 TEST_F(URLRequestTestHTTP,
3045 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3046 ASSERT_TRUE(test_server_.Start());
3048 TestDelegate d;
3049 BlockingNetworkDelegate network_delegate(
3050 BlockingNetworkDelegate::SYNCHRONOUS);
3052 TestURLRequestContext context(true);
3053 context.set_network_delegate(&network_delegate);
3054 context.Init();
3056 d.set_credentials(AuthCredentials(kUser, kSecret));
3059 GURL url(test_server_.GetURL("auth-basic"));
3060 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3061 r.Start();
3064 HttpRequestHeaders headers;
3065 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3066 EXPECT_FALSE(headers.HasHeader("Authorization"));
3069 base::RunLoop().Run();
3071 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3072 EXPECT_EQ(0, r.status().error());
3073 EXPECT_EQ(200, r.GetResponseCode());
3074 EXPECT_TRUE(d.auth_required_called());
3075 EXPECT_EQ(1, network_delegate.created_requests());
3076 EXPECT_EQ(0, network_delegate.destroyed_requests());
3078 EXPECT_EQ(1, network_delegate.destroyed_requests());
3081 // Tests that the network delegate can synchronously complete OnAuthRequired
3082 // by setting credentials.
3083 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3084 ASSERT_TRUE(test_server_.Start());
3086 TestDelegate d;
3087 BlockingNetworkDelegate network_delegate(
3088 BlockingNetworkDelegate::SYNCHRONOUS);
3089 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3090 network_delegate.set_auth_retval(
3091 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3093 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3095 TestURLRequestContext context(true);
3096 context.set_network_delegate(&network_delegate);
3097 context.Init();
3100 GURL url(test_server_.GetURL("auth-basic"));
3101 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3102 r.Start();
3103 base::RunLoop().Run();
3105 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3106 EXPECT_EQ(0, r.status().error());
3107 EXPECT_EQ(200, r.GetResponseCode());
3108 EXPECT_FALSE(d.auth_required_called());
3109 EXPECT_EQ(1, network_delegate.created_requests());
3110 EXPECT_EQ(0, network_delegate.destroyed_requests());
3112 EXPECT_EQ(1, network_delegate.destroyed_requests());
3115 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3116 // headers (for the first or second request) when called at the proper times.
3117 TEST_F(URLRequestTestHTTP,
3118 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3119 ASSERT_TRUE(test_server_.Start());
3121 TestDelegate d;
3122 BlockingNetworkDelegate network_delegate(
3123 BlockingNetworkDelegate::SYNCHRONOUS);
3124 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3125 network_delegate.set_auth_retval(
3126 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3128 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3130 TestURLRequestContext context(true);
3131 context.set_network_delegate(&network_delegate);
3132 context.Init();
3135 GURL url(test_server_.GetURL("auth-basic"));
3136 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3137 r.Start();
3138 base::RunLoop().Run();
3140 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3141 EXPECT_EQ(0, r.status().error());
3142 EXPECT_EQ(200, r.GetResponseCode());
3143 EXPECT_FALSE(d.auth_required_called());
3144 EXPECT_EQ(1, network_delegate.created_requests());
3145 EXPECT_EQ(0, network_delegate.destroyed_requests());
3148 HttpRequestHeaders headers;
3149 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3150 EXPECT_TRUE(headers.HasHeader("Authorization"));
3153 EXPECT_EQ(1, network_delegate.destroyed_requests());
3156 // Tests that the network delegate can synchronously complete OnAuthRequired
3157 // by cancelling authentication.
3158 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3159 ASSERT_TRUE(test_server_.Start());
3161 TestDelegate d;
3162 BlockingNetworkDelegate network_delegate(
3163 BlockingNetworkDelegate::SYNCHRONOUS);
3164 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3165 network_delegate.set_auth_retval(
3166 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3168 TestURLRequestContext context(true);
3169 context.set_network_delegate(&network_delegate);
3170 context.Init();
3173 GURL url(test_server_.GetURL("auth-basic"));
3174 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3175 r.Start();
3176 base::RunLoop().Run();
3178 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3179 EXPECT_EQ(OK, r.status().error());
3180 EXPECT_EQ(401, r.GetResponseCode());
3181 EXPECT_FALSE(d.auth_required_called());
3182 EXPECT_EQ(1, network_delegate.created_requests());
3183 EXPECT_EQ(0, network_delegate.destroyed_requests());
3185 EXPECT_EQ(1, network_delegate.destroyed_requests());
3188 // Tests that the network delegate can asynchronously complete OnAuthRequired
3189 // by taking no action. This indicates that the NetworkDelegate does not want
3190 // to handle the challenge, and is passing the buck along to the
3191 // URLRequest::Delegate.
3192 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3193 ASSERT_TRUE(test_server_.Start());
3195 TestDelegate d;
3196 BlockingNetworkDelegate network_delegate(
3197 BlockingNetworkDelegate::AUTO_CALLBACK);
3198 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3200 TestURLRequestContext context(true);
3201 context.set_network_delegate(&network_delegate);
3202 context.Init();
3204 d.set_credentials(AuthCredentials(kUser, kSecret));
3207 GURL url(test_server_.GetURL("auth-basic"));
3208 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3209 r.Start();
3210 base::RunLoop().Run();
3212 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3213 EXPECT_EQ(0, r.status().error());
3214 EXPECT_EQ(200, r.GetResponseCode());
3215 EXPECT_TRUE(d.auth_required_called());
3216 EXPECT_EQ(1, network_delegate.created_requests());
3217 EXPECT_EQ(0, network_delegate.destroyed_requests());
3219 EXPECT_EQ(1, network_delegate.destroyed_requests());
3222 // Tests that the network delegate can asynchronously complete OnAuthRequired
3223 // by setting credentials.
3224 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3225 ASSERT_TRUE(test_server_.Start());
3227 TestDelegate d;
3228 BlockingNetworkDelegate network_delegate(
3229 BlockingNetworkDelegate::AUTO_CALLBACK);
3230 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3231 network_delegate.set_auth_retval(
3232 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3234 AuthCredentials auth_credentials(kUser, kSecret);
3235 network_delegate.set_auth_credentials(auth_credentials);
3237 TestURLRequestContext context(true);
3238 context.set_network_delegate(&network_delegate);
3239 context.Init();
3242 GURL url(test_server_.GetURL("auth-basic"));
3243 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3244 r.Start();
3245 base::RunLoop().Run();
3247 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3248 EXPECT_EQ(0, r.status().error());
3250 EXPECT_EQ(200, r.GetResponseCode());
3251 EXPECT_FALSE(d.auth_required_called());
3252 EXPECT_EQ(1, network_delegate.created_requests());
3253 EXPECT_EQ(0, network_delegate.destroyed_requests());
3255 EXPECT_EQ(1, network_delegate.destroyed_requests());
3258 // Tests that the network delegate can asynchronously complete OnAuthRequired
3259 // by cancelling authentication.
3260 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3261 ASSERT_TRUE(test_server_.Start());
3263 TestDelegate d;
3264 BlockingNetworkDelegate network_delegate(
3265 BlockingNetworkDelegate::AUTO_CALLBACK);
3266 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3267 network_delegate.set_auth_retval(
3268 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3270 TestURLRequestContext context(true);
3271 context.set_network_delegate(&network_delegate);
3272 context.Init();
3275 GURL url(test_server_.GetURL("auth-basic"));
3276 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3277 r.Start();
3278 base::RunLoop().Run();
3280 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3281 EXPECT_EQ(OK, r.status().error());
3282 EXPECT_EQ(401, r.GetResponseCode());
3283 EXPECT_FALSE(d.auth_required_called());
3284 EXPECT_EQ(1, network_delegate.created_requests());
3285 EXPECT_EQ(0, network_delegate.destroyed_requests());
3287 EXPECT_EQ(1, network_delegate.destroyed_requests());
3290 // Tests that we can handle when a network request was canceled while we were
3291 // waiting for the network delegate.
3292 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3293 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3294 ASSERT_TRUE(test_server_.Start());
3296 TestDelegate d;
3297 BlockingNetworkDelegate network_delegate(
3298 BlockingNetworkDelegate::USER_CALLBACK);
3299 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3301 TestURLRequestContext context(true);
3302 context.set_network_delegate(&network_delegate);
3303 context.Init();
3306 URLRequest r(
3307 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3309 r.Start();
3310 base::RunLoop().Run();
3311 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3312 network_delegate.stage_blocked_for_callback());
3313 EXPECT_EQ(0, network_delegate.completed_requests());
3314 // Cancel before callback.
3315 r.Cancel();
3316 // Ensure that network delegate is notified.
3317 EXPECT_EQ(1, network_delegate.completed_requests());
3318 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3319 EXPECT_EQ(ERR_ABORTED, r.status().error());
3320 EXPECT_EQ(1, network_delegate.created_requests());
3321 EXPECT_EQ(0, network_delegate.destroyed_requests());
3323 EXPECT_EQ(1, network_delegate.destroyed_requests());
3326 // Tests that we can handle when a network request was canceled while we were
3327 // waiting for the network delegate.
3328 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3329 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3330 ASSERT_TRUE(test_server_.Start());
3332 TestDelegate d;
3333 BlockingNetworkDelegate network_delegate(
3334 BlockingNetworkDelegate::USER_CALLBACK);
3335 network_delegate.set_block_on(
3336 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
3338 TestURLRequestContext context(true);
3339 context.set_network_delegate(&network_delegate);
3340 context.Init();
3343 URLRequest r(
3344 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3346 r.Start();
3347 base::RunLoop().Run();
3348 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3349 network_delegate.stage_blocked_for_callback());
3350 EXPECT_EQ(0, network_delegate.completed_requests());
3351 // Cancel before callback.
3352 r.Cancel();
3353 // Ensure that network delegate is notified.
3354 EXPECT_EQ(1, network_delegate.completed_requests());
3355 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3356 EXPECT_EQ(ERR_ABORTED, r.status().error());
3357 EXPECT_EQ(1, network_delegate.created_requests());
3358 EXPECT_EQ(0, network_delegate.destroyed_requests());
3360 EXPECT_EQ(1, network_delegate.destroyed_requests());
3363 // Tests that we can handle when a network request was canceled while we were
3364 // waiting for the network delegate.
3365 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3366 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3367 ASSERT_TRUE(test_server_.Start());
3369 TestDelegate d;
3370 BlockingNetworkDelegate network_delegate(
3371 BlockingNetworkDelegate::USER_CALLBACK);
3372 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3374 TestURLRequestContext context(true);
3375 context.set_network_delegate(&network_delegate);
3376 context.Init();
3379 URLRequest r(
3380 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3382 r.Start();
3383 base::RunLoop().Run();
3384 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3385 network_delegate.stage_blocked_for_callback());
3386 EXPECT_EQ(0, network_delegate.completed_requests());
3387 // Cancel before callback.
3388 r.Cancel();
3389 // Ensure that network delegate is notified.
3390 EXPECT_EQ(1, network_delegate.completed_requests());
3391 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3392 EXPECT_EQ(ERR_ABORTED, r.status().error());
3393 EXPECT_EQ(1, network_delegate.created_requests());
3394 EXPECT_EQ(0, network_delegate.destroyed_requests());
3396 EXPECT_EQ(1, network_delegate.destroyed_requests());
3399 // Tests that we can handle when a network request was canceled while we were
3400 // waiting for the network delegate.
3401 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3402 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
3403 ASSERT_TRUE(test_server_.Start());
3405 TestDelegate d;
3406 BlockingNetworkDelegate network_delegate(
3407 BlockingNetworkDelegate::USER_CALLBACK);
3408 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3410 TestURLRequestContext context(true);
3411 context.set_network_delegate(&network_delegate);
3412 context.Init();
3415 URLRequest r(
3416 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, &context);
3418 r.Start();
3419 base::RunLoop().Run();
3420 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3421 network_delegate.stage_blocked_for_callback());
3422 EXPECT_EQ(0, network_delegate.completed_requests());
3423 // Cancel before callback.
3424 r.Cancel();
3425 // Ensure that network delegate is notified.
3426 EXPECT_EQ(1, network_delegate.completed_requests());
3427 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3428 EXPECT_EQ(ERR_ABORTED, r.status().error());
3429 EXPECT_EQ(1, network_delegate.created_requests());
3430 EXPECT_EQ(0, network_delegate.destroyed_requests());
3432 EXPECT_EQ(1, network_delegate.destroyed_requests());
3435 // In this unit test, we're using the HTTPTestServer as a proxy server and
3436 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3437 // The HTTPTestServer will return a 401 response, which we should balk at.
3438 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
3439 ASSERT_TRUE(test_server_.Start());
3441 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3442 TestURLRequestContextWithProxy context(
3443 test_server_.host_port_pair().ToString(), &network_delegate);
3445 TestDelegate d;
3447 URLRequest r(
3448 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, &context);
3450 r.Start();
3451 EXPECT_TRUE(r.is_pending());
3453 base::RunLoop().Run();
3455 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3456 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
3460 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
3461 ASSERT_TRUE(test_server_.Start());
3463 TestDelegate d;
3465 URLRequest r(test_server_.GetURL(std::string()),
3466 DEFAULT_PRIORITY,
3468 &default_context_);
3470 r.Start();
3471 EXPECT_TRUE(r.is_pending());
3473 base::RunLoop().Run();
3475 EXPECT_EQ(1, d.response_started_count());
3476 EXPECT_FALSE(d.received_data_before_response());
3477 EXPECT_NE(0, d.bytes_received());
3478 EXPECT_EQ(test_server_.host_port_pair().host(),
3479 r.GetSocketAddress().host());
3480 EXPECT_EQ(test_server_.host_port_pair().port(),
3481 r.GetSocketAddress().port());
3483 // TODO(eroman): Add back the NetLog tests...
3487 // This test has the server send a large number of cookies to the client.
3488 // To ensure that no number of cookies causes a crash, a galloping binary
3489 // search is used to estimate that maximum number of cookies that are accepted
3490 // by the browser. Beyond the maximum number, the request will fail with
3491 // ERR_RESPONSE_HEADERS_TOO_BIG.
3492 #if defined(OS_WIN)
3493 // http://crbug.com/177916
3494 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3495 #else
3496 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3497 #endif // defined(OS_WIN)
3498 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
3499 ASSERT_TRUE(test_server_.Start());
3501 int lower_bound = 0;
3502 int upper_bound = 1;
3504 // Double the number of cookies until the response header limits are
3505 // exceeded.
3506 while (DoManyCookiesRequest(upper_bound)) {
3507 lower_bound = upper_bound;
3508 upper_bound *= 2;
3509 ASSERT_LT(upper_bound, 1000000);
3512 int tolerance = upper_bound * 0.005;
3513 if (tolerance < 2)
3514 tolerance = 2;
3516 // Perform a binary search to find the highest possible number of cookies,
3517 // within the desired tolerance.
3518 while (upper_bound - lower_bound >= tolerance) {
3519 int num_cookies = (lower_bound + upper_bound) / 2;
3521 if (DoManyCookiesRequest(num_cookies))
3522 lower_bound = num_cookies;
3523 else
3524 upper_bound = num_cookies;
3526 // Success: the test did not crash.
3529 TEST_F(URLRequestTestHTTP, GetTest) {
3530 ASSERT_TRUE(test_server_.Start());
3532 TestDelegate d;
3534 URLRequest r(test_server_.GetURL(std::string()),
3535 DEFAULT_PRIORITY,
3537 &default_context_);
3539 r.Start();
3540 EXPECT_TRUE(r.is_pending());
3542 base::RunLoop().Run();
3544 EXPECT_EQ(1, d.response_started_count());
3545 EXPECT_FALSE(d.received_data_before_response());
3546 EXPECT_NE(0, d.bytes_received());
3547 EXPECT_EQ(test_server_.host_port_pair().host(),
3548 r.GetSocketAddress().host());
3549 EXPECT_EQ(test_server_.host_port_pair().port(),
3550 r.GetSocketAddress().port());
3554 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3555 ASSERT_TRUE(test_server_.Start());
3557 TestDelegate d;
3559 GURL test_url(test_server_.GetURL(std::string()));
3560 URLRequest r(test_url, DEFAULT_PRIORITY, &d, &default_context_);
3562 HttpRequestHeaders headers;
3563 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3565 r.Start();
3566 EXPECT_TRUE(r.is_pending());
3568 base::RunLoop().Run();
3570 EXPECT_EQ(1, d.response_started_count());
3571 EXPECT_FALSE(d.received_data_before_response());
3572 EXPECT_NE(0, d.bytes_received());
3573 EXPECT_EQ(test_server_.host_port_pair().host(),
3574 r.GetSocketAddress().host());
3575 EXPECT_EQ(test_server_.host_port_pair().port(),
3576 r.GetSocketAddress().port());
3578 EXPECT_TRUE(d.have_full_request_headers());
3579 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3583 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3584 ASSERT_TRUE(test_server_.Start());
3586 TestDelegate d;
3588 URLRequest r(test_server_.GetURL(std::string()),
3589 DEFAULT_PRIORITY,
3591 &default_context_);
3593 r.Start();
3594 EXPECT_TRUE(r.is_pending());
3596 base::RunLoop().Run();
3598 LoadTimingInfo load_timing_info;
3599 r.GetLoadTimingInfo(&load_timing_info);
3600 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3602 EXPECT_EQ(1, d.response_started_count());
3603 EXPECT_FALSE(d.received_data_before_response());
3604 EXPECT_NE(0, d.bytes_received());
3605 EXPECT_EQ(test_server_.host_port_pair().host(),
3606 r.GetSocketAddress().host());
3607 EXPECT_EQ(test_server_.host_port_pair().port(),
3608 r.GetSocketAddress().port());
3612 TEST_F(URLRequestTestHTTP, GetZippedTest) {
3613 ASSERT_TRUE(test_server_.Start());
3615 // Parameter that specifies the Content-Length field in the response:
3616 // C - Compressed length.
3617 // U - Uncompressed length.
3618 // L - Large length (larger than both C & U).
3619 // M - Medium length (between C & U).
3620 // S - Small length (smaller than both C & U).
3621 const char test_parameters[] = "CULMS";
3622 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3623 // C & U should be OK.
3624 // L & M are larger than the data sent, and show an error.
3625 // S has too little data, but we seem to accept it.
3626 const bool test_expect_success[num_tests] =
3627 { true, true, false, false, true };
3629 for (int i = 0; i < num_tests ; i++) {
3630 TestDelegate d;
3632 std::string test_file =
3633 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3634 test_parameters[i]);
3636 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3637 TestURLRequestContext context(true);
3638 context.set_network_delegate(&network_delegate);
3639 context.Init();
3641 URLRequest r(
3642 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, &context);
3643 r.Start();
3644 EXPECT_TRUE(r.is_pending());
3646 base::RunLoop().Run();
3648 EXPECT_EQ(1, d.response_started_count());
3649 EXPECT_FALSE(d.received_data_before_response());
3650 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3651 << " status = " << r.status().status()
3652 << " error = " << r.status().error();
3653 if (test_expect_success[i]) {
3654 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3655 << " Parameter = \"" << test_file << "\"";
3656 } else {
3657 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3658 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
3659 << " Parameter = \"" << test_file << "\"";
3665 TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
3666 ASSERT_TRUE(test_server_.Start());
3668 SpawnedTestServer https_test_server(
3669 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
3670 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3671 ASSERT_TRUE(https_test_server.Start());
3673 // An https server is sent a request with an https referer,
3674 // and responds with a redirect to an http url. The http
3675 // server should not be sent the referer.
3676 GURL http_destination = test_server_.GetURL(std::string());
3677 TestDelegate d;
3678 URLRequest req(
3679 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3680 DEFAULT_PRIORITY,
3682 &default_context_);
3683 req.SetReferrer("https://www.referrer.com/");
3684 req.Start();
3685 base::RunLoop().Run();
3687 EXPECT_EQ(1, d.response_started_count());
3688 EXPECT_EQ(1, d.received_redirect_count());
3689 EXPECT_EQ(http_destination, req.url());
3690 EXPECT_EQ(std::string(), req.referrer());
3693 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3694 ASSERT_TRUE(test_server_.Start());
3696 GURL destination_url = test_server_.GetURL(std::string());
3697 GURL original_url =
3698 test_server_.GetURL("server-redirect?" + destination_url.spec());
3699 TestDelegate d;
3700 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3701 req.Start();
3702 base::RunLoop().Run();
3704 EXPECT_EQ(1, d.response_started_count());
3705 EXPECT_EQ(1, d.received_redirect_count());
3706 EXPECT_EQ(destination_url, req.url());
3707 EXPECT_EQ(original_url, req.original_url());
3708 ASSERT_EQ(2U, req.url_chain().size());
3709 EXPECT_EQ(original_url, req.url_chain()[0]);
3710 EXPECT_EQ(destination_url, req.url_chain()[1]);
3712 LoadTimingInfo load_timing_info_before_redirect;
3713 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3714 &load_timing_info_before_redirect));
3715 TestLoadTimingNotReused(load_timing_info_before_redirect,
3716 CONNECT_TIMING_HAS_DNS_TIMES);
3718 LoadTimingInfo load_timing_info;
3719 req.GetLoadTimingInfo(&load_timing_info);
3720 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3722 // Check that a new socket was used on redirect, since the server does not
3723 // supposed keep-alive sockets, and that the times before the redirect are
3724 // before the ones recorded for the second request.
3725 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3726 load_timing_info.socket_log_id);
3727 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3728 load_timing_info.connect_timing.connect_start);
3731 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3732 ASSERT_TRUE(test_server_.Start());
3734 GURL destination_url = test_server_.GetURL(std::string());
3735 GURL middle_redirect_url =
3736 test_server_.GetURL("server-redirect?" + destination_url.spec());
3737 GURL original_url = test_server_.GetURL(
3738 "server-redirect?" + middle_redirect_url.spec());
3739 TestDelegate d;
3740 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3741 req.Start();
3742 base::RunLoop().Run();
3744 EXPECT_EQ(1, d.response_started_count());
3745 EXPECT_EQ(2, d.received_redirect_count());
3746 EXPECT_EQ(destination_url, req.url());
3747 EXPECT_EQ(original_url, req.original_url());
3748 ASSERT_EQ(3U, req.url_chain().size());
3749 EXPECT_EQ(original_url, req.url_chain()[0]);
3750 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3751 EXPECT_EQ(destination_url, req.url_chain()[2]);
3754 // First and second pieces of information logged by delegates to URLRequests.
3755 const char kFirstDelegateInfo[] = "Wonderful delegate";
3756 const char kSecondDelegateInfo[] = "Exciting delegate";
3758 // Logs delegate information to a URLRequest. The first string is logged
3759 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3760 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3761 // another asynchronous call is used to clear the delegate information
3762 // before calling a callback. The object then deletes itself.
3763 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3764 public:
3765 typedef base::Callback<void()> Callback;
3767 // Each time delegate information is added to the URLRequest, the resulting
3768 // load state is checked. The expected load state after each request is
3769 // passed in as an argument.
3770 static void Run(URLRequest* url_request,
3771 LoadState expected_first_load_state,
3772 LoadState expected_second_load_state,
3773 LoadState expected_third_load_state,
3774 const Callback& callback) {
3775 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3776 url_request,
3777 expected_first_load_state,
3778 expected_second_load_state,
3779 expected_third_load_state,
3780 callback);
3781 logger->Start();
3784 // Checks that the log entries, starting with log_position, contain the
3785 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3786 // recorded. Returns the index of entry after the expected number of
3787 // events this logged, or entries.size() if there aren't enough entries.
3788 static size_t CheckDelegateInfo(
3789 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3790 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3791 if (log_position + 3 >= entries.size()) {
3792 ADD_FAILURE() << "Not enough log entries";
3793 return entries.size();
3795 std::string delegate_info;
3796 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3797 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3798 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3799 &delegate_info));
3800 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3802 ++log_position;
3803 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3804 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3806 ++log_position;
3807 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3808 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3809 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3810 &delegate_info));
3811 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3813 ++log_position;
3814 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3815 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3817 return log_position + 1;
3820 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3821 // Returns the position of the end message.
3822 static size_t ExpectBeforeNetworkEvents(
3823 const CapturingNetLog::CapturedEntryList& entries,
3824 size_t log_position) {
3825 log_position =
3826 ExpectLogContainsSomewhereAfter(entries,
3827 log_position,
3828 NetLog::TYPE_URL_REQUEST_DELEGATE,
3829 NetLog::PHASE_BEGIN);
3830 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3831 entries[log_position + 1].type);
3832 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3833 return log_position + 1;
3836 private:
3837 friend class base::RefCounted<AsyncDelegateLogger>;
3839 AsyncDelegateLogger(URLRequest* url_request,
3840 LoadState expected_first_load_state,
3841 LoadState expected_second_load_state,
3842 LoadState expected_third_load_state,
3843 const Callback& callback)
3844 : url_request_(url_request),
3845 expected_first_load_state_(expected_first_load_state),
3846 expected_second_load_state_(expected_second_load_state),
3847 expected_third_load_state_(expected_third_load_state),
3848 callback_(callback) {
3851 ~AsyncDelegateLogger() {}
3853 void Start() {
3854 url_request_->LogBlockedBy(kFirstDelegateInfo);
3855 LoadStateWithParam load_state = url_request_->GetLoadState();
3856 EXPECT_EQ(expected_first_load_state_, load_state.state);
3857 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3858 base::MessageLoop::current()->PostTask(
3859 FROM_HERE,
3860 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3863 void LogSecondDelegate() {
3864 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
3865 LoadStateWithParam load_state = url_request_->GetLoadState();
3866 EXPECT_EQ(expected_second_load_state_, load_state.state);
3867 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3868 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3869 } else {
3870 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3872 base::MessageLoop::current()->PostTask(
3873 FROM_HERE,
3874 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3877 void LogComplete() {
3878 url_request_->LogUnblocked();
3879 LoadStateWithParam load_state = url_request_->GetLoadState();
3880 EXPECT_EQ(expected_third_load_state_, load_state.state);
3881 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3882 EXPECT_EQ(base::string16(), load_state.param);
3883 callback_.Run();
3886 URLRequest* url_request_;
3887 const int expected_first_load_state_;
3888 const int expected_second_load_state_;
3889 const int expected_third_load_state_;
3890 const Callback callback_;
3892 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3895 // NetworkDelegate that logs delegate information before a request is started,
3896 // before headers are sent, when headers are read, and when auth information
3897 // is requested. Uses AsyncDelegateLogger.
3898 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3899 public:
3900 AsyncLoggingNetworkDelegate() {}
3901 virtual ~AsyncLoggingNetworkDelegate() {}
3903 // NetworkDelegate implementation.
3904 virtual int OnBeforeURLRequest(URLRequest* request,
3905 const CompletionCallback& callback,
3906 GURL* new_url) OVERRIDE {
3907 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3908 return RunCallbackAsynchronously(request, callback);
3911 virtual int OnBeforeSendHeaders(URLRequest* request,
3912 const CompletionCallback& callback,
3913 HttpRequestHeaders* headers) OVERRIDE {
3914 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3915 return RunCallbackAsynchronously(request, callback);
3918 virtual int OnHeadersReceived(
3919 URLRequest* request,
3920 const CompletionCallback& callback,
3921 const HttpResponseHeaders* original_response_headers,
3922 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE {
3923 TestNetworkDelegate::OnHeadersReceived(request, callback,
3924 original_response_headers,
3925 override_response_headers);
3926 return RunCallbackAsynchronously(request, callback);
3929 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
3930 URLRequest* request,
3931 const AuthChallengeInfo& auth_info,
3932 const AuthCallback& callback,
3933 AuthCredentials* credentials) OVERRIDE {
3934 AsyncDelegateLogger::Run(
3935 request,
3936 LOAD_STATE_WAITING_FOR_DELEGATE,
3937 LOAD_STATE_WAITING_FOR_DELEGATE,
3938 LOAD_STATE_WAITING_FOR_DELEGATE,
3939 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
3940 callback, credentials));
3941 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
3944 private:
3945 static int RunCallbackAsynchronously(
3946 URLRequest* request,
3947 const CompletionCallback& callback) {
3948 AsyncDelegateLogger::Run(
3949 request,
3950 LOAD_STATE_WAITING_FOR_DELEGATE,
3951 LOAD_STATE_WAITING_FOR_DELEGATE,
3952 LOAD_STATE_WAITING_FOR_DELEGATE,
3953 base::Bind(callback, OK));
3954 return ERR_IO_PENDING;
3957 static void SetAuthAndResume(const AuthCallback& callback,
3958 AuthCredentials* credentials) {
3959 *credentials = AuthCredentials(kUser, kSecret);
3960 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3963 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
3966 // URLRequest::Delegate that logs delegate information when the headers
3967 // are received, when each read completes, and during redirects. Uses
3968 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
3970 // Inherits from TestDelegate to reuse the TestDelegate code to handle
3971 // advancing to the next step in most cases, as well as cancellation.
3972 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
3973 public:
3974 enum CancelStage {
3975 NO_CANCEL = 0,
3976 CANCEL_ON_RECEIVED_REDIRECT,
3977 CANCEL_ON_RESPONSE_STARTED,
3978 CANCEL_ON_READ_COMPLETED
3981 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
3982 : cancel_stage_(cancel_stage) {
3983 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
3984 set_cancel_in_received_redirect(true);
3985 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
3986 set_cancel_in_response_started(true);
3987 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
3988 set_cancel_in_received_data(true);
3990 virtual ~AsyncLoggingUrlRequestDelegate() {}
3992 // URLRequest::Delegate implementation:
3993 void virtual OnReceivedRedirect(URLRequest* request,
3994 const GURL& new_url,
3995 bool* defer_redirect) OVERRIDE {
3996 *defer_redirect = true;
3997 AsyncDelegateLogger::Run(
3998 request,
3999 LOAD_STATE_WAITING_FOR_DELEGATE,
4000 LOAD_STATE_WAITING_FOR_DELEGATE,
4001 LOAD_STATE_WAITING_FOR_DELEGATE,
4002 base::Bind(
4003 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4004 base::Unretained(this), request, new_url));
4007 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4008 AsyncDelegateLogger::Run(
4009 request,
4010 LOAD_STATE_WAITING_FOR_DELEGATE,
4011 LOAD_STATE_WAITING_FOR_DELEGATE,
4012 LOAD_STATE_WAITING_FOR_DELEGATE,
4013 base::Bind(
4014 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4015 base::Unretained(this), request));
4018 virtual void OnReadCompleted(URLRequest* request,
4019 int bytes_read) OVERRIDE {
4020 AsyncDelegateLogger::Run(
4021 request,
4022 LOAD_STATE_IDLE,
4023 LOAD_STATE_IDLE,
4024 LOAD_STATE_IDLE,
4025 base::Bind(
4026 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4027 base::Unretained(this), request, bytes_read));
4030 private:
4031 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4032 const GURL& new_url) {
4033 bool defer_redirect = false;
4034 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
4035 // FollowDeferredRedirect should not be called after cancellation.
4036 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4037 return;
4038 if (!defer_redirect)
4039 request->FollowDeferredRedirect();
4042 void OnResponseStartedLoggingComplete(URLRequest* request) {
4043 // The parent class continues the request.
4044 TestDelegate::OnResponseStarted(request);
4047 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4048 // The parent class continues the request.
4049 TestDelegate::OnReadCompleted(request, bytes_read);
4052 const CancelStage cancel_stage_;
4054 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4057 // Tests handling of delegate info before a request starts.
4058 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4059 ASSERT_TRUE(test_server_.Start());
4061 TestDelegate request_delegate;
4062 TestURLRequestContext context(true);
4063 context.set_network_delegate(NULL);
4064 context.set_net_log(&net_log_);
4065 context.Init();
4068 URLRequest r(test_server_.GetURL("empty.html"),
4069 DEFAULT_PRIORITY,
4070 &request_delegate,
4071 &context);
4072 LoadStateWithParam load_state = r.GetLoadState();
4073 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4074 EXPECT_EQ(base::string16(), load_state.param);
4076 AsyncDelegateLogger::Run(
4078 LOAD_STATE_WAITING_FOR_DELEGATE,
4079 LOAD_STATE_WAITING_FOR_DELEGATE,
4080 LOAD_STATE_IDLE,
4081 base::Bind(&URLRequest::Start, base::Unretained(&r)));
4083 base::RunLoop().Run();
4085 EXPECT_EQ(200, r.GetResponseCode());
4086 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4089 CapturingNetLog::CapturedEntryList entries;
4090 net_log_.GetEntries(&entries);
4091 size_t log_position = ExpectLogContainsSomewhereAfter(
4092 entries,
4094 NetLog::TYPE_DELEGATE_INFO,
4095 NetLog::PHASE_BEGIN);
4097 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4099 // Nothing else should add any delegate info to the request.
4100 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4101 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4104 // Tests handling of delegate info from a network delegate.
4105 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4106 ASSERT_TRUE(test_server_.Start());
4108 TestDelegate request_delegate;
4109 AsyncLoggingNetworkDelegate network_delegate;
4110 TestURLRequestContext context(true);
4111 context.set_network_delegate(&network_delegate);
4112 context.set_net_log(&net_log_);
4113 context.Init();
4116 URLRequest r(test_server_.GetURL("simple.html"),
4117 DEFAULT_PRIORITY,
4118 &request_delegate,
4119 &context);
4120 LoadStateWithParam load_state = r.GetLoadState();
4121 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4122 EXPECT_EQ(base::string16(), load_state.param);
4124 r.Start();
4125 base::RunLoop().Run();
4127 EXPECT_EQ(200, r.GetResponseCode());
4128 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4129 EXPECT_EQ(1, network_delegate.created_requests());
4130 EXPECT_EQ(0, network_delegate.destroyed_requests());
4132 EXPECT_EQ(1, network_delegate.destroyed_requests());
4134 size_t log_position = 0;
4135 CapturingNetLog::CapturedEntryList entries;
4136 net_log_.GetEntries(&entries);
4137 for (size_t i = 0; i < 3; ++i) {
4138 log_position = ExpectLogContainsSomewhereAfter(
4139 entries,
4140 log_position + 1,
4141 NetLog::TYPE_URL_REQUEST_DELEGATE,
4142 NetLog::PHASE_BEGIN);
4144 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4145 log_position + 1);
4147 ASSERT_LT(log_position, entries.size());
4148 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4149 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4151 if (i == 1) {
4152 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4153 entries, log_position + 1);
4157 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4158 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4161 // Tests handling of delegate info from a network delegate in the case of an
4162 // HTTP redirect.
4163 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4164 ASSERT_TRUE(test_server_.Start());
4166 TestDelegate request_delegate;
4167 AsyncLoggingNetworkDelegate network_delegate;
4168 TestURLRequestContext context(true);
4169 context.set_network_delegate(&network_delegate);
4170 context.set_net_log(&net_log_);
4171 context.Init();
4174 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4175 DEFAULT_PRIORITY,
4176 &request_delegate,
4177 &context);
4178 LoadStateWithParam load_state = r.GetLoadState();
4179 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4180 EXPECT_EQ(base::string16(), load_state.param);
4182 r.Start();
4183 base::RunLoop().Run();
4185 EXPECT_EQ(200, r.GetResponseCode());
4186 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4187 EXPECT_EQ(2, network_delegate.created_requests());
4188 EXPECT_EQ(0, network_delegate.destroyed_requests());
4190 EXPECT_EQ(1, network_delegate.destroyed_requests());
4192 size_t log_position = 0;
4193 CapturingNetLog::CapturedEntryList entries;
4194 net_log_.GetEntries(&entries);
4195 // The NetworkDelegate logged information in OnBeforeURLRequest,
4196 // OnBeforeSendHeaders, and OnHeadersReceived.
4197 for (size_t i = 0; i < 3; ++i) {
4198 log_position = ExpectLogContainsSomewhereAfter(
4199 entries,
4200 log_position + 1,
4201 NetLog::TYPE_URL_REQUEST_DELEGATE,
4202 NetLog::PHASE_BEGIN);
4204 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4205 log_position + 1);
4207 ASSERT_LT(log_position, entries.size());
4208 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4209 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4211 if (i == 1) {
4212 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4213 entries, log_position + 1);
4217 // The URLRequest::Delegate then gets informed about the redirect.
4218 log_position = ExpectLogContainsSomewhereAfter(
4219 entries,
4220 log_position + 1,
4221 NetLog::TYPE_URL_REQUEST_DELEGATE,
4222 NetLog::PHASE_BEGIN);
4224 // The NetworkDelegate logged information in the same three events as before.
4225 for (size_t i = 0; i < 3; ++i) {
4226 log_position = ExpectLogContainsSomewhereAfter(
4227 entries,
4228 log_position + 1,
4229 NetLog::TYPE_URL_REQUEST_DELEGATE,
4230 NetLog::PHASE_BEGIN);
4232 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4233 log_position + 1);
4235 ASSERT_LT(log_position, entries.size());
4236 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4237 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4240 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4241 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4244 // Tests handling of delegate info from a network delegate in the case of HTTP
4245 // AUTH.
4246 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4247 ASSERT_TRUE(test_server_.Start());
4249 TestDelegate request_delegate;
4250 AsyncLoggingNetworkDelegate network_delegate;
4251 TestURLRequestContext context(true);
4252 context.set_network_delegate(&network_delegate);
4253 context.set_net_log(&net_log_);
4254 context.Init();
4257 URLRequest r(test_server_.GetURL("auth-basic"),
4258 DEFAULT_PRIORITY,
4259 &request_delegate,
4260 &context);
4261 LoadStateWithParam load_state = r.GetLoadState();
4262 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4263 EXPECT_EQ(base::string16(), load_state.param);
4265 r.Start();
4266 base::RunLoop().Run();
4268 EXPECT_EQ(200, r.GetResponseCode());
4269 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4270 EXPECT_EQ(1, network_delegate.created_requests());
4271 EXPECT_EQ(0, network_delegate.destroyed_requests());
4273 EXPECT_EQ(1, network_delegate.destroyed_requests());
4275 size_t log_position = 0;
4276 CapturingNetLog::CapturedEntryList entries;
4277 net_log_.GetEntries(&entries);
4278 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4279 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4280 // OnBeforeURLRequest and OnBeforeSendHeaders.
4281 for (size_t i = 0; i < 6; ++i) {
4282 log_position = ExpectLogContainsSomewhereAfter(
4283 entries,
4284 log_position + 1,
4285 NetLog::TYPE_URL_REQUEST_DELEGATE,
4286 NetLog::PHASE_BEGIN);
4288 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4289 log_position + 1);
4291 ASSERT_LT(log_position, entries.size());
4292 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4293 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4295 if (i == 1) {
4296 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4297 entries, log_position + 1);
4301 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4302 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4305 // Tests handling of delegate info from a URLRequest::Delegate.
4306 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4307 ASSERT_TRUE(test_server_.Start());
4309 AsyncLoggingUrlRequestDelegate request_delegate(
4310 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4311 TestURLRequestContext context(true);
4312 context.set_network_delegate(NULL);
4313 context.set_net_log(&net_log_);
4314 context.Init();
4317 // A chunked response with delays between chunks is used to make sure that
4318 // attempts by the URLRequest delegate to log information while reading the
4319 // body are ignored. Since they are ignored, this test is robust against
4320 // the possibility of multiple reads being combined in the unlikely event
4321 // that it occurs.
4322 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
4323 DEFAULT_PRIORITY,
4324 &request_delegate,
4325 &context);
4326 LoadStateWithParam load_state = r.GetLoadState();
4327 r.Start();
4328 base::RunLoop().Run();
4330 EXPECT_EQ(200, r.GetResponseCode());
4331 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4334 CapturingNetLog::CapturedEntryList entries;
4335 net_log_.GetEntries(&entries);
4337 size_t log_position = 0;
4339 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4340 entries, log_position);
4342 // The delegate info should only have been logged on header complete. Other
4343 // times it should silently be ignored.
4344 log_position =
4345 ExpectLogContainsSomewhereAfter(entries,
4346 log_position + 1,
4347 NetLog::TYPE_URL_REQUEST_DELEGATE,
4348 NetLog::PHASE_BEGIN);
4350 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4351 log_position + 1);
4353 ASSERT_LT(log_position, entries.size());
4354 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4355 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4357 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4358 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4359 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4360 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4363 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4364 // an HTTP redirect.
4365 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4366 ASSERT_TRUE(test_server_.Start());
4368 AsyncLoggingUrlRequestDelegate request_delegate(
4369 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4370 TestURLRequestContext context(true);
4371 context.set_network_delegate(NULL);
4372 context.set_net_log(&net_log_);
4373 context.Init();
4376 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4377 DEFAULT_PRIORITY,
4378 &request_delegate,
4379 &context);
4380 LoadStateWithParam load_state = r.GetLoadState();
4381 r.Start();
4382 base::RunLoop().Run();
4384 EXPECT_EQ(200, r.GetResponseCode());
4385 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4388 CapturingNetLog::CapturedEntryList entries;
4389 net_log_.GetEntries(&entries);
4391 // Delegate info should only have been logged in OnReceivedRedirect and
4392 // OnResponseStarted.
4393 size_t log_position = 0;
4394 for (int i = 0; i < 2; ++i) {
4395 if (i == 0) {
4396 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4397 entries, log_position) + 1;
4400 log_position = ExpectLogContainsSomewhereAfter(
4401 entries,
4402 log_position,
4403 NetLog::TYPE_URL_REQUEST_DELEGATE,
4404 NetLog::PHASE_BEGIN);
4406 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4407 log_position + 1);
4409 ASSERT_LT(log_position, entries.size());
4410 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4411 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4414 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4415 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4416 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4417 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4420 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4421 // an HTTP redirect, with cancellation at various points.
4422 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4423 ASSERT_TRUE(test_server_.Start());
4425 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4426 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4427 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4428 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4431 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4432 ++test_case) {
4433 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4434 TestURLRequestContext context(true);
4435 CapturingNetLog net_log;
4436 context.set_network_delegate(NULL);
4437 context.set_net_log(&net_log);
4438 context.Init();
4441 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4442 DEFAULT_PRIORITY,
4443 &request_delegate,
4444 &context);
4445 LoadStateWithParam load_state = r.GetLoadState();
4446 r.Start();
4447 base::RunLoop().Run();
4448 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4451 CapturingNetLog::CapturedEntryList entries;
4452 net_log.GetEntries(&entries);
4454 // Delegate info is always logged in both OnReceivedRedirect and
4455 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4456 // OnResponseStarted delegate call is after cancellation, but logging is
4457 // still currently supported in that call.
4458 size_t log_position = 0;
4459 for (int i = 0; i < 2; ++i) {
4460 if (i == 0) {
4461 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4462 entries, log_position) + 1;
4465 log_position = ExpectLogContainsSomewhereAfter(
4466 entries,
4467 log_position,
4468 NetLog::TYPE_URL_REQUEST_DELEGATE,
4469 NetLog::PHASE_BEGIN);
4471 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4472 log_position + 1);
4474 ASSERT_LT(log_position, entries.size());
4475 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4476 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4479 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4480 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4481 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4482 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4486 namespace {
4488 const char kExtraHeader[] = "Allow-Snafu";
4489 const char kExtraValue[] = "fubar";
4491 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
4492 virtual void OnReceivedRedirect(net::URLRequest* request,
4493 const GURL& new_url,
4494 bool* defer_redirect) OVERRIDE {
4495 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4496 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4500 } // namespace
4502 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4503 ASSERT_TRUE(test_server_.Start());
4505 GURL destination_url = test_server_.GetURL(
4506 "echoheader?" + std::string(kExtraHeader));
4507 GURL original_url = test_server_.GetURL(
4508 "server-redirect?" + destination_url.spec());
4509 RedirectWithAdditionalHeadersDelegate d;
4510 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4511 req.Start();
4512 base::RunLoop().Run();
4514 std::string value;
4515 const HttpRequestHeaders& headers = req.extra_request_headers();
4516 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4517 EXPECT_EQ(kExtraValue, value);
4518 EXPECT_FALSE(req.is_pending());
4519 EXPECT_FALSE(req.is_redirecting());
4520 EXPECT_EQ(kExtraValue, d.data_received());
4523 namespace {
4525 const char kExtraHeaderToRemove[] = "To-Be-Removed";
4527 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
4528 virtual void OnReceivedRedirect(net::URLRequest* request,
4529 const GURL& new_url,
4530 bool* defer_redirect) OVERRIDE {
4531 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4532 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4536 } // namespace
4538 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4539 ASSERT_TRUE(test_server_.Start());
4541 GURL destination_url = test_server_.GetURL(
4542 "echoheader?" + std::string(kExtraHeaderToRemove));
4543 GURL original_url = test_server_.GetURL(
4544 "server-redirect?" + destination_url.spec());
4545 RedirectWithHeaderRemovalDelegate d;
4546 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4547 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4548 req.Start();
4549 base::RunLoop().Run();
4551 std::string value;
4552 const HttpRequestHeaders& headers = req.extra_request_headers();
4553 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4554 EXPECT_FALSE(req.is_pending());
4555 EXPECT_FALSE(req.is_redirecting());
4556 EXPECT_EQ("None", d.data_received());
4559 TEST_F(URLRequestTestHTTP, CancelTest) {
4560 TestDelegate d;
4562 URLRequest r(GURL("http://www.google.com/"),
4563 DEFAULT_PRIORITY,
4565 &default_context_);
4567 r.Start();
4568 EXPECT_TRUE(r.is_pending());
4570 r.Cancel();
4572 base::RunLoop().Run();
4574 // We expect to receive OnResponseStarted even though the request has been
4575 // cancelled.
4576 EXPECT_EQ(1, d.response_started_count());
4577 EXPECT_EQ(0, d.bytes_received());
4578 EXPECT_FALSE(d.received_data_before_response());
4582 TEST_F(URLRequestTestHTTP, CancelTest2) {
4583 ASSERT_TRUE(test_server_.Start());
4585 TestDelegate d;
4587 URLRequest r(test_server_.GetURL(std::string()),
4588 DEFAULT_PRIORITY,
4590 &default_context_);
4592 d.set_cancel_in_response_started(true);
4594 r.Start();
4595 EXPECT_TRUE(r.is_pending());
4597 base::RunLoop().Run();
4599 EXPECT_EQ(1, d.response_started_count());
4600 EXPECT_EQ(0, d.bytes_received());
4601 EXPECT_FALSE(d.received_data_before_response());
4602 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4606 TEST_F(URLRequestTestHTTP, CancelTest3) {
4607 ASSERT_TRUE(test_server_.Start());
4609 TestDelegate d;
4611 URLRequest r(test_server_.GetURL(std::string()),
4612 DEFAULT_PRIORITY,
4614 &default_context_);
4616 d.set_cancel_in_received_data(true);
4618 r.Start();
4619 EXPECT_TRUE(r.is_pending());
4621 base::RunLoop().Run();
4623 EXPECT_EQ(1, d.response_started_count());
4624 // There is no guarantee about how much data was received
4625 // before the cancel was issued. It could have been 0 bytes,
4626 // or it could have been all the bytes.
4627 // EXPECT_EQ(0, d.bytes_received());
4628 EXPECT_FALSE(d.received_data_before_response());
4629 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4633 TEST_F(URLRequestTestHTTP, CancelTest4) {
4634 ASSERT_TRUE(test_server_.Start());
4636 TestDelegate d;
4638 URLRequest r(test_server_.GetURL(std::string()),
4639 DEFAULT_PRIORITY,
4641 &default_context_);
4643 r.Start();
4644 EXPECT_TRUE(r.is_pending());
4646 // The request will be implicitly canceled when it is destroyed. The
4647 // test delegate must not post a quit message when this happens because
4648 // this test doesn't actually have a message loop. The quit message would
4649 // get put on this thread's message queue and the next test would exit
4650 // early, causing problems.
4651 d.set_quit_on_complete(false);
4653 // expect things to just cleanup properly.
4655 // we won't actually get a received reponse here because we've never run the
4656 // message loop
4657 EXPECT_FALSE(d.received_data_before_response());
4658 EXPECT_EQ(0, d.bytes_received());
4661 TEST_F(URLRequestTestHTTP, CancelTest5) {
4662 ASSERT_TRUE(test_server_.Start());
4664 // populate cache
4666 TestDelegate d;
4667 URLRequest r(test_server_.GetURL("cachetime"),
4668 DEFAULT_PRIORITY,
4670 &default_context_);
4671 r.Start();
4672 base::RunLoop().Run();
4673 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4676 // cancel read from cache (see bug 990242)
4678 TestDelegate d;
4679 URLRequest r(test_server_.GetURL("cachetime"),
4680 DEFAULT_PRIORITY,
4682 &default_context_);
4683 r.Start();
4684 r.Cancel();
4685 base::RunLoop().Run();
4687 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4688 EXPECT_EQ(1, d.response_started_count());
4689 EXPECT_EQ(0, d.bytes_received());
4690 EXPECT_FALSE(d.received_data_before_response());
4694 TEST_F(URLRequestTestHTTP, PostTest) {
4695 ASSERT_TRUE(test_server_.Start());
4696 HTTPUploadDataOperationTest("POST");
4699 TEST_F(URLRequestTestHTTP, PutTest) {
4700 ASSERT_TRUE(test_server_.Start());
4701 HTTPUploadDataOperationTest("PUT");
4704 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4705 ASSERT_TRUE(test_server_.Start());
4707 TestDelegate d;
4709 URLRequest r(
4710 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4711 r.set_method("POST");
4713 r.Start();
4714 EXPECT_TRUE(r.is_pending());
4716 base::RunLoop().Run();
4718 ASSERT_EQ(1, d.response_started_count())
4719 << "request failed: " << r.status().status()
4720 << ", error: " << r.status().error();
4722 EXPECT_FALSE(d.received_data_before_response());
4723 EXPECT_TRUE(d.data_received().empty());
4727 TEST_F(URLRequestTestHTTP, PostFileTest) {
4728 ASSERT_TRUE(test_server_.Start());
4730 TestDelegate d;
4732 URLRequest r(
4733 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4734 r.set_method("POST");
4736 base::FilePath dir;
4737 PathService::Get(base::DIR_EXE, &dir);
4738 base::SetCurrentDirectory(dir);
4740 ScopedVector<UploadElementReader> element_readers;
4742 base::FilePath path;
4743 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4744 path = path.Append(FILE_PATH_LITERAL("net"));
4745 path = path.Append(FILE_PATH_LITERAL("data"));
4746 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4747 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4748 element_readers.push_back(
4749 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4750 path,
4752 kuint64max,
4753 base::Time()));
4754 r.set_upload(make_scoped_ptr(
4755 new UploadDataStream(element_readers.Pass(), 0)));
4757 r.Start();
4758 EXPECT_TRUE(r.is_pending());
4760 base::RunLoop().Run();
4762 int64 size = 0;
4763 ASSERT_EQ(true, base::GetFileSize(path, &size));
4764 scoped_ptr<char[]> buf(new char[size]);
4766 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
4768 ASSERT_EQ(1, d.response_started_count())
4769 << "request failed: " << r.status().status()
4770 << ", error: " << r.status().error();
4772 EXPECT_FALSE(d.received_data_before_response());
4774 EXPECT_EQ(size, d.bytes_received());
4775 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
4779 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4780 ASSERT_TRUE(test_server_.Start());
4782 TestDelegate d;
4784 URLRequest r(test_server_.GetURL("echo"), DEFAULT_PRIORITY,
4785 &d, &default_context_);
4786 r.set_method("POST");
4788 ScopedVector<UploadElementReader> element_readers;
4790 element_readers.push_back(new UploadFileElementReader(
4791 base::MessageLoopProxy::current().get(),
4792 base::FilePath(FILE_PATH_LITERAL(
4793 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4795 kuint64max,
4796 base::Time()));
4797 r.set_upload(make_scoped_ptr(
4798 new UploadDataStream(element_readers.Pass(), 0)));
4800 r.Start();
4801 EXPECT_TRUE(r.is_pending());
4803 base::RunLoop().Run();
4805 EXPECT_TRUE(d.request_failed());
4806 EXPECT_FALSE(d.received_data_before_response());
4807 EXPECT_EQ(0, d.bytes_received());
4808 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
4809 EXPECT_EQ(ERR_FILE_NOT_FOUND, r.status().error());
4813 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4814 ASSERT_TRUE(test_server_.Start());
4816 TestDelegate d;
4818 URLRequest r(
4819 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4820 r.EnableChunkedUpload();
4821 r.set_method("POST");
4822 AddChunksToUpload(&r);
4823 r.Start();
4824 EXPECT_TRUE(r.is_pending());
4826 base::RunLoop().Run();
4828 VerifyReceivedDataMatchesChunks(&r, &d);
4832 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4833 ASSERT_TRUE(test_server_.Start());
4835 TestDelegate d;
4837 URLRequest r(
4838 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4839 r.EnableChunkedUpload();
4840 r.set_method("POST");
4841 r.Start();
4842 EXPECT_TRUE(r.is_pending());
4843 AddChunksToUpload(&r);
4844 base::RunLoop().Run();
4846 VerifyReceivedDataMatchesChunks(&r, &d);
4850 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4851 ASSERT_TRUE(test_server_.Start());
4853 TestDelegate d;
4855 URLRequest r(
4856 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4857 r.EnableChunkedUpload();
4858 r.set_method("POST");
4859 r.Start();
4860 EXPECT_TRUE(r.is_pending());
4862 base::RunLoop().RunUntilIdle();
4863 AddChunksToUpload(&r);
4864 base::RunLoop().Run();
4866 VerifyReceivedDataMatchesChunks(&r, &d);
4870 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4871 ASSERT_TRUE(test_server_.Start());
4873 TestDelegate d;
4874 URLRequest req(test_server_.GetURL("files/with-headers.html"),
4875 DEFAULT_PRIORITY,
4877 &default_context_);
4878 req.Start();
4879 base::RunLoop().Run();
4881 const HttpResponseHeaders* headers = req.response_headers();
4883 // Simple sanity check that response_info() accesses the same data.
4884 EXPECT_EQ(headers, req.response_info().headers.get());
4886 std::string header;
4887 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4888 EXPECT_EQ("private", header);
4890 header.clear();
4891 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4892 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4894 // The response has two "X-Multiple-Entries" headers.
4895 // This verfies our output has them concatenated together.
4896 header.clear();
4897 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4898 EXPECT_EQ("a, b", header);
4901 TEST_F(URLRequestTestHTTP, ProcessSTS) {
4902 SpawnedTestServer::SSLOptions ssl_options;
4903 SpawnedTestServer https_test_server(
4904 SpawnedTestServer::TYPE_HTTPS,
4905 ssl_options,
4906 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4907 ASSERT_TRUE(https_test_server.Start());
4909 TestDelegate d;
4910 URLRequest request(https_test_server.GetURL("files/hsts-headers.html"),
4911 DEFAULT_PRIORITY,
4913 &default_context_);
4914 request.Start();
4915 base::RunLoop().Run();
4917 TransportSecurityState* security_state =
4918 default_context_.transport_security_state();
4919 bool sni_available = true;
4920 TransportSecurityState::DomainState domain_state;
4921 EXPECT_TRUE(security_state->GetDomainState(
4922 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
4923 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4924 domain_state.upgrade_mode);
4925 EXPECT_TRUE(domain_state.sts_include_subdomains);
4926 EXPECT_FALSE(domain_state.pkp_include_subdomains);
4927 #if defined(OS_ANDROID)
4928 // Android's CertVerifyProc does not (yet) handle pins.
4929 #else
4930 EXPECT_FALSE(domain_state.HasPublicKeyPins());
4931 #endif
4934 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
4935 // reject HPKP headers, and a test setting only HPKP headers will fail (no
4936 // DomainState present because header rejected).
4937 #if defined(OS_ANDROID)
4938 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
4939 #else
4940 #define MAYBE_ProcessPKP ProcessPKP
4941 #endif
4943 // Tests that enabling HPKP on a domain does not affect the HSTS
4944 // validity/expiration.
4945 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
4946 SpawnedTestServer::SSLOptions ssl_options;
4947 SpawnedTestServer https_test_server(
4948 SpawnedTestServer::TYPE_HTTPS,
4949 ssl_options,
4950 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4951 ASSERT_TRUE(https_test_server.Start());
4953 TestDelegate d;
4954 URLRequest request(https_test_server.GetURL("files/hpkp-headers.html"),
4955 DEFAULT_PRIORITY,
4957 &default_context_);
4958 request.Start();
4959 base::RunLoop().Run();
4961 TransportSecurityState* security_state =
4962 default_context_.transport_security_state();
4963 bool sni_available = true;
4964 TransportSecurityState::DomainState domain_state;
4965 EXPECT_TRUE(security_state->GetDomainState(
4966 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
4967 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
4968 domain_state.upgrade_mode);
4969 EXPECT_FALSE(domain_state.sts_include_subdomains);
4970 EXPECT_FALSE(domain_state.pkp_include_subdomains);
4971 EXPECT_TRUE(domain_state.HasPublicKeyPins());
4972 EXPECT_NE(domain_state.upgrade_expiry,
4973 domain_state.dynamic_spki_hashes_expiry);
4976 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
4977 SpawnedTestServer::SSLOptions ssl_options;
4978 SpawnedTestServer https_test_server(
4979 SpawnedTestServer::TYPE_HTTPS,
4980 ssl_options,
4981 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4982 ASSERT_TRUE(https_test_server.Start());
4984 TestDelegate d;
4985 URLRequest request(
4986 https_test_server.GetURL("files/hsts-multiple-headers.html"),
4987 DEFAULT_PRIORITY,
4989 &default_context_);
4990 request.Start();
4991 base::RunLoop().Run();
4993 // We should have set parameters from the first header, not the second.
4994 TransportSecurityState* security_state =
4995 default_context_.transport_security_state();
4996 bool sni_available = true;
4997 TransportSecurityState::DomainState domain_state;
4998 EXPECT_TRUE(security_state->GetDomainState(
4999 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
5000 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5001 domain_state.upgrade_mode);
5002 EXPECT_FALSE(domain_state.sts_include_subdomains);
5003 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5006 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5007 SpawnedTestServer::SSLOptions ssl_options;
5008 SpawnedTestServer https_test_server(
5009 SpawnedTestServer::TYPE_HTTPS,
5010 ssl_options,
5011 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5012 ASSERT_TRUE(https_test_server.Start());
5014 TestDelegate d;
5015 URLRequest request(
5016 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5017 DEFAULT_PRIORITY,
5019 &default_context_);
5020 request.Start();
5021 base::RunLoop().Run();
5023 // We should have set parameters from the first header, not the second.
5024 TransportSecurityState* security_state =
5025 default_context_.transport_security_state();
5026 bool sni_available = true;
5027 TransportSecurityState::DomainState domain_state;
5028 EXPECT_TRUE(security_state->GetDomainState(
5029 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
5030 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5031 domain_state.upgrade_mode);
5032 #if defined(OS_ANDROID)
5033 // Android's CertVerifyProc does not (yet) handle pins.
5034 #else
5035 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5036 #endif
5037 EXPECT_NE(domain_state.upgrade_expiry,
5038 domain_state.dynamic_spki_hashes_expiry);
5040 // Even though there is an HSTS header asserting includeSubdomains, it is
5041 // the *second* such header, and we MUST process only the first.
5042 EXPECT_FALSE(domain_state.sts_include_subdomains);
5043 // includeSubdomains does not occur in the test HPKP header.
5044 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5047 // Tests that when multiple HPKP headers are present, asserting different
5048 // policies, that only the first such policy is processed.
5049 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5050 SpawnedTestServer::SSLOptions ssl_options;
5051 SpawnedTestServer https_test_server(
5052 SpawnedTestServer::TYPE_HTTPS,
5053 ssl_options,
5054 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5055 ASSERT_TRUE(https_test_server.Start());
5057 TestDelegate d;
5058 URLRequest request(
5059 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5060 DEFAULT_PRIORITY,
5062 &default_context_);
5063 request.Start();
5064 base::RunLoop().Run();
5066 TransportSecurityState* security_state =
5067 default_context_.transport_security_state();
5068 bool sni_available = true;
5069 TransportSecurityState::DomainState domain_state;
5070 EXPECT_TRUE(security_state->GetDomainState(
5071 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
5072 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5073 domain_state.upgrade_mode);
5074 #if defined(OS_ANDROID)
5075 // Android's CertVerifyProc does not (yet) handle pins.
5076 #else
5077 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5078 #endif
5079 EXPECT_NE(domain_state.upgrade_expiry,
5080 domain_state.dynamic_spki_hashes_expiry);
5082 EXPECT_TRUE(domain_state.sts_include_subdomains);
5083 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5086 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5087 ASSERT_TRUE(test_server_.Start());
5089 TestDelegate d;
5090 URLRequest req(test_server_.GetURL("files/content-type-normalization.html"),
5091 DEFAULT_PRIORITY,
5093 &default_context_);
5094 req.Start();
5095 base::RunLoop().Run();
5097 std::string mime_type;
5098 req.GetMimeType(&mime_type);
5099 EXPECT_EQ("text/html", mime_type);
5101 std::string charset;
5102 req.GetCharset(&charset);
5103 EXPECT_EQ("utf-8", charset);
5104 req.Cancel();
5107 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictRedirects) {
5108 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5109 GURL file_url("file:///foo.txt");
5110 GURL data_url("data:,foo");
5111 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5112 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5113 DataProtocolHandler data_protocol_handler;
5114 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5116 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5117 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
5118 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
5121 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5122 ASSERT_TRUE(test_server_.Start());
5124 TestDelegate d;
5125 URLRequest req(test_server_.GetURL("files/redirect-to-file.html"),
5126 DEFAULT_PRIORITY,
5128 &default_context_);
5129 req.Start();
5130 base::RunLoop().Run();
5132 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5133 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5136 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5137 ASSERT_TRUE(test_server_.Start());
5139 TestDelegate d;
5140 URLRequest req(test_server_.GetURL("files/redirect-to-data.html"),
5141 DEFAULT_PRIORITY,
5143 &default_context_);
5144 req.Start();
5145 base::MessageLoop::current()->Run();
5147 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5148 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5151 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5152 ASSERT_TRUE(test_server_.Start());
5154 TestDelegate d;
5155 URLRequest req(test_server_.GetURL("files/redirect-to-invalid-url.html"),
5156 DEFAULT_PRIORITY,
5158 &default_context_);
5159 req.Start();
5160 base::RunLoop().Run();
5162 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5163 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
5166 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5167 ASSERT_TRUE(test_server_.Start());
5169 TestDelegate d;
5170 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5171 DEFAULT_PRIORITY,
5173 &default_context_);
5174 req.SetReferrer("http://user:pass@foo.com/");
5175 req.Start();
5176 base::RunLoop().Run();
5178 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5181 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5182 ASSERT_TRUE(test_server_.Start());
5184 TestDelegate d;
5185 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5186 DEFAULT_PRIORITY,
5188 &default_context_);
5189 req.SetReferrer("http://foo.com/test#fragment");
5190 req.Start();
5191 base::RunLoop().Run();
5193 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5196 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5197 ASSERT_TRUE(test_server_.Start());
5199 TestDelegate d;
5200 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5201 DEFAULT_PRIORITY,
5203 &default_context_);
5204 req.SetReferrer("http://foo.com/test#fragment");
5205 req.SetReferrer("");
5206 req.Start();
5207 base::RunLoop().Run();
5209 EXPECT_EQ(std::string("None"), d.data_received());
5212 // Defer network start and then resume, checking that the request was a success
5213 // and bytes were received.
5214 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5215 ASSERT_TRUE(test_server_.Start());
5217 TestDelegate d;
5219 d.set_quit_on_network_start(true);
5220 GURL test_url(test_server_.GetURL("echo"));
5221 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5223 req.Start();
5224 base::RunLoop().Run();
5226 EXPECT_EQ(1, d.received_before_network_start_count());
5227 EXPECT_EQ(0, d.response_started_count());
5229 req.ResumeNetworkStart();
5230 base::RunLoop().Run();
5232 EXPECT_EQ(1, d.response_started_count());
5233 EXPECT_NE(0, d.bytes_received());
5234 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5238 // Check that OnBeforeNetworkStart is only called once even if there is a
5239 // redirect.
5240 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5241 ASSERT_TRUE(test_server_.Start());
5243 TestDelegate d;
5245 d.set_quit_on_redirect(true);
5246 d.set_quit_on_network_start(true);
5247 URLRequest req(test_server_.GetURL("server-redirect?echo"),
5248 DEFAULT_PRIORITY,
5250 &default_context_);
5252 req.Start();
5253 base::RunLoop().Run();
5255 EXPECT_EQ(1, d.received_before_network_start_count());
5256 EXPECT_EQ(0, d.response_started_count());
5257 EXPECT_EQ(0, d.received_redirect_count());
5259 req.ResumeNetworkStart();
5260 base::RunLoop().Run();
5262 EXPECT_EQ(1, d.received_redirect_count());
5263 req.FollowDeferredRedirect();
5264 base::RunLoop().Run();
5266 // Check that the redirect's new network transaction does not get propagated
5267 // to a second OnBeforeNetworkStart() notification.
5268 EXPECT_EQ(1, d.received_before_network_start_count());
5270 EXPECT_EQ(1, d.response_started_count());
5271 EXPECT_NE(0, d.bytes_received());
5272 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5276 // Cancel the request after learning that the request would use the network.
5277 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5278 ASSERT_TRUE(test_server_.Start());
5280 TestDelegate d;
5282 d.set_quit_on_network_start(true);
5283 GURL test_url(test_server_.GetURL("echo"));
5284 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5286 req.Start();
5287 base::RunLoop().Run();
5289 EXPECT_EQ(1, d.received_before_network_start_count());
5290 EXPECT_EQ(0, d.response_started_count());
5292 req.Cancel();
5293 base::RunLoop().Run();
5295 EXPECT_EQ(1, d.response_started_count());
5296 EXPECT_EQ(0, d.bytes_received());
5297 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5301 TEST_F(URLRequestTestHTTP, CancelRedirect) {
5302 ASSERT_TRUE(test_server_.Start());
5304 TestDelegate d;
5306 d.set_cancel_in_received_redirect(true);
5307 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5308 DEFAULT_PRIORITY,
5310 &default_context_);
5311 req.Start();
5312 base::RunLoop().Run();
5314 EXPECT_EQ(1, d.response_started_count());
5315 EXPECT_EQ(0, d.bytes_received());
5316 EXPECT_FALSE(d.received_data_before_response());
5317 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5321 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5322 ASSERT_TRUE(test_server_.Start());
5324 TestDelegate d;
5326 d.set_quit_on_redirect(true);
5327 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5328 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5330 req.Start();
5331 base::RunLoop().Run();
5333 EXPECT_EQ(1, d.received_redirect_count());
5335 req.FollowDeferredRedirect();
5336 base::RunLoop().Run();
5338 EXPECT_EQ(1, d.response_started_count());
5339 EXPECT_FALSE(d.received_data_before_response());
5340 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5342 base::FilePath path;
5343 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5344 path = path.Append(FILE_PATH_LITERAL("net"));
5345 path = path.Append(FILE_PATH_LITERAL("data"));
5346 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5347 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5349 std::string contents;
5350 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5351 EXPECT_EQ(contents, d.data_received());
5355 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5356 ASSERT_TRUE(test_server_.Start());
5358 TestDelegate d;
5360 d.set_quit_on_redirect(true);
5361 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5362 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5364 EXPECT_FALSE(d.have_full_request_headers());
5366 req.Start();
5367 base::RunLoop().Run();
5369 EXPECT_EQ(1, d.received_redirect_count());
5370 EXPECT_TRUE(d.have_full_request_headers());
5371 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5372 d.ClearFullRequestHeaders();
5374 req.FollowDeferredRedirect();
5375 base::RunLoop().Run();
5377 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5378 EXPECT_EQ(1, d.response_started_count());
5379 EXPECT_TRUE(d.have_full_request_headers());
5380 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5381 EXPECT_FALSE(d.received_data_before_response());
5382 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5384 base::FilePath path;
5385 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5386 path = path.Append(FILE_PATH_LITERAL("net"));
5387 path = path.Append(FILE_PATH_LITERAL("data"));
5388 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5389 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5391 std::string contents;
5392 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5393 EXPECT_EQ(contents, d.data_received());
5397 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5398 ASSERT_TRUE(test_server_.Start());
5400 TestDelegate d;
5402 d.set_quit_on_redirect(true);
5403 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5404 DEFAULT_PRIORITY,
5406 &default_context_);
5407 req.Start();
5408 base::RunLoop().Run();
5410 EXPECT_EQ(1, d.received_redirect_count());
5412 req.Cancel();
5413 base::RunLoop().Run();
5415 EXPECT_EQ(1, d.response_started_count());
5416 EXPECT_EQ(0, d.bytes_received());
5417 EXPECT_FALSE(d.received_data_before_response());
5418 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5422 TEST_F(URLRequestTestHTTP, VaryHeader) {
5423 ASSERT_TRUE(test_server_.Start());
5425 // Populate the cache.
5427 TestDelegate d;
5428 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5429 DEFAULT_PRIORITY,
5431 &default_context_);
5432 HttpRequestHeaders headers;
5433 headers.SetHeader("foo", "1");
5434 req.SetExtraRequestHeaders(headers);
5435 req.Start();
5436 base::RunLoop().Run();
5438 LoadTimingInfo load_timing_info;
5439 req.GetLoadTimingInfo(&load_timing_info);
5440 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5443 // Expect a cache hit.
5445 TestDelegate d;
5446 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5447 DEFAULT_PRIORITY,
5449 &default_context_);
5450 HttpRequestHeaders headers;
5451 headers.SetHeader("foo", "1");
5452 req.SetExtraRequestHeaders(headers);
5453 req.Start();
5454 base::RunLoop().Run();
5456 EXPECT_TRUE(req.was_cached());
5458 LoadTimingInfo load_timing_info;
5459 req.GetLoadTimingInfo(&load_timing_info);
5460 TestLoadTimingCacheHitNoNetwork(load_timing_info);
5463 // Expect a cache miss.
5465 TestDelegate d;
5466 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5467 DEFAULT_PRIORITY,
5469 &default_context_);
5470 HttpRequestHeaders headers;
5471 headers.SetHeader("foo", "2");
5472 req.SetExtraRequestHeaders(headers);
5473 req.Start();
5474 base::RunLoop().Run();
5476 EXPECT_FALSE(req.was_cached());
5478 LoadTimingInfo load_timing_info;
5479 req.GetLoadTimingInfo(&load_timing_info);
5480 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5484 TEST_F(URLRequestTestHTTP, BasicAuth) {
5485 ASSERT_TRUE(test_server_.Start());
5487 // populate the cache
5489 TestDelegate d;
5490 d.set_credentials(AuthCredentials(kUser, kSecret));
5492 URLRequest r(test_server_.GetURL("auth-basic"),
5493 DEFAULT_PRIORITY,
5495 &default_context_);
5496 r.Start();
5498 base::RunLoop().Run();
5500 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5503 // repeat request with end-to-end validation. since auth-basic results in a
5504 // cachable page, we expect this test to result in a 304. in which case, the
5505 // response should be fetched from the cache.
5507 TestDelegate d;
5508 d.set_credentials(AuthCredentials(kUser, kSecret));
5510 URLRequest r(test_server_.GetURL("auth-basic"),
5511 DEFAULT_PRIORITY,
5513 &default_context_);
5514 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5515 r.Start();
5517 base::RunLoop().Run();
5519 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5521 // Should be the same cached document.
5522 EXPECT_TRUE(r.was_cached());
5526 // Check that Set-Cookie headers in 401 responses are respected.
5527 // http://crbug.com/6450
5528 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5529 ASSERT_TRUE(test_server_.Start());
5531 GURL url_requiring_auth =
5532 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5534 // Request a page that will give a 401 containing a Set-Cookie header.
5535 // Verify that when the transaction is restarted, it includes the new cookie.
5537 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5538 TestURLRequestContext context(true);
5539 context.set_network_delegate(&network_delegate);
5540 context.Init();
5542 TestDelegate d;
5543 d.set_credentials(AuthCredentials(kUser, kSecret));
5545 URLRequest r(url_requiring_auth, DEFAULT_PRIORITY, &d, &context);
5546 r.Start();
5548 base::RunLoop().Run();
5550 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5552 // Make sure we sent the cookie in the restarted transaction.
5553 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5554 != std::string::npos);
5557 // Same test as above, except this time the restart is initiated earlier
5558 // (without user intervention since identity is embedded in the URL).
5560 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5561 TestURLRequestContext context(true);
5562 context.set_network_delegate(&network_delegate);
5563 context.Init();
5565 TestDelegate d;
5567 GURL::Replacements replacements;
5568 std::string username("user2");
5569 std::string password("secret");
5570 replacements.SetUsernameStr(username);
5571 replacements.SetPasswordStr(password);
5572 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5574 URLRequest r(url_with_identity, DEFAULT_PRIORITY, &d, &context);
5575 r.Start();
5577 base::RunLoop().Run();
5579 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5581 // Make sure we sent the cookie in the restarted transaction.
5582 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5583 != std::string::npos);
5587 // Tests that load timing works as expected with auth and the cache.
5588 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5589 ASSERT_TRUE(test_server_.Start());
5591 // populate the cache
5593 TestDelegate d;
5594 d.set_credentials(AuthCredentials(kUser, kSecret));
5596 URLRequest r(test_server_.GetURL("auth-basic"),
5597 DEFAULT_PRIORITY,
5599 &default_context_);
5600 r.Start();
5602 base::RunLoop().Run();
5604 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5606 LoadTimingInfo load_timing_info_before_auth;
5607 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5608 &load_timing_info_before_auth));
5609 TestLoadTimingNotReused(load_timing_info_before_auth,
5610 CONNECT_TIMING_HAS_DNS_TIMES);
5612 LoadTimingInfo load_timing_info;
5613 r.GetLoadTimingInfo(&load_timing_info);
5614 // The test server does not support keep alive sockets, so the second
5615 // request with auth should use a new socket.
5616 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5617 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5618 load_timing_info.socket_log_id);
5619 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5620 load_timing_info.connect_timing.connect_start);
5623 // Repeat request with end-to-end validation. Since auth-basic results in a
5624 // cachable page, we expect this test to result in a 304. In which case, the
5625 // response should be fetched from the cache.
5627 TestDelegate d;
5628 d.set_credentials(AuthCredentials(kUser, kSecret));
5630 URLRequest r(test_server_.GetURL("auth-basic"),
5631 DEFAULT_PRIORITY,
5633 &default_context_);
5634 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5635 r.Start();
5637 base::RunLoop().Run();
5639 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5641 // Should be the same cached document.
5642 EXPECT_TRUE(r.was_cached());
5644 // Since there was a request that went over the wire, the load timing
5645 // information should include connection times.
5646 LoadTimingInfo load_timing_info;
5647 r.GetLoadTimingInfo(&load_timing_info);
5648 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5652 // In this test, we do a POST which the server will 302 redirect.
5653 // The subsequent transaction should use GET, and should not send the
5654 // Content-Type header.
5655 // http://code.google.com/p/chromium/issues/detail?id=843
5656 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5657 ASSERT_TRUE(test_server_.Start());
5659 const char kData[] = "hello world";
5661 TestDelegate d;
5662 URLRequest req(test_server_.GetURL("files/redirect-to-echoall"),
5663 DEFAULT_PRIORITY,
5665 &default_context_);
5666 req.set_method("POST");
5667 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
5669 // Set headers (some of which are specific to the POST).
5670 HttpRequestHeaders headers;
5671 headers.AddHeadersFromString(
5672 "Content-Type: multipart/form-data; "
5673 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5674 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5675 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5676 "Accept-Language: en-US,en\r\n"
5677 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5678 "Content-Length: 11\r\n"
5679 "Origin: http://localhost:1337/");
5680 req.SetExtraRequestHeaders(headers);
5681 req.Start();
5682 base::RunLoop().Run();
5684 std::string mime_type;
5685 req.GetMimeType(&mime_type);
5686 EXPECT_EQ("text/html", mime_type);
5688 const std::string& data = d.data_received();
5690 // Check that the post-specific headers were stripped:
5691 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
5692 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
5693 EXPECT_FALSE(ContainsString(data, "Origin:"));
5695 // These extra request headers should not have been stripped.
5696 EXPECT_TRUE(ContainsString(data, "Accept:"));
5697 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
5698 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
5701 // The following tests check that we handle mutating the request method for
5702 // HTTP redirects as expected.
5703 // See http://crbug.com/56373 and http://crbug.com/102130.
5705 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
5706 ASSERT_TRUE(test_server_.Start());
5708 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
5710 HTTPRedirectMethodTest(url, "POST", "GET", true);
5711 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5712 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5715 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
5716 ASSERT_TRUE(test_server_.Start());
5718 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
5720 HTTPRedirectMethodTest(url, "POST", "GET", true);
5721 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5722 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5725 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
5726 ASSERT_TRUE(test_server_.Start());
5728 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
5730 HTTPRedirectMethodTest(url, "POST", "GET", true);
5731 HTTPRedirectMethodTest(url, "PUT", "GET", true);
5732 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5735 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
5736 ASSERT_TRUE(test_server_.Start());
5738 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
5740 HTTPRedirectMethodTest(url, "POST", "POST", true);
5741 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5742 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5745 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
5746 ASSERT_TRUE(test_server_.Start());
5748 const char kData[] = "hello world";
5750 TestDelegate d;
5751 URLRequest req(test_server_.GetURL("empty.html"),
5752 DEFAULT_PRIORITY,
5754 &default_context_);
5755 req.set_method("POST");
5756 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
5757 HttpRequestHeaders headers;
5758 headers.SetHeader(HttpRequestHeaders::kContentLength,
5759 base::UintToString(arraysize(kData) - 1));
5760 req.SetExtraRequestHeaders(headers);
5762 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5763 &req, &default_network_delegate_, test_server_.GetURL("echo"),
5764 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5765 AddTestInterceptor()->set_main_intercept_job(job);
5767 req.Start();
5768 base::RunLoop().Run();
5769 EXPECT_EQ("GET", req.method());
5772 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
5773 ASSERT_TRUE(test_server_.Start());
5775 const char kData[] = "hello world";
5777 TestDelegate d;
5778 URLRequest req(test_server_.GetURL("empty.html"),
5779 DEFAULT_PRIORITY,
5781 &default_context_);
5782 req.set_method("POST");
5783 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
5784 HttpRequestHeaders headers;
5785 headers.SetHeader(HttpRequestHeaders::kContentLength,
5786 base::UintToString(arraysize(kData) - 1));
5787 req.SetExtraRequestHeaders(headers);
5789 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5790 &req, &default_network_delegate_, test_server_.GetURL("echo"),
5791 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
5792 "Very Good Reason");
5793 AddTestInterceptor()->set_main_intercept_job(job);
5795 req.Start();
5796 base::RunLoop().Run();
5797 EXPECT_EQ("POST", req.method());
5798 EXPECT_EQ(kData, d.data_received());
5801 // Check that default A-L header is sent.
5802 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
5803 ASSERT_TRUE(test_server_.Start());
5805 StaticHttpUserAgentSettings settings("en", std::string());
5806 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
5807 TestURLRequestContext context(true);
5808 context.set_network_delegate(&network_delegate);
5809 context.set_http_user_agent_settings(&settings);
5810 context.Init();
5812 TestDelegate d;
5813 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
5814 DEFAULT_PRIORITY,
5816 &context);
5817 req.Start();
5818 base::RunLoop().Run();
5819 EXPECT_EQ("en", d.data_received());
5822 // Check that an empty A-L header is not sent. http://crbug.com/77365.
5823 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
5824 ASSERT_TRUE(test_server_.Start());
5826 std::string empty_string; // Avoid most vexing parse on line below.
5827 StaticHttpUserAgentSettings settings(empty_string, empty_string);
5828 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
5829 TestURLRequestContext context(true);
5830 context.set_network_delegate(&network_delegate);
5831 context.Init();
5832 // We override the language after initialization because empty entries
5833 // get overridden by Init().
5834 context.set_http_user_agent_settings(&settings);
5836 TestDelegate d;
5837 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
5838 DEFAULT_PRIORITY,
5840 &context);
5841 req.Start();
5842 base::RunLoop().Run();
5843 EXPECT_EQ("None", d.data_received());
5846 // Check that if request overrides the A-L header, the default is not appended.
5847 // See http://crbug.com/20894
5848 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
5849 ASSERT_TRUE(test_server_.Start());
5851 TestDelegate d;
5852 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
5853 DEFAULT_PRIORITY,
5855 &default_context_);
5856 HttpRequestHeaders headers;
5857 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
5858 req.SetExtraRequestHeaders(headers);
5859 req.Start();
5860 base::RunLoop().Run();
5861 EXPECT_EQ(std::string("ru"), d.data_received());
5864 // Check that default A-E header is sent.
5865 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
5866 ASSERT_TRUE(test_server_.Start());
5868 TestDelegate d;
5869 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
5870 DEFAULT_PRIORITY,
5872 &default_context_);
5873 HttpRequestHeaders headers;
5874 req.SetExtraRequestHeaders(headers);
5875 req.Start();
5876 base::RunLoop().Run();
5877 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
5880 // Check that if request overrides the A-E header, the default is not appended.
5881 // See http://crbug.com/47381
5882 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
5883 ASSERT_TRUE(test_server_.Start());
5885 TestDelegate d;
5886 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
5887 DEFAULT_PRIORITY,
5889 &default_context_);
5890 HttpRequestHeaders headers;
5891 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
5892 req.SetExtraRequestHeaders(headers);
5893 req.Start();
5894 base::RunLoop().Run();
5895 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
5896 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
5899 // Check that setting the A-C header sends the proper header.
5900 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
5901 ASSERT_TRUE(test_server_.Start());
5903 TestDelegate d;
5904 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
5905 DEFAULT_PRIORITY,
5907 &default_context_);
5908 HttpRequestHeaders headers;
5909 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
5910 req.SetExtraRequestHeaders(headers);
5911 req.Start();
5912 base::RunLoop().Run();
5913 EXPECT_EQ(std::string("koi-8r"), d.data_received());
5916 // Check that default User-Agent header is sent.
5917 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
5918 ASSERT_TRUE(test_server_.Start());
5920 TestDelegate d;
5921 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
5922 DEFAULT_PRIORITY,
5924 &default_context_);
5925 req.Start();
5926 base::RunLoop().Run();
5927 EXPECT_EQ(req.context()->http_user_agent_settings()->GetUserAgent(),
5928 d.data_received());
5931 // Check that if request overrides the User-Agent header,
5932 // the default is not appended.
5933 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
5934 ASSERT_TRUE(test_server_.Start());
5936 TestDelegate d;
5937 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
5938 DEFAULT_PRIORITY,
5940 &default_context_);
5941 HttpRequestHeaders headers;
5942 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
5943 req.SetExtraRequestHeaders(headers);
5944 req.Start();
5945 base::RunLoop().Run();
5946 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
5949 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
5950 // User-Agent header to be sent but does not send the Accept-Language and
5951 // Accept-Charset headers.
5952 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
5953 ASSERT_TRUE(test_server_.Start());
5955 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
5956 TestURLRequestContext context(true);
5957 context.set_network_delegate(&network_delegate);
5958 context.Init();
5959 // We override the HttpUserAgentSettings after initialization because empty
5960 // entries get overridden by Init().
5961 context.set_http_user_agent_settings(NULL);
5963 struct {
5964 const char* request;
5965 const char* expected_response;
5966 } tests[] = { { "echoheader?Accept-Language", "None" },
5967 { "echoheader?Accept-Charset", "None" },
5968 { "echoheader?User-Agent", "" } };
5970 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
5971 TestDelegate d;
5972 URLRequest req(
5973 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, &context);
5974 req.Start();
5975 base::RunLoop().Run();
5976 EXPECT_EQ(tests[i].expected_response, d.data_received())
5977 << " Request = \"" << tests[i].request << "\"";
5981 // Make sure that URLRequest passes on its priority updates to
5982 // newly-created jobs after the first one.
5983 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
5984 ASSERT_TRUE(test_server_.Start());
5986 TestDelegate d;
5987 URLRequest req(test_server_.GetURL("empty.html"),
5988 DEFAULT_PRIORITY,
5990 &default_context_);
5991 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
5993 scoped_refptr<URLRequestRedirectJob> redirect_job =
5994 new URLRequestRedirectJob(
5995 &req, &default_network_delegate_, test_server_.GetURL("echo"),
5996 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5997 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
5999 req.SetPriority(LOW);
6000 req.Start();
6001 EXPECT_TRUE(req.is_pending());
6003 scoped_refptr<URLRequestTestJob> job =
6004 new URLRequestTestJob(&req, &default_network_delegate_);
6005 AddTestInterceptor()->set_main_intercept_job(job.get());
6007 // Should trigger |job| to be started.
6008 base::RunLoop().Run();
6009 EXPECT_EQ(LOW, job->priority());
6012 // Check that creating a network request while entering/exiting suspend mode
6013 // fails as it should. This is the only case where an HttpTransactionFactory
6014 // does not return an HttpTransaction.
6015 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6016 // Create a new HttpNetworkLayer that thinks it's suspended.
6017 HttpNetworkSession::Params params;
6018 params.host_resolver = default_context_.host_resolver();
6019 params.cert_verifier = default_context_.cert_verifier();
6020 params.transport_security_state = default_context_.transport_security_state();
6021 params.proxy_service = default_context_.proxy_service();
6022 params.ssl_config_service = default_context_.ssl_config_service();
6023 params.http_auth_handler_factory =
6024 default_context_.http_auth_handler_factory();
6025 params.network_delegate = &default_network_delegate_;
6026 params.http_server_properties = default_context_.http_server_properties();
6027 scoped_ptr<HttpNetworkLayer> network_layer(
6028 new HttpNetworkLayer(new HttpNetworkSession(params)));
6029 network_layer->OnSuspend();
6031 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6032 HttpCache::DefaultBackend::InMemory(0));
6034 TestURLRequestContext context(true);
6035 context.set_http_transaction_factory(&http_cache);
6036 context.Init();
6038 TestDelegate d;
6039 URLRequest req(GURL("http://127.0.0.1/"),
6040 DEFAULT_PRIORITY,
6042 &context);
6043 req.Start();
6044 base::RunLoop().Run();
6046 EXPECT_TRUE(d.request_failed());
6047 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6048 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6051 // Check that creating a network request while entering/exiting suspend mode
6052 // fails as it should in the case there is no cache. This is the only case
6053 // where an HttpTransactionFactory does not return an HttpTransaction.
6054 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6055 // Create a new HttpNetworkLayer that thinks it's suspended.
6056 HttpNetworkSession::Params params;
6057 params.host_resolver = default_context_.host_resolver();
6058 params.cert_verifier = default_context_.cert_verifier();
6059 params.transport_security_state = default_context_.transport_security_state();
6060 params.proxy_service = default_context_.proxy_service();
6061 params.ssl_config_service = default_context_.ssl_config_service();
6062 params.http_auth_handler_factory =
6063 default_context_.http_auth_handler_factory();
6064 params.network_delegate = &default_network_delegate_;
6065 params.http_server_properties = default_context_.http_server_properties();
6066 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6067 network_layer.OnSuspend();
6069 TestURLRequestContext context(true);
6070 context.set_http_transaction_factory(&network_layer);
6071 context.Init();
6073 TestDelegate d;
6074 URLRequest req(GURL("http://127.0.0.1/"),
6075 DEFAULT_PRIORITY,
6077 &context);
6078 req.Start();
6079 base::RunLoop().Run();
6081 EXPECT_TRUE(d.request_failed());
6082 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6083 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6086 class HTTPSRequestTest : public testing::Test {
6087 public:
6088 HTTPSRequestTest() : default_context_(true) {
6089 default_context_.set_network_delegate(&default_network_delegate_);
6090 default_context_.Init();
6092 virtual ~HTTPSRequestTest() {}
6094 protected:
6095 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
6096 TestURLRequestContext default_context_;
6099 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
6100 SpawnedTestServer test_server(
6101 SpawnedTestServer::TYPE_HTTPS,
6102 SpawnedTestServer::kLocalhost,
6103 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6104 ASSERT_TRUE(test_server.Start());
6106 TestDelegate d;
6108 URLRequest r(test_server.GetURL(std::string()),
6109 DEFAULT_PRIORITY,
6111 &default_context_);
6112 r.Start();
6113 EXPECT_TRUE(r.is_pending());
6115 base::RunLoop().Run();
6117 EXPECT_EQ(1, d.response_started_count());
6118 EXPECT_FALSE(d.received_data_before_response());
6119 EXPECT_NE(0, d.bytes_received());
6120 CheckSSLInfo(r.ssl_info());
6121 EXPECT_EQ(test_server.host_port_pair().host(),
6122 r.GetSocketAddress().host());
6123 EXPECT_EQ(test_server.host_port_pair().port(),
6124 r.GetSocketAddress().port());
6128 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
6129 SpawnedTestServer::SSLOptions ssl_options(
6130 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6131 SpawnedTestServer test_server(
6132 SpawnedTestServer::TYPE_HTTPS,
6133 ssl_options,
6134 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6135 ASSERT_TRUE(test_server.Start());
6137 bool err_allowed = true;
6138 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6139 TestDelegate d;
6141 d.set_allow_certificate_errors(err_allowed);
6142 URLRequest r(test_server.GetURL(std::string()),
6143 DEFAULT_PRIORITY,
6145 &default_context_);
6147 r.Start();
6148 EXPECT_TRUE(r.is_pending());
6150 base::RunLoop().Run();
6152 EXPECT_EQ(1, d.response_started_count());
6153 EXPECT_FALSE(d.received_data_before_response());
6154 EXPECT_TRUE(d.have_certificate_errors());
6155 if (err_allowed) {
6156 EXPECT_NE(0, d.bytes_received());
6157 CheckSSLInfo(r.ssl_info());
6158 } else {
6159 EXPECT_EQ(0, d.bytes_received());
6165 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
6166 SpawnedTestServer::SSLOptions ssl_options(
6167 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6168 SpawnedTestServer test_server(
6169 SpawnedTestServer::TYPE_HTTPS,
6170 ssl_options,
6171 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6172 ASSERT_TRUE(test_server.Start());
6174 // Iterate from false to true, just so that we do the opposite of the
6175 // previous test in order to increase test coverage.
6176 bool err_allowed = false;
6177 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6178 TestDelegate d;
6180 d.set_allow_certificate_errors(err_allowed);
6181 URLRequest r(test_server.GetURL(std::string()),
6182 DEFAULT_PRIORITY,
6184 &default_context_);
6186 r.Start();
6187 EXPECT_TRUE(r.is_pending());
6189 base::RunLoop().Run();
6191 EXPECT_EQ(1, d.response_started_count());
6192 EXPECT_FALSE(d.received_data_before_response());
6193 EXPECT_TRUE(d.have_certificate_errors());
6194 if (err_allowed) {
6195 EXPECT_NE(0, d.bytes_received());
6196 CheckSSLInfo(r.ssl_info());
6197 } else {
6198 EXPECT_EQ(0, d.bytes_received());
6204 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
6205 // than necessary.
6206 TEST_F(HTTPSRequestTest, TLSv1Fallback) {
6207 uint16 default_version_max = SSLConfigService::default_version_max();
6208 // The OpenSSL library in use may not support TLS 1.1.
6209 #if !defined(USE_OPENSSL)
6210 EXPECT_GT(default_version_max, SSL_PROTOCOL_VERSION_TLS1);
6211 #endif
6212 if (default_version_max <= SSL_PROTOCOL_VERSION_TLS1)
6213 return;
6215 SpawnedTestServer::SSLOptions ssl_options(
6216 SpawnedTestServer::SSLOptions::CERT_OK);
6217 ssl_options.tls_intolerant =
6218 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
6219 SpawnedTestServer test_server(
6220 SpawnedTestServer::TYPE_HTTPS,
6221 ssl_options,
6222 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6223 ASSERT_TRUE(test_server.Start());
6225 TestDelegate d;
6226 TestURLRequestContext context(true);
6227 context.Init();
6228 d.set_allow_certificate_errors(true);
6229 URLRequest r(
6230 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6231 r.Start();
6233 base::RunLoop().Run();
6235 EXPECT_EQ(1, d.response_started_count());
6236 EXPECT_NE(0, d.bytes_received());
6237 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
6238 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6239 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6242 // Tests that we don't fallback with servers that implement TLS_FALLBACK_SCSV.
6243 #if defined(USE_OPENSSL)
6244 TEST_F(HTTPSRequestTest, DISABLED_FallbackSCSV) {
6245 #else
6246 TEST_F(HTTPSRequestTest, FallbackSCSV) {
6247 #endif
6248 SpawnedTestServer::SSLOptions ssl_options(
6249 SpawnedTestServer::SSLOptions::CERT_OK);
6250 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
6251 // a version fallback.
6252 ssl_options.tls_intolerant =
6253 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6254 // Have the server process TLS_FALLBACK_SCSV so that version fallback
6255 // connections are rejected.
6256 ssl_options.fallback_scsv_enabled = true;
6258 SpawnedTestServer test_server(
6259 SpawnedTestServer::TYPE_HTTPS,
6260 ssl_options,
6261 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6262 ASSERT_TRUE(test_server.Start());
6264 TestDelegate d;
6265 TestURLRequestContext context(true);
6266 context.Init();
6267 d.set_allow_certificate_errors(true);
6268 URLRequest r(
6269 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6270 r.Start();
6272 base::RunLoop().Run();
6274 EXPECT_EQ(1, d.response_started_count());
6275 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
6276 // intolerance. If the fallback SCSV is processed when the original error
6277 // that caused the fallback should be returned, which should be
6278 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
6279 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, r.status().error());
6282 // This tests that a load of www.google.com with a certificate error sets
6283 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
6284 // the interstitial to be fatal.
6285 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
6286 SpawnedTestServer::SSLOptions ssl_options(
6287 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6288 SpawnedTestServer test_server(
6289 SpawnedTestServer::TYPE_HTTPS,
6290 ssl_options,
6291 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6292 ASSERT_TRUE(test_server.Start());
6294 // We require that the URL be www.google.com in order to pick up the
6295 // preloaded HSTS entries in the TransportSecurityState. This means that we
6296 // have to use a MockHostResolver in order to direct www.google.com to the
6297 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6299 MockHostResolver host_resolver;
6300 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6301 TestURLRequestContext context(true);
6302 context.set_network_delegate(&network_delegate);
6303 context.set_host_resolver(&host_resolver);
6304 TransportSecurityState transport_security_state;
6305 context.set_transport_security_state(&transport_security_state);
6306 context.Init();
6308 TestDelegate d;
6309 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6310 test_server.host_port_pair().port())),
6311 DEFAULT_PRIORITY,
6313 &context);
6315 r.Start();
6316 EXPECT_TRUE(r.is_pending());
6318 base::RunLoop().Run();
6320 EXPECT_EQ(1, d.response_started_count());
6321 EXPECT_FALSE(d.received_data_before_response());
6322 EXPECT_TRUE(d.have_certificate_errors());
6323 EXPECT_TRUE(d.certificate_errors_are_fatal());
6326 // This tests that cached HTTPS page loads do not cause any updates to the
6327 // TransportSecurityState.
6328 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6329 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6330 // matter. It just has to be any error.
6331 SpawnedTestServer::SSLOptions ssl_options(
6332 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6333 SpawnedTestServer test_server(
6334 SpawnedTestServer::TYPE_HTTPS,
6335 ssl_options,
6336 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6337 ASSERT_TRUE(test_server.Start());
6339 // We require that the URL be www.google.com in order to pick up the
6340 // preloaded and dynamic HSTS and public key pin entries in the
6341 // TransportSecurityState. This means that we have to use a
6342 // MockHostResolver in order to direct www.google.com to the testserver.
6343 // By default, MockHostResolver maps all hosts to 127.0.0.1.
6345 MockHostResolver host_resolver;
6346 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6347 TestURLRequestContext context(true);
6348 context.set_network_delegate(&network_delegate);
6349 context.set_host_resolver(&host_resolver);
6350 TransportSecurityState transport_security_state;
6351 TransportSecurityState::DomainState domain_state;
6352 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
6353 &domain_state));
6354 context.set_transport_security_state(&transport_security_state);
6355 context.Init();
6357 TestDelegate d;
6358 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6359 test_server.host_port_pair().port())),
6360 DEFAULT_PRIORITY,
6362 &context);
6364 r.Start();
6365 EXPECT_TRUE(r.is_pending());
6367 base::RunLoop().Run();
6369 EXPECT_EQ(1, d.response_started_count());
6370 EXPECT_FALSE(d.received_data_before_response());
6371 EXPECT_TRUE(d.have_certificate_errors());
6372 EXPECT_TRUE(d.certificate_errors_are_fatal());
6374 // Get a fresh copy of the state, and check that it hasn't been updated.
6375 TransportSecurityState::DomainState new_domain_state;
6376 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
6377 &new_domain_state));
6378 EXPECT_EQ(new_domain_state.upgrade_mode, domain_state.upgrade_mode);
6379 EXPECT_EQ(new_domain_state.sts_include_subdomains,
6380 domain_state.sts_include_subdomains);
6381 EXPECT_EQ(new_domain_state.pkp_include_subdomains,
6382 domain_state.pkp_include_subdomains);
6383 EXPECT_TRUE(FingerprintsEqual(new_domain_state.static_spki_hashes,
6384 domain_state.static_spki_hashes));
6385 EXPECT_TRUE(FingerprintsEqual(new_domain_state.dynamic_spki_hashes,
6386 domain_state.dynamic_spki_hashes));
6387 EXPECT_TRUE(FingerprintsEqual(new_domain_state.bad_static_spki_hashes,
6388 domain_state.bad_static_spki_hashes));
6391 // Make sure HSTS preserves a POST request's method and body.
6392 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6393 static const char kData[] = "hello world";
6395 SpawnedTestServer::SSLOptions ssl_options(
6396 SpawnedTestServer::SSLOptions::CERT_OK);
6397 SpawnedTestServer test_server(
6398 SpawnedTestServer::TYPE_HTTPS,
6399 ssl_options,
6400 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6401 ASSERT_TRUE(test_server.Start());
6404 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6405 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
6406 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6407 // to 127.0.0.1.
6408 MockHostResolver host_resolver;
6410 // Force https for www.somewhere.com.
6411 TransportSecurityState transport_security_state;
6412 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6413 bool include_subdomains = false;
6414 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6415 include_subdomains);
6417 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6419 TestURLRequestContext context(true);
6420 context.set_host_resolver(&host_resolver);
6421 context.set_transport_security_state(&transport_security_state);
6422 context.set_network_delegate(&network_delegate);
6423 context.Init();
6425 TestDelegate d;
6426 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6427 // cause a certificate error. Ignore the error.
6428 d.set_allow_certificate_errors(true);
6430 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6431 test_server.host_port_pair().port())),
6432 DEFAULT_PRIORITY,
6434 &context);
6435 req.set_method("POST");
6436 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6438 req.Start();
6439 base::RunLoop().Run();
6441 EXPECT_EQ("https", req.url().scheme());
6442 EXPECT_EQ("POST", req.method());
6443 EXPECT_EQ(kData, d.data_received());
6445 LoadTimingInfo load_timing_info;
6446 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6447 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6448 TestLoadTimingCacheHitNoNetwork(load_timing_info);
6451 TEST_F(HTTPSRequestTest, SSLv3Fallback) {
6452 SpawnedTestServer::SSLOptions ssl_options(
6453 SpawnedTestServer::SSLOptions::CERT_OK);
6454 ssl_options.tls_intolerant =
6455 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6456 SpawnedTestServer test_server(
6457 SpawnedTestServer::TYPE_HTTPS,
6458 ssl_options,
6459 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6460 ASSERT_TRUE(test_server.Start());
6462 TestDelegate d;
6463 TestURLRequestContext context(true);
6464 context.Init();
6465 d.set_allow_certificate_errors(true);
6466 URLRequest r(
6467 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6468 r.Start();
6470 base::RunLoop().Run();
6472 EXPECT_EQ(1, d.response_started_count());
6473 EXPECT_NE(0, d.bytes_received());
6474 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
6475 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6476 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6479 namespace {
6481 class SSLClientAuthTestDelegate : public TestDelegate {
6482 public:
6483 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6485 virtual void OnCertificateRequested(
6486 URLRequest* request,
6487 SSLCertRequestInfo* cert_request_info) OVERRIDE {
6488 on_certificate_requested_count_++;
6489 base::MessageLoop::current()->Quit();
6491 int on_certificate_requested_count() {
6492 return on_certificate_requested_count_;
6494 private:
6495 int on_certificate_requested_count_;
6498 } // namespace
6500 // TODO(davidben): Test the rest of the code. Specifically,
6501 // - Filtering which certificates to select.
6502 // - Sending a certificate back.
6503 // - Getting a certificate request in an SSL renegotiation sending the
6504 // HTTP request.
6505 TEST_F(HTTPSRequestTest, ClientAuthTest) {
6506 SpawnedTestServer::SSLOptions ssl_options;
6507 ssl_options.request_client_certificate = true;
6508 SpawnedTestServer test_server(
6509 SpawnedTestServer::TYPE_HTTPS,
6510 ssl_options,
6511 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6512 ASSERT_TRUE(test_server.Start());
6514 SSLClientAuthTestDelegate d;
6516 URLRequest r(test_server.GetURL(std::string()),
6517 DEFAULT_PRIORITY,
6519 &default_context_);
6521 r.Start();
6522 EXPECT_TRUE(r.is_pending());
6524 base::RunLoop().Run();
6526 EXPECT_EQ(1, d.on_certificate_requested_count());
6527 EXPECT_FALSE(d.received_data_before_response());
6528 EXPECT_EQ(0, d.bytes_received());
6530 // Send no certificate.
6531 // TODO(davidben): Get temporary client cert import (with keys) working on
6532 // all platforms so we can test sending a cert as well.
6533 r.ContinueWithCertificate(NULL);
6535 base::RunLoop().Run();
6537 EXPECT_EQ(1, d.response_started_count());
6538 EXPECT_FALSE(d.received_data_before_response());
6539 EXPECT_NE(0, d.bytes_received());
6543 TEST_F(HTTPSRequestTest, ResumeTest) {
6544 // Test that we attempt a session resume when making two connections to the
6545 // same host.
6546 SpawnedTestServer::SSLOptions ssl_options;
6547 ssl_options.record_resume = true;
6548 SpawnedTestServer test_server(
6549 SpawnedTestServer::TYPE_HTTPS,
6550 ssl_options,
6551 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6552 ASSERT_TRUE(test_server.Start());
6554 SSLClientSocket::ClearSessionCache();
6557 TestDelegate d;
6558 URLRequest r(test_server.GetURL("ssl-session-cache"),
6559 DEFAULT_PRIORITY,
6561 &default_context_);
6563 r.Start();
6564 EXPECT_TRUE(r.is_pending());
6566 base::RunLoop().Run();
6568 EXPECT_EQ(1, d.response_started_count());
6571 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6572 CloseAllConnections();
6575 TestDelegate d;
6576 URLRequest r(test_server.GetURL("ssl-session-cache"),
6577 DEFAULT_PRIORITY,
6579 &default_context_);
6581 r.Start();
6582 EXPECT_TRUE(r.is_pending());
6584 base::RunLoop().Run();
6586 // The response will look like;
6587 // insert abc
6588 // lookup abc
6589 // insert xyz
6591 // With a newline at the end which makes the split think that there are
6592 // four lines.
6594 EXPECT_EQ(1, d.response_started_count());
6595 std::vector<std::string> lines;
6596 base::SplitString(d.data_received(), '\n', &lines);
6597 ASSERT_EQ(4u, lines.size()) << d.data_received();
6599 std::string session_id;
6601 for (size_t i = 0; i < 2; i++) {
6602 std::vector<std::string> parts;
6603 base::SplitString(lines[i], '\t', &parts);
6604 ASSERT_EQ(2u, parts.size());
6605 if (i == 0) {
6606 EXPECT_EQ("insert", parts[0]);
6607 session_id = parts[1];
6608 } else {
6609 EXPECT_EQ("lookup", parts[0]);
6610 EXPECT_EQ(session_id, parts[1]);
6616 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6617 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6618 // differs.
6619 SpawnedTestServer::SSLOptions ssl_options;
6620 ssl_options.record_resume = true;
6621 SpawnedTestServer test_server(
6622 SpawnedTestServer::TYPE_HTTPS,
6623 ssl_options,
6624 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6625 ASSERT_TRUE(test_server.Start());
6627 SSLClientSocket::ClearSessionCache();
6630 TestDelegate d;
6631 URLRequest r(test_server.GetURL("ssl-session-cache"),
6632 DEFAULT_PRIORITY,
6634 &default_context_);
6636 r.Start();
6637 EXPECT_TRUE(r.is_pending());
6639 base::RunLoop().Run();
6641 EXPECT_EQ(1, d.response_started_count());
6644 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6645 HttpNetworkSession::Params params;
6646 params.host_resolver = default_context_.host_resolver();
6647 params.cert_verifier = default_context_.cert_verifier();
6648 params.transport_security_state = default_context_.transport_security_state();
6649 params.proxy_service = default_context_.proxy_service();
6650 params.ssl_config_service = default_context_.ssl_config_service();
6651 params.http_auth_handler_factory =
6652 default_context_.http_auth_handler_factory();
6653 params.network_delegate = &default_network_delegate_;
6654 params.http_server_properties = default_context_.http_server_properties();
6655 params.ssl_session_cache_shard = "alternate";
6657 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
6658 new net::HttpNetworkSession(params),
6659 net::HttpCache::DefaultBackend::InMemory(0)));
6661 default_context_.set_http_transaction_factory(cache.get());
6664 TestDelegate d;
6665 URLRequest r(test_server.GetURL("ssl-session-cache"),
6666 DEFAULT_PRIORITY,
6668 &default_context_);
6670 r.Start();
6671 EXPECT_TRUE(r.is_pending());
6673 base::RunLoop().Run();
6675 // The response will look like;
6676 // insert abc
6677 // insert xyz
6679 // With a newline at the end which makes the split think that there are
6680 // three lines.
6682 EXPECT_EQ(1, d.response_started_count());
6683 std::vector<std::string> lines;
6684 base::SplitString(d.data_received(), '\n', &lines);
6685 ASSERT_EQ(3u, lines.size());
6687 std::string session_id;
6688 for (size_t i = 0; i < 2; i++) {
6689 std::vector<std::string> parts;
6690 base::SplitString(lines[i], '\t', &parts);
6691 ASSERT_EQ(2u, parts.size());
6692 EXPECT_EQ("insert", parts[0]);
6693 if (i == 0) {
6694 session_id = parts[1];
6695 } else {
6696 EXPECT_NE(session_id, parts[1]);
6702 class HTTPSSessionTest : public testing::Test {
6703 public:
6704 HTTPSSessionTest() : default_context_(true) {
6705 cert_verifier_.set_default_result(net::OK);
6707 default_context_.set_network_delegate(&default_network_delegate_);
6708 default_context_.set_cert_verifier(&cert_verifier_);
6709 default_context_.Init();
6711 virtual ~HTTPSSessionTest() {}
6713 protected:
6714 MockCertVerifier cert_verifier_;
6715 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
6716 TestURLRequestContext default_context_;
6719 // Tests that session resumption is not attempted if an invalid certificate
6720 // is presented.
6721 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
6722 SpawnedTestServer::SSLOptions ssl_options;
6723 ssl_options.record_resume = true;
6724 SpawnedTestServer test_server(
6725 SpawnedTestServer::TYPE_HTTPS,
6726 ssl_options,
6727 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6728 ASSERT_TRUE(test_server.Start());
6730 SSLClientSocket::ClearSessionCache();
6732 // Simulate the certificate being expired and attempt a connection.
6733 cert_verifier_.set_default_result(net::ERR_CERT_DATE_INVALID);
6735 TestDelegate d;
6736 URLRequest r(test_server.GetURL("ssl-session-cache"),
6737 DEFAULT_PRIORITY,
6739 &default_context_);
6741 r.Start();
6742 EXPECT_TRUE(r.is_pending());
6744 base::RunLoop().Run();
6746 EXPECT_EQ(1, d.response_started_count());
6749 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6750 CloseAllConnections();
6752 // Now change the certificate to be acceptable (so that the response is
6753 // loaded), and ensure that no session id is presented to the peer.
6754 cert_verifier_.set_default_result(net::OK);
6756 TestDelegate d;
6757 URLRequest r(test_server.GetURL("ssl-session-cache"),
6758 DEFAULT_PRIORITY,
6760 &default_context_);
6762 r.Start();
6763 EXPECT_TRUE(r.is_pending());
6765 base::RunLoop().Run();
6767 // The response will look like;
6768 // insert abc
6769 // insert xyz
6771 // With a newline at the end which makes the split think that there are
6772 // three lines.
6774 // If a session was presented (eg: a bug), then the response would look
6775 // like;
6776 // insert abc
6777 // lookup abc
6778 // insert xyz
6780 EXPECT_EQ(1, d.response_started_count());
6781 std::vector<std::string> lines;
6782 base::SplitString(d.data_received(), '\n', &lines);
6783 ASSERT_EQ(3u, lines.size()) << d.data_received();
6785 std::string session_id;
6786 for (size_t i = 0; i < 2; i++) {
6787 std::vector<std::string> parts;
6788 base::SplitString(lines[i], '\t', &parts);
6789 ASSERT_EQ(2u, parts.size());
6790 EXPECT_EQ("insert", parts[0]);
6791 if (i == 0) {
6792 session_id = parts[1];
6793 } else {
6794 EXPECT_NE(session_id, parts[1]);
6800 class TestSSLConfigService : public SSLConfigService {
6801 public:
6802 TestSSLConfigService(bool ev_enabled,
6803 bool online_rev_checking,
6804 bool rev_checking_required_local_anchors)
6805 : ev_enabled_(ev_enabled),
6806 online_rev_checking_(online_rev_checking),
6807 rev_checking_required_local_anchors_(
6808 rev_checking_required_local_anchors) {}
6810 // SSLConfigService:
6811 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
6812 *config = SSLConfig();
6813 config->rev_checking_enabled = online_rev_checking_;
6814 config->verify_ev_cert = ev_enabled_;
6815 config->rev_checking_required_local_anchors =
6816 rev_checking_required_local_anchors_;
6819 protected:
6820 virtual ~TestSSLConfigService() {}
6822 private:
6823 const bool ev_enabled_;
6824 const bool online_rev_checking_;
6825 const bool rev_checking_required_local_anchors_;
6828 // This the fingerprint of the "Testing CA" certificate used by the testserver.
6829 // See net/data/ssl/certificates/ocsp-test-root.pem.
6830 static const SHA1HashValue kOCSPTestCertFingerprint =
6831 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
6832 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
6834 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
6835 // testserver.
6836 static const SHA256HashValue kOCSPTestCertSPKI = { {
6837 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
6838 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
6839 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
6840 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
6841 } };
6843 // This is the policy OID contained in the certificates that testserver
6844 // generates.
6845 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
6847 class HTTPSOCSPTest : public HTTPSRequestTest {
6848 public:
6849 HTTPSOCSPTest()
6850 : context_(true),
6851 ev_test_policy_(
6852 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
6853 kOCSPTestCertFingerprint,
6854 kOCSPTestCertPolicy)) {
6857 virtual void SetUp() OVERRIDE {
6858 SetupContext(&context_);
6859 context_.Init();
6861 scoped_refptr<net::X509Certificate> root_cert =
6862 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
6863 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
6864 test_root_.reset(new ScopedTestRoot(root_cert.get()));
6866 #if defined(USE_NSS) || defined(OS_IOS)
6867 SetURLRequestContextForNSSHttpIO(&context_);
6868 EnsureNSSHttpIOInit();
6869 #endif
6872 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
6873 CertStatus* out_cert_status) {
6874 // We always overwrite out_cert_status.
6875 *out_cert_status = 0;
6876 SpawnedTestServer test_server(
6877 SpawnedTestServer::TYPE_HTTPS,
6878 ssl_options,
6879 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6880 ASSERT_TRUE(test_server.Start());
6882 TestDelegate d;
6883 d.set_allow_certificate_errors(true);
6884 URLRequest r(
6885 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context_);
6886 r.Start();
6888 base::RunLoop().Run();
6890 EXPECT_EQ(1, d.response_started_count());
6891 *out_cert_status = r.ssl_info().cert_status;
6894 virtual ~HTTPSOCSPTest() {
6895 #if defined(USE_NSS) || defined(OS_IOS)
6896 ShutdownNSSHttpIO();
6897 #endif
6900 protected:
6901 // SetupContext configures the URLRequestContext that will be used for making
6902 // connetions to testserver. This can be overridden in test subclasses for
6903 // different behaviour.
6904 virtual void SetupContext(URLRequestContext* context) {
6905 context->set_ssl_config_service(
6906 new TestSSLConfigService(true /* check for EV */,
6907 true /* online revocation checking */,
6908 false /* require rev. checking for local
6909 anchors */));
6912 scoped_ptr<ScopedTestRoot> test_root_;
6913 TestURLRequestContext context_;
6914 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
6917 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
6918 #if defined(OS_WIN)
6919 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
6920 // have that ability on other platforms.
6921 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
6922 #else
6923 return 0;
6924 #endif
6927 // SystemSupportsHardFailRevocationChecking returns true iff the current
6928 // operating system supports revocation checking and can distinguish between
6929 // situations where a given certificate lacks any revocation information (eg:
6930 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
6931 // revocation information cannot be obtained (eg: the CRL was unreachable).
6932 // If it does not, then tests which rely on 'hard fail' behaviour should be
6933 // skipped.
6934 static bool SystemSupportsHardFailRevocationChecking() {
6935 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
6936 return true;
6937 #else
6938 return false;
6939 #endif
6942 // SystemUsesChromiumEVMetadata returns true iff the current operating system
6943 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
6944 // several tests are effected because our testing EV certificate won't be
6945 // recognised as EV.
6946 static bool SystemUsesChromiumEVMetadata() {
6947 #if defined(USE_OPENSSL)
6948 // http://crbug.com/117478 - OpenSSL does not support EV validation.
6949 return false;
6950 #elif defined(OS_MACOSX) && !defined(OS_IOS)
6951 // On OS X, we use the system to tell us whether a certificate is EV or not
6952 // and the system won't recognise our testing root.
6953 return false;
6954 #else
6955 return true;
6956 #endif
6959 static bool SystemSupportsOCSP() {
6960 #if defined(USE_OPENSSL)
6961 // http://crbug.com/117478 - OpenSSL does not support OCSP.
6962 return false;
6963 #elif defined(OS_WIN)
6964 return base::win::GetVersion() >= base::win::VERSION_VISTA;
6965 #elif defined(OS_ANDROID)
6966 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
6967 return false;
6968 #else
6969 return true;
6970 #endif
6973 TEST_F(HTTPSOCSPTest, Valid) {
6974 if (!SystemSupportsOCSP()) {
6975 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6976 return;
6979 SpawnedTestServer::SSLOptions ssl_options(
6980 SpawnedTestServer::SSLOptions::CERT_AUTO);
6981 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
6983 CertStatus cert_status;
6984 DoConnection(ssl_options, &cert_status);
6986 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6988 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6989 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
6991 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6994 TEST_F(HTTPSOCSPTest, Revoked) {
6995 if (!SystemSupportsOCSP()) {
6996 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6997 return;
7000 SpawnedTestServer::SSLOptions ssl_options(
7001 SpawnedTestServer::SSLOptions::CERT_AUTO);
7002 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7004 CertStatus cert_status;
7005 DoConnection(ssl_options, &cert_status);
7007 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
7008 // Doesn't pass on OS X yet for reasons that need to be investigated.
7009 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7010 #endif
7011 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7012 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7015 TEST_F(HTTPSOCSPTest, Invalid) {
7016 if (!SystemSupportsOCSP()) {
7017 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7018 return;
7021 SpawnedTestServer::SSLOptions ssl_options(
7022 SpawnedTestServer::SSLOptions::CERT_AUTO);
7023 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7025 CertStatus cert_status;
7026 DoConnection(ssl_options, &cert_status);
7028 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7029 cert_status & CERT_STATUS_ALL_ERRORS);
7031 // Without a positive OCSP response, we shouldn't show the EV status.
7032 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7033 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7036 class HTTPSHardFailTest : public HTTPSOCSPTest {
7037 protected:
7038 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7039 context->set_ssl_config_service(
7040 new TestSSLConfigService(false /* check for EV */,
7041 false /* online revocation checking */,
7042 true /* require rev. checking for local
7043 anchors */));
7048 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
7049 if (!SystemSupportsOCSP()) {
7050 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7051 return;
7054 if (!SystemSupportsHardFailRevocationChecking()) {
7055 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
7056 << "revocation checking";
7057 return;
7060 SpawnedTestServer::SSLOptions ssl_options(
7061 SpawnedTestServer::SSLOptions::CERT_AUTO);
7062 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7064 CertStatus cert_status;
7065 DoConnection(ssl_options, &cert_status);
7067 EXPECT_EQ(CERT_STATUS_REVOKED,
7068 cert_status & CERT_STATUS_REVOKED);
7070 // Without a positive OCSP response, we shouldn't show the EV status.
7071 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7074 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
7075 protected:
7076 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7077 context->set_ssl_config_service(
7078 new TestSSLConfigService(true /* check for EV */,
7079 false /* online revocation checking */,
7080 false /* require rev. checking for local
7081 anchors */));
7085 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
7086 if (!SystemSupportsOCSP()) {
7087 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7088 return;
7091 SpawnedTestServer::SSLOptions ssl_options(
7092 SpawnedTestServer::SSLOptions::CERT_AUTO);
7093 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7094 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7096 CertStatus cert_status;
7097 DoConnection(ssl_options, &cert_status);
7099 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7100 cert_status & CERT_STATUS_ALL_ERRORS);
7102 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7103 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7104 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7107 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
7108 if (!SystemSupportsOCSP()) {
7109 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7110 return;
7113 SpawnedTestServer::SSLOptions ssl_options(
7114 SpawnedTestServer::SSLOptions::CERT_AUTO);
7115 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7116 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7118 CertStatus cert_status;
7119 DoConnection(ssl_options, &cert_status);
7121 // Currently only works for Windows. When using NSS or OS X, it's not
7122 // possible to determine whether the check failed because of actual
7123 // revocation or because there was an OCSP failure.
7124 #if defined(OS_WIN)
7125 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7126 #else
7127 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7128 #endif
7130 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7131 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7132 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7135 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
7136 if (!SystemSupportsOCSP()) {
7137 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7138 return;
7141 SpawnedTestServer::SSLOptions ssl_options(
7142 SpawnedTestServer::SSLOptions::CERT_AUTO);
7143 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7144 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7146 CertStatus cert_status;
7147 DoConnection(ssl_options, &cert_status);
7149 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7151 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7152 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7153 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7154 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7157 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
7158 if (!SystemSupportsOCSP()) {
7159 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7160 return;
7163 SpawnedTestServer::SSLOptions ssl_options(
7164 SpawnedTestServer::SSLOptions::CERT_AUTO);
7165 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7166 SSLConfigService::SetCRLSet(
7167 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7169 CertStatus cert_status;
7170 DoConnection(ssl_options, &cert_status);
7172 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7173 cert_status & CERT_STATUS_ALL_ERRORS);
7175 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7176 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7177 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7180 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
7181 if (!SystemSupportsOCSP()) {
7182 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7183 return;
7186 SpawnedTestServer::SSLOptions ssl_options(
7187 SpawnedTestServer::SSLOptions::CERT_AUTO);
7188 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7189 SSLConfigService::SetCRLSet(
7190 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7191 false, &kOCSPTestCertSPKI, "")));
7193 CertStatus cert_status;
7194 DoConnection(ssl_options, &cert_status);
7196 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7197 // revocation check for EV.
7198 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7199 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7200 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7201 EXPECT_FALSE(
7202 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7205 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
7206 if (!SystemSupportsOCSP()) {
7207 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7208 return;
7211 SpawnedTestServer::SSLOptions ssl_options(
7212 SpawnedTestServer::SSLOptions::CERT_AUTO);
7213 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7214 SSLConfigService::SetCRLSet(
7215 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
7217 CertStatus cert_status = 0;
7218 DoConnection(ssl_options, &cert_status);
7220 // Even with a fresh CRLSet, we should still do online revocation checks when
7221 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7222 // test.
7223 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7224 cert_status & CERT_STATUS_ALL_ERRORS);
7226 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7227 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7228 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7231 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
7232 // Test that when EV verification is requested, but online revocation
7233 // checking is disabled, and the leaf certificate is not in fact EV, that
7234 // no revocation checking actually happens.
7235 if (!SystemSupportsOCSP()) {
7236 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7237 return;
7240 // Unmark the certificate's OID as EV, which should disable revocation
7241 // checking (as per the user preference)
7242 ev_test_policy_.reset();
7244 SpawnedTestServer::SSLOptions ssl_options(
7245 SpawnedTestServer::SSLOptions::CERT_AUTO);
7246 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7247 SSLConfigService::SetCRLSet(
7248 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7250 CertStatus cert_status;
7251 DoConnection(ssl_options, &cert_status);
7253 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7255 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7256 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7259 class HTTPSCRLSetTest : public HTTPSOCSPTest {
7260 protected:
7261 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7262 context->set_ssl_config_service(
7263 new TestSSLConfigService(false /* check for EV */,
7264 false /* online revocation checking */,
7265 false /* require rev. checking for local
7266 anchors */));
7270 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
7271 SpawnedTestServer::SSLOptions ssl_options(
7272 SpawnedTestServer::SSLOptions::CERT_AUTO);
7273 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7274 SSLConfigService::SetCRLSet(
7275 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7277 CertStatus cert_status;
7278 DoConnection(ssl_options, &cert_status);
7280 // If we're not trying EV verification then, even if the CRLSet has expired,
7281 // we don't fall back to online revocation checks.
7282 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7283 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7284 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7287 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
7288 #if defined(USE_OPENSSL)
7289 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
7290 return;
7291 #endif
7293 SpawnedTestServer::SSLOptions ssl_options(
7294 SpawnedTestServer::SSLOptions::CERT_AUTO);
7295 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7296 ssl_options.cert_serial = 10;
7297 SSLConfigService::SetCRLSet(
7298 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7299 false, &kOCSPTestCertSPKI, "\x0a")));
7301 CertStatus cert_status = 0;
7302 DoConnection(ssl_options, &cert_status);
7304 // If the certificate is recorded as revoked in the CRLSet, that should be
7305 // reflected without online revocation checking.
7306 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7307 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7308 EXPECT_FALSE(
7309 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7311 #endif // !defined(OS_IOS)
7313 #if !defined(DISABLE_FTP_SUPPORT)
7314 class URLRequestTestFTP : public URLRequestTest {
7315 public:
7316 URLRequestTestFTP()
7317 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
7318 base::FilePath()) {
7321 protected:
7322 SpawnedTestServer test_server_;
7325 // Make sure an FTP request using an unsafe ports fails.
7326 TEST_F(URLRequestTestFTP, UnsafePort) {
7327 ASSERT_TRUE(test_server_.Start());
7329 URLRequestJobFactoryImpl job_factory;
7330 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
7332 GURL url("ftp://127.0.0.1:7");
7333 job_factory.SetProtocolHandler(
7334 "ftp",
7335 new FtpProtocolHandler(&ftp_transaction_factory));
7336 default_context_.set_job_factory(&job_factory);
7338 TestDelegate d;
7340 URLRequest r(url, DEFAULT_PRIORITY, &d, &default_context_);
7341 r.Start();
7342 EXPECT_TRUE(r.is_pending());
7344 base::RunLoop().Run();
7346 EXPECT_FALSE(r.is_pending());
7347 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
7348 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
7352 // Flaky, see http://crbug.com/25045.
7353 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
7354 ASSERT_TRUE(test_server_.Start());
7356 TestDelegate d;
7358 URLRequest r(
7359 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, &default_context_);
7360 r.Start();
7361 EXPECT_TRUE(r.is_pending());
7363 base::RunLoop().Run();
7365 EXPECT_FALSE(r.is_pending());
7366 EXPECT_EQ(1, d.response_started_count());
7367 EXPECT_FALSE(d.received_data_before_response());
7368 EXPECT_LT(0, d.bytes_received());
7369 EXPECT_EQ(test_server_.host_port_pair().host(),
7370 r.GetSocketAddress().host());
7371 EXPECT_EQ(test_server_.host_port_pair().port(),
7372 r.GetSocketAddress().port());
7376 // Flaky, see http://crbug.com/25045.
7377 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
7378 ASSERT_TRUE(test_server_.Start());
7380 base::FilePath app_path;
7381 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7382 app_path = app_path.AppendASCII("LICENSE");
7383 TestDelegate d;
7385 URLRequest r(test_server_.GetURL("/LICENSE"),
7386 DEFAULT_PRIORITY,
7388 &default_context_);
7389 r.Start();
7390 EXPECT_TRUE(r.is_pending());
7392 base::RunLoop().Run();
7394 int64 file_size = 0;
7395 base::GetFileSize(app_path, &file_size);
7397 EXPECT_FALSE(r.is_pending());
7398 EXPECT_EQ(1, d.response_started_count());
7399 EXPECT_FALSE(d.received_data_before_response());
7400 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7401 EXPECT_EQ(test_server_.host_port_pair().host(),
7402 r.GetSocketAddress().host());
7403 EXPECT_EQ(test_server_.host_port_pair().port(),
7404 r.GetSocketAddress().port());
7408 // Flaky, see http://crbug.com/25045.
7409 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
7410 ASSERT_TRUE(test_server_.Start());
7412 base::FilePath app_path;
7413 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7414 app_path = app_path.AppendASCII("LICENSE");
7415 TestDelegate d;
7417 URLRequest r(
7418 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7419 DEFAULT_PRIORITY,
7421 &default_context_);
7422 r.Start();
7423 EXPECT_TRUE(r.is_pending());
7425 base::RunLoop().Run();
7427 int64 file_size = 0;
7428 base::GetFileSize(app_path, &file_size);
7430 EXPECT_FALSE(r.is_pending());
7431 EXPECT_EQ(test_server_.host_port_pair().host(),
7432 r.GetSocketAddress().host());
7433 EXPECT_EQ(test_server_.host_port_pair().port(),
7434 r.GetSocketAddress().port());
7435 EXPECT_EQ(1, d.response_started_count());
7436 EXPECT_FALSE(d.received_data_before_response());
7437 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7439 LoadTimingInfo load_timing_info;
7440 r.GetLoadTimingInfo(&load_timing_info);
7441 TestLoadTimingNoHttpResponse(load_timing_info);
7445 // Flaky, see http://crbug.com/25045.
7446 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
7447 ASSERT_TRUE(test_server_.Start());
7449 base::FilePath app_path;
7450 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7451 app_path = app_path.AppendASCII("LICENSE");
7452 TestDelegate d;
7454 URLRequest r(test_server_.GetURLWithUserAndPassword(
7455 "/LICENSE", "chrome", "wrong_password"),
7456 DEFAULT_PRIORITY,
7458 &default_context_);
7459 r.Start();
7460 EXPECT_TRUE(r.is_pending());
7462 base::RunLoop().Run();
7464 int64 file_size = 0;
7465 base::GetFileSize(app_path, &file_size);
7467 EXPECT_FALSE(r.is_pending());
7468 EXPECT_EQ(1, d.response_started_count());
7469 EXPECT_FALSE(d.received_data_before_response());
7470 EXPECT_EQ(d.bytes_received(), 0);
7474 // Flaky, see http://crbug.com/25045.
7475 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
7476 ASSERT_TRUE(test_server_.Start());
7478 base::FilePath app_path;
7479 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7480 app_path = app_path.AppendASCII("LICENSE");
7481 TestDelegate d;
7482 // Set correct login credentials. The delegate will be asked for them when
7483 // the initial login with wrong credentials will fail.
7484 d.set_credentials(AuthCredentials(kChrome, kChrome));
7486 URLRequest r(test_server_.GetURLWithUserAndPassword(
7487 "/LICENSE", "chrome", "wrong_password"),
7488 DEFAULT_PRIORITY,
7490 &default_context_);
7491 r.Start();
7492 EXPECT_TRUE(r.is_pending());
7494 base::RunLoop().Run();
7496 int64 file_size = 0;
7497 base::GetFileSize(app_path, &file_size);
7499 EXPECT_FALSE(r.is_pending());
7500 EXPECT_EQ(1, d.response_started_count());
7501 EXPECT_FALSE(d.received_data_before_response());
7502 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7506 // Flaky, see http://crbug.com/25045.
7507 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
7508 ASSERT_TRUE(test_server_.Start());
7510 base::FilePath app_path;
7511 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7512 app_path = app_path.AppendASCII("LICENSE");
7513 TestDelegate d;
7515 URLRequest r(test_server_.GetURLWithUserAndPassword(
7516 "/LICENSE", "wrong_user", "chrome"),
7517 DEFAULT_PRIORITY,
7519 &default_context_);
7520 r.Start();
7521 EXPECT_TRUE(r.is_pending());
7523 base::RunLoop().Run();
7525 int64 file_size = 0;
7526 base::GetFileSize(app_path, &file_size);
7528 EXPECT_FALSE(r.is_pending());
7529 EXPECT_EQ(1, d.response_started_count());
7530 EXPECT_FALSE(d.received_data_before_response());
7531 EXPECT_EQ(d.bytes_received(), 0);
7535 // Flaky, see http://crbug.com/25045.
7536 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
7537 ASSERT_TRUE(test_server_.Start());
7539 base::FilePath app_path;
7540 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7541 app_path = app_path.AppendASCII("LICENSE");
7542 TestDelegate d;
7543 // Set correct login credentials. The delegate will be asked for them when
7544 // the initial login with wrong credentials will fail.
7545 d.set_credentials(AuthCredentials(kChrome, kChrome));
7547 URLRequest r(test_server_.GetURLWithUserAndPassword(
7548 "/LICENSE", "wrong_user", "chrome"),
7549 DEFAULT_PRIORITY,
7551 &default_context_);
7552 r.Start();
7553 EXPECT_TRUE(r.is_pending());
7555 base::RunLoop().Run();
7557 int64 file_size = 0;
7558 base::GetFileSize(app_path, &file_size);
7560 EXPECT_FALSE(r.is_pending());
7561 EXPECT_EQ(1, d.response_started_count());
7562 EXPECT_FALSE(d.received_data_before_response());
7563 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7567 // Flaky, see http://crbug.com/25045.
7568 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
7569 ASSERT_TRUE(test_server_.Start());
7571 base::FilePath app_path;
7572 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7573 app_path = app_path.AppendASCII("LICENSE");
7575 scoped_ptr<TestDelegate> d(new TestDelegate);
7577 // Pass correct login identity in the URL.
7578 URLRequest r(
7579 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7580 DEFAULT_PRIORITY,
7581 d.get(),
7582 &default_context_);
7583 r.Start();
7584 EXPECT_TRUE(r.is_pending());
7586 base::RunLoop().Run();
7588 int64 file_size = 0;
7589 base::GetFileSize(app_path, &file_size);
7591 EXPECT_FALSE(r.is_pending());
7592 EXPECT_EQ(1, d->response_started_count());
7593 EXPECT_FALSE(d->received_data_before_response());
7594 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7597 d.reset(new TestDelegate);
7599 // This request should use cached identity from previous request.
7600 URLRequest r(test_server_.GetURL("/LICENSE"),
7601 DEFAULT_PRIORITY,
7602 d.get(),
7603 &default_context_);
7604 r.Start();
7605 EXPECT_TRUE(r.is_pending());
7607 base::RunLoop().Run();
7609 int64 file_size = 0;
7610 base::GetFileSize(app_path, &file_size);
7612 EXPECT_FALSE(r.is_pending());
7613 EXPECT_EQ(1, d->response_started_count());
7614 EXPECT_FALSE(d->received_data_before_response());
7615 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7619 // Flaky, see http://crbug.com/25045.
7620 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
7621 ASSERT_TRUE(test_server_.Start());
7623 base::FilePath app_path;
7624 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7625 app_path = app_path.AppendASCII("LICENSE");
7627 scoped_ptr<TestDelegate> d(new TestDelegate);
7628 // Set correct login credentials. The delegate will be asked for them when
7629 // the initial login with wrong credentials will fail.
7630 d->set_credentials(AuthCredentials(kChrome, kChrome));
7632 URLRequest r(test_server_.GetURLWithUserAndPassword(
7633 "/LICENSE", "chrome", "wrong_password"),
7634 DEFAULT_PRIORITY,
7635 d.get(),
7636 &default_context_);
7637 r.Start();
7638 EXPECT_TRUE(r.is_pending());
7640 base::RunLoop().Run();
7642 int64 file_size = 0;
7643 base::GetFileSize(app_path, &file_size);
7645 EXPECT_FALSE(r.is_pending());
7646 EXPECT_EQ(1, d->response_started_count());
7647 EXPECT_FALSE(d->received_data_before_response());
7648 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7651 // Use a new delegate without explicit credentials. The cached ones should be
7652 // used.
7653 d.reset(new TestDelegate);
7655 // Don't pass wrong credentials in the URL, they would override valid cached
7656 // ones.
7657 URLRequest r(test_server_.GetURL("/LICENSE"),
7658 DEFAULT_PRIORITY,
7659 d.get(),
7660 &default_context_);
7661 r.Start();
7662 EXPECT_TRUE(r.is_pending());
7664 base::RunLoop().Run();
7666 int64 file_size = 0;
7667 base::GetFileSize(app_path, &file_size);
7669 EXPECT_FALSE(r.is_pending());
7670 EXPECT_EQ(1, d->response_started_count());
7671 EXPECT_FALSE(d->received_data_before_response());
7672 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7675 #endif // !defined(DISABLE_FTP_SUPPORT)
7677 } // namespace net