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.
4
5 #include "build/build_config.h"
6
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shlobj.h>
10 #endif
11
12 #include <algorithm>
13 #include <string>
14
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/files/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/format_macros.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/memory/weak_ptr.h"
23 #include "base/message_loop/message_loop.h"
24 #include "base/message_loop/message_loop_proxy.h"
25 #include "base/path_service.h"
26 #include "base/run_loop.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/stringprintf.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "net/base/capturing_net_log.h"
34 #include "net/base/load_flags.h"
35 #include "net/base/load_timing_info.h"
36 #include "net/base/load_timing_info_test_util.h"
37 #include "net/base/net_errors.h"
38 #include "net/base/net_log.h"
39 #include "net/base/net_log_unittest.h"
40 #include "net/base/net_module.h"
41 #include "net/base/net_util.h"
42 #include "net/base/request_priority.h"
43 #include "net/base/test_data_directory.h"
44 #include "net/base/upload_bytes_element_reader.h"
45 #include "net/base/upload_data_stream.h"
46 #include "net/base/upload_file_element_reader.h"
47 #include "net/cert/ev_root_ca_metadata.h"
48 #include "net/cert/mock_cert_verifier.h"
49 #include "net/cert/test_root_certs.h"
50 #include "net/cookies/cookie_monster.h"
51 #include "net/cookies/cookie_store_test_helpers.h"
52 #include "net/disk_cache/disk_cache.h"
53 #include "net/dns/mock_host_resolver.h"
54 #include "net/ftp/ftp_network_layer.h"
55 #include "net/http/http_byte_range.h"
56 #include "net/http/http_cache.h"
57 #include "net/http/http_network_layer.h"
58 #include "net/http/http_network_session.h"
59 #include "net/http/http_request_headers.h"
60 #include "net/http/http_response_headers.h"
61 #include "net/http/http_util.h"
62 #include "net/ocsp/nss_ocsp.h"
63 #include "net/proxy/proxy_service.h"
64 #include "net/socket/ssl_client_socket.h"
65 #include "net/ssl/ssl_cipher_suite_names.h"
66 #include "net/ssl/ssl_connection_status_flags.h"
67 #include "net/test/cert_test_util.h"
68 #include "net/test/spawned_test_server/spawned_test_server.h"
69 #include "net/url_request/data_protocol_handler.h"
70 #include "net/url_request/static_http_user_agent_settings.h"
71 #include "net/url_request/url_request.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"
79
80 #if !defined(DISABLE_FILE_SUPPORT)
81 #include "net/base/filename_util.h"
82 #include "net/url_request/file_protocol_handler.h"
83 #include "net/url_request/url_request_file_dir_job.h"
84 #endif
85
86 #if !defined(DISABLE_FTP_SUPPORT)
87 #include "net/url_request/ftp_protocol_handler.h"
88 #endif
89
90 #if defined(OS_WIN)
91 #include "base/win/scoped_com_initializer.h"
92 #include "base/win/scoped_comptr.h"
93 #include "base/win/windows_version.h"
94 #endif
95
96 using base::ASCIIToUTF16;
97 using base::Time;
98
99 namespace net {
100
101 namespace {
102
103 const base::string16 kChrome(ASCIIToUTF16("chrome"));
104 const base::string16 kSecret(ASCIIToUTF16("secret"));
105 const base::string16 kUser(ASCIIToUTF16("user"));
106
107 // Tests load timing information in the case a fresh connection was used, with
108 // no proxy.
TestLoadTimingNotReused(const LoadTimingInfo & load_timing_info,int connect_timing_flags)109 void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
110 int connect_timing_flags) {
111 EXPECT_FALSE(load_timing_info.socket_reused);
112 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
113
114 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
115 EXPECT_FALSE(load_timing_info.request_start.is_null());
116
117 EXPECT_LE(load_timing_info.request_start,
118 load_timing_info.connect_timing.connect_start);
119 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
120 connect_timing_flags);
121 EXPECT_LE(load_timing_info.connect_timing.connect_end,
122 load_timing_info.send_start);
123 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
124 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
125
126 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
127 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
128 }
129
130 // Same as above, but with proxy times.
TestLoadTimingNotReusedWithProxy(const LoadTimingInfo & load_timing_info,int connect_timing_flags)131 void TestLoadTimingNotReusedWithProxy(
132 const LoadTimingInfo& load_timing_info,
133 int connect_timing_flags) {
134 EXPECT_FALSE(load_timing_info.socket_reused);
135 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
136
137 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
138 EXPECT_FALSE(load_timing_info.request_start.is_null());
139
140 EXPECT_LE(load_timing_info.request_start,
141 load_timing_info.proxy_resolve_start);
142 EXPECT_LE(load_timing_info.proxy_resolve_start,
143 load_timing_info.proxy_resolve_end);
144 EXPECT_LE(load_timing_info.proxy_resolve_end,
145 load_timing_info.connect_timing.connect_start);
146 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
147 connect_timing_flags);
148 EXPECT_LE(load_timing_info.connect_timing.connect_end,
149 load_timing_info.send_start);
150 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
151 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
152 }
153
154 // Same as above, but with a reused socket and proxy times.
TestLoadTimingReusedWithProxy(const LoadTimingInfo & load_timing_info)155 void TestLoadTimingReusedWithProxy(
156 const LoadTimingInfo& load_timing_info) {
157 EXPECT_TRUE(load_timing_info.socket_reused);
158 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
159
160 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
161 EXPECT_FALSE(load_timing_info.request_start.is_null());
162
163 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
164
165 EXPECT_LE(load_timing_info.request_start,
166 load_timing_info.proxy_resolve_start);
167 EXPECT_LE(load_timing_info.proxy_resolve_start,
168 load_timing_info.proxy_resolve_end);
169 EXPECT_LE(load_timing_info.proxy_resolve_end,
170 load_timing_info.send_start);
171 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
172 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
173 }
174
175 // Tests load timing information in the case of a cache hit, when no cache
176 // validation request was sent over the wire.
TestNetResourceProvider(int key)177 base::StringPiece TestNetResourceProvider(int key) {
178 return "header";
179 }
180
FillBuffer(char * buffer,size_t len)181 void FillBuffer(char* buffer, size_t len) {
182 static bool called = false;
183 if (!called) {
184 called = true;
185 int seed = static_cast<int>(Time::Now().ToInternalValue());
186 srand(seed);
187 }
188
189 for (size_t i = 0; i < len; i++) {
190 buffer[i] = static_cast<char>(rand());
191 if (!buffer[i])
192 buffer[i] = 'g';
193 }
194 }
195
196 #if !defined(OS_IOS)
TestLoadTimingCacheHitNoNetwork(const LoadTimingInfo & load_timing_info)197 void TestLoadTimingCacheHitNoNetwork(
198 const LoadTimingInfo& load_timing_info) {
199 EXPECT_FALSE(load_timing_info.socket_reused);
200 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
201
202 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
203 EXPECT_FALSE(load_timing_info.request_start.is_null());
204
205 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
206 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
207 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
208 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
209
210 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
211 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
212 }
213
214 // Tests load timing in the case that there is no HTTP response. This can be
215 // used to test in the case of errors or non-HTTP requests.
TestLoadTimingNoHttpResponse(const LoadTimingInfo & load_timing_info)216 void TestLoadTimingNoHttpResponse(
217 const LoadTimingInfo& load_timing_info) {
218 EXPECT_FALSE(load_timing_info.socket_reused);
219 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
220
221 // Only the request times should be non-null.
222 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
223 EXPECT_FALSE(load_timing_info.request_start.is_null());
224
225 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
226
227 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
228 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
229 EXPECT_TRUE(load_timing_info.send_start.is_null());
230 EXPECT_TRUE(load_timing_info.send_end.is_null());
231 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
232 }
233
234 // Do a case-insensitive search through |haystack| for |needle|.
ContainsString(const std::string & haystack,const char * needle)235 bool ContainsString(const std::string& haystack, const char* needle) {
236 std::string::const_iterator it =
237 std::search(haystack.begin(),
238 haystack.end(),
239 needle,
240 needle + strlen(needle),
241 base::CaseInsensitiveCompare<char>());
242 return it != haystack.end();
243 }
244
CreateSimpleUploadData(const char * data)245 UploadDataStream* CreateSimpleUploadData(const char* data) {
246 scoped_ptr<UploadElementReader> reader(
247 new UploadBytesElementReader(data, strlen(data)));
248 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
249 }
250
251 // Verify that the SSLInfo of a successful SSL connection has valid values.
CheckSSLInfo(const SSLInfo & ssl_info)252 void CheckSSLInfo(const SSLInfo& ssl_info) {
253 // -1 means unknown. 0 means no encryption.
254 EXPECT_GT(ssl_info.security_bits, 0);
255
256 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
257 int cipher_suite = SSLConnectionStatusToCipherSuite(
258 ssl_info.connection_status);
259 EXPECT_NE(0, cipher_suite);
260 }
261
CheckFullRequestHeaders(const HttpRequestHeaders & headers,const GURL & host_url)262 void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
263 const GURL& host_url) {
264 std::string sent_value;
265
266 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
267 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
268
269 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
270 EXPECT_EQ("keep-alive", sent_value);
271 }
272
FingerprintsEqual(const HashValueVector & a,const HashValueVector & b)273 bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
274 size_t size = a.size();
275
276 if (size != b.size())
277 return false;
278
279 for (size_t i = 0; i < size; ++i) {
280 if (!a[i].Equals(b[i]))
281 return false;
282 }
283
284 return true;
285 }
286 #endif // !defined(OS_IOS)
287
288 // A network delegate that allows the user to choose a subset of request stages
289 // to block in. When blocking, the delegate can do one of the following:
290 // * synchronously return a pre-specified error code, or
291 // * asynchronously return that value via an automatically called callback,
292 // or
293 // * block and wait for the user to do a callback.
294 // Additionally, the user may also specify a redirect URL -- then each request
295 // with the current URL different from the redirect target will be redirected
296 // to that target, in the on-before-URL-request stage, independent of whether
297 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
298 class BlockingNetworkDelegate : public TestNetworkDelegate {
299 public:
300 // Stages in which the delegate can block.
301 enum Stage {
302 NOT_BLOCKED = 0,
303 ON_BEFORE_URL_REQUEST = 1 << 0,
304 ON_BEFORE_SEND_HEADERS = 1 << 1,
305 ON_HEADERS_RECEIVED = 1 << 2,
306 ON_AUTH_REQUIRED = 1 << 3
307 };
308
309 // Behavior during blocked stages. During other stages, just
310 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
311 enum BlockMode {
312 SYNCHRONOUS, // No callback, returns specified return values.
313 AUTO_CALLBACK, // |this| posts a task to run the callback using the
314 // specified return codes.
315 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
316 // |auth_retval_| are ignored. In every blocking stage the
317 // message loop is quit.
318 };
319
320 // Creates a delegate which does not block at all.
321 explicit BlockingNetworkDelegate(BlockMode block_mode);
322
323 // For users to trigger a callback returning |response|.
324 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
325 // Only call if |block_mode_| == USER_CALLBACK.
326 void DoCallback(int response);
327 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
328
329 // Setters.
set_retval(int retval)330 void set_retval(int retval) {
331 ASSERT_NE(USER_CALLBACK, block_mode_);
332 ASSERT_NE(ERR_IO_PENDING, retval);
333 ASSERT_NE(OK, retval);
334 retval_ = retval;
335 }
336
337 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
338 // |auth_credentials_| will be passed with the response.
set_auth_retval(AuthRequiredResponse auth_retval)339 void set_auth_retval(AuthRequiredResponse auth_retval) {
340 ASSERT_NE(USER_CALLBACK, block_mode_);
341 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
342 auth_retval_ = auth_retval;
343 }
set_auth_credentials(const AuthCredentials & auth_credentials)344 void set_auth_credentials(const AuthCredentials& auth_credentials) {
345 auth_credentials_ = auth_credentials;
346 }
347
set_redirect_url(const GURL & url)348 void set_redirect_url(const GURL& url) {
349 redirect_url_ = url;
350 }
351
set_block_on(int block_on)352 void set_block_on(int block_on) {
353 block_on_ = block_on;
354 }
355
356 // Allows the user to check in which state did we block.
stage_blocked_for_callback() const357 Stage stage_blocked_for_callback() const {
358 EXPECT_EQ(USER_CALLBACK, block_mode_);
359 return stage_blocked_for_callback_;
360 }
361
362 private:
363 void RunCallback(int response, const CompletionCallback& callback);
364 void RunAuthCallback(AuthRequiredResponse response,
365 const AuthCallback& callback);
366
367 // TestNetworkDelegate implementation.
368 virtual int OnBeforeURLRequest(URLRequest* request,
369 const CompletionCallback& callback,
370 GURL* new_url) OVERRIDE;
371
372 virtual int OnBeforeSendHeaders(URLRequest* request,
373 const CompletionCallback& callback,
374 HttpRequestHeaders* headers) OVERRIDE;
375
376 virtual int OnHeadersReceived(
377 URLRequest* request,
378 const CompletionCallback& callback,
379 const HttpResponseHeaders* original_response_headers,
380 scoped_refptr<HttpResponseHeaders>* override_response_headers,
381 GURL* allowed_unsafe_redirect_url) OVERRIDE;
382
383 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
384 URLRequest* request,
385 const AuthChallengeInfo& auth_info,
386 const AuthCallback& callback,
387 AuthCredentials* credentials) OVERRIDE;
388
389 // Resets the callbacks and |stage_blocked_for_callback_|.
390 void Reset();
391
392 // Checks whether we should block in |stage|. If yes, returns an error code
393 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
394 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
395
396 // Configuration parameters, can be adjusted by public methods:
397 const BlockMode block_mode_;
398
399 // Values returned on blocking stages when mode is SYNCHRONOUS or
400 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
401 int retval_; // To be returned in non-auth stages.
402 AuthRequiredResponse auth_retval_;
403
404 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
405 int block_on_; // Bit mask: in which stages to block.
406
407 // |auth_credentials_| will be copied to |*target_auth_credential_| on
408 // callback.
409 AuthCredentials auth_credentials_;
410 AuthCredentials* target_auth_credentials_;
411
412 // Internal variables, not set by not the user:
413 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
414 // USER_CALLBACK).
415 Stage stage_blocked_for_callback_;
416
417 // Callback objects stored during blocking stages.
418 CompletionCallback callback_;
419 AuthCallback auth_callback_;
420
421 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
422
423 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
424 };
425
BlockingNetworkDelegate(BlockMode block_mode)426 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
427 : block_mode_(block_mode),
428 retval_(OK),
429 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
430 block_on_(0),
431 target_auth_credentials_(NULL),
432 stage_blocked_for_callback_(NOT_BLOCKED),
433 weak_factory_(this) {
434 }
435
DoCallback(int response)436 void BlockingNetworkDelegate::DoCallback(int response) {
437 ASSERT_EQ(USER_CALLBACK, block_mode_);
438 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
439 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
440 CompletionCallback callback = callback_;
441 Reset();
442 RunCallback(response, callback);
443 }
444
DoAuthCallback(NetworkDelegate::AuthRequiredResponse response)445 void BlockingNetworkDelegate::DoAuthCallback(
446 NetworkDelegate::AuthRequiredResponse response) {
447 ASSERT_EQ(USER_CALLBACK, block_mode_);
448 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
449 AuthCallback auth_callback = auth_callback_;
450 Reset();
451 RunAuthCallback(response, auth_callback);
452 }
453
RunCallback(int response,const CompletionCallback & callback)454 void BlockingNetworkDelegate::RunCallback(int response,
455 const CompletionCallback& callback) {
456 callback.Run(response);
457 }
458
RunAuthCallback(AuthRequiredResponse response,const AuthCallback & callback)459 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
460 const AuthCallback& callback) {
461 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
462 ASSERT_TRUE(target_auth_credentials_ != NULL);
463 *target_auth_credentials_ = auth_credentials_;
464 }
465 callback.Run(response);
466 }
467
OnBeforeURLRequest(URLRequest * request,const CompletionCallback & callback,GURL * new_url)468 int BlockingNetworkDelegate::OnBeforeURLRequest(
469 URLRequest* request,
470 const CompletionCallback& callback,
471 GURL* new_url) {
472 if (redirect_url_ == request->url())
473 return OK; // We've already seen this request and redirected elsewhere.
474
475 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
476
477 if (!redirect_url_.is_empty())
478 *new_url = redirect_url_;
479
480 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
481 }
482
OnBeforeSendHeaders(URLRequest * request,const CompletionCallback & callback,HttpRequestHeaders * headers)483 int BlockingNetworkDelegate::OnBeforeSendHeaders(
484 URLRequest* request,
485 const CompletionCallback& callback,
486 HttpRequestHeaders* headers) {
487 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
488
489 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
490 }
491
OnHeadersReceived(URLRequest * request,const CompletionCallback & callback,const HttpResponseHeaders * original_response_headers,scoped_refptr<HttpResponseHeaders> * override_response_headers,GURL * allowed_unsafe_redirect_url)492 int BlockingNetworkDelegate::OnHeadersReceived(
493 URLRequest* request,
494 const CompletionCallback& callback,
495 const HttpResponseHeaders* original_response_headers,
496 scoped_refptr<HttpResponseHeaders>* override_response_headers,
497 GURL* allowed_unsafe_redirect_url) {
498 TestNetworkDelegate::OnHeadersReceived(request,
499 callback,
500 original_response_headers,
501 override_response_headers,
502 allowed_unsafe_redirect_url);
503
504 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
505 }
506
OnAuthRequired(URLRequest * request,const AuthChallengeInfo & auth_info,const AuthCallback & callback,AuthCredentials * credentials)507 NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
508 URLRequest* request,
509 const AuthChallengeInfo& auth_info,
510 const AuthCallback& callback,
511 AuthCredentials* credentials) {
512 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
513 credentials);
514 // Check that the user has provided callback for the previous blocked stage.
515 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
516
517 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
518 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
519 }
520
521 target_auth_credentials_ = credentials;
522
523 switch (block_mode_) {
524 case SYNCHRONOUS:
525 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
526 *target_auth_credentials_ = auth_credentials_;
527 return auth_retval_;
528
529 case AUTO_CALLBACK:
530 base::MessageLoop::current()->PostTask(
531 FROM_HERE,
532 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
533 weak_factory_.GetWeakPtr(), auth_retval_, callback));
534 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
535
536 case USER_CALLBACK:
537 auth_callback_ = callback;
538 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
539 base::MessageLoop::current()->PostTask(FROM_HERE,
540 base::MessageLoop::QuitClosure());
541 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
542 }
543 NOTREACHED();
544 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
545 }
546
Reset()547 void BlockingNetworkDelegate::Reset() {
548 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
549 stage_blocked_for_callback_ = NOT_BLOCKED;
550 callback_.Reset();
551 auth_callback_.Reset();
552 }
553
MaybeBlockStage(BlockingNetworkDelegate::Stage stage,const CompletionCallback & callback)554 int BlockingNetworkDelegate::MaybeBlockStage(
555 BlockingNetworkDelegate::Stage stage,
556 const CompletionCallback& callback) {
557 // Check that the user has provided callback for the previous blocked stage.
558 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
559
560 if ((block_on_ & stage) == 0) {
561 return OK;
562 }
563
564 switch (block_mode_) {
565 case SYNCHRONOUS:
566 EXPECT_NE(OK, retval_);
567 return retval_;
568
569 case AUTO_CALLBACK:
570 base::MessageLoop::current()->PostTask(
571 FROM_HERE,
572 base::Bind(&BlockingNetworkDelegate::RunCallback,
573 weak_factory_.GetWeakPtr(), retval_, callback));
574 return ERR_IO_PENDING;
575
576 case USER_CALLBACK:
577 callback_ = callback;
578 stage_blocked_for_callback_ = stage;
579 base::MessageLoop::current()->PostTask(FROM_HERE,
580 base::MessageLoop::QuitClosure());
581 return ERR_IO_PENDING;
582 }
583 NOTREACHED();
584 return 0;
585 }
586
587 class TestURLRequestContextWithProxy : public TestURLRequestContext {
588 public:
589 // Does not own |delegate|.
TestURLRequestContextWithProxy(const std::string & proxy,NetworkDelegate * delegate)590 TestURLRequestContextWithProxy(const std::string& proxy,
591 NetworkDelegate* delegate)
592 : TestURLRequestContext(true) {
593 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
594 set_network_delegate(delegate);
595 Init();
596 }
~TestURLRequestContextWithProxy()597 virtual ~TestURLRequestContextWithProxy() {}
598 };
599
600 } // namespace
601
602 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
603 class URLRequestTest : public PlatformTest {
604 public:
URLRequestTest()605 URLRequestTest() : default_context_(true) {
606 default_context_.set_network_delegate(&default_network_delegate_);
607 default_context_.set_net_log(&net_log_);
608 job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
609 #if !defined(DISABLE_FILE_SUPPORT)
610 job_factory_.SetProtocolHandler(
611 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
612 #endif
613 default_context_.set_job_factory(&job_factory_);
614 default_context_.Init();
615 }
~URLRequestTest()616 virtual ~URLRequestTest() {
617 // URLRequestJobs may post clean-up tasks on destruction.
618 base::RunLoop().RunUntilIdle();
619 }
620
621 // Adds the TestJobInterceptor to the default context.
AddTestInterceptor()622 TestJobInterceptor* AddTestInterceptor() {
623 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
624 job_factory_.SetProtocolHandler("http", NULL);
625 job_factory_.SetProtocolHandler("http", protocol_handler_);
626 return protocol_handler_;
627 }
628
629 protected:
630 CapturingNetLog net_log_;
631 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
632 URLRequestJobFactoryImpl job_factory_;
633 TestURLRequestContext default_context_;
634 };
635
TEST_F(URLRequestTest,AboutBlankTest)636 TEST_F(URLRequestTest, AboutBlankTest) {
637 TestDelegate d;
638 {
639 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
640 GURL("about:blank"), DEFAULT_PRIORITY, &d, NULL));
641
642 r->Start();
643 EXPECT_TRUE(r->is_pending());
644
645 base::RunLoop().Run();
646
647 EXPECT_TRUE(!r->is_pending());
648 EXPECT_FALSE(d.received_data_before_response());
649 EXPECT_EQ(d.bytes_received(), 0);
650 EXPECT_EQ("", r->GetSocketAddress().host());
651 EXPECT_EQ(0, r->GetSocketAddress().port());
652
653 HttpRequestHeaders headers;
654 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
655 }
656 }
657
TEST_F(URLRequestTest,DataURLImageTest)658 TEST_F(URLRequestTest, DataURLImageTest) {
659 TestDelegate d;
660 {
661 // Use our nice little Chrome logo.
662 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
663 GURL(
664 "data:image/png;base64,"
665 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
666 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
667 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
668 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
669 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
670 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
671 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
672 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
673 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
674 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
675 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
676 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
677 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
678 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
679 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
680 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
681 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
682 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
683 DEFAULT_PRIORITY, &d, NULL));
684
685 r->Start();
686 EXPECT_TRUE(r->is_pending());
687
688 base::RunLoop().Run();
689
690 EXPECT_TRUE(!r->is_pending());
691 EXPECT_FALSE(d.received_data_before_response());
692 EXPECT_EQ(d.bytes_received(), 911);
693 EXPECT_EQ("", r->GetSocketAddress().host());
694 EXPECT_EQ(0, r->GetSocketAddress().port());
695
696 HttpRequestHeaders headers;
697 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
698 }
699 }
700
701 #if !defined(DISABLE_FILE_SUPPORT)
TEST_F(URLRequestTest,FileTest)702 TEST_F(URLRequestTest, FileTest) {
703 base::FilePath app_path;
704 PathService::Get(base::FILE_EXE, &app_path);
705 GURL app_url = FilePathToFileURL(app_path);
706
707 TestDelegate d;
708 {
709 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
710 app_url, DEFAULT_PRIORITY, &d, NULL));
711
712 r->Start();
713 EXPECT_TRUE(r->is_pending());
714
715 base::RunLoop().Run();
716
717 int64 file_size = -1;
718 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
719
720 EXPECT_TRUE(!r->is_pending());
721 EXPECT_EQ(1, d.response_started_count());
722 EXPECT_FALSE(d.received_data_before_response());
723 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
724 EXPECT_EQ("", r->GetSocketAddress().host());
725 EXPECT_EQ(0, r->GetSocketAddress().port());
726
727 HttpRequestHeaders headers;
728 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
729 }
730 }
731
TEST_F(URLRequestTest,FileTestCancel)732 TEST_F(URLRequestTest, FileTestCancel) {
733 base::FilePath app_path;
734 PathService::Get(base::FILE_EXE, &app_path);
735 GURL app_url = FilePathToFileURL(app_path);
736
737 TestDelegate d;
738 {
739 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
740 app_url, DEFAULT_PRIORITY, &d, NULL));
741
742 r->Start();
743 EXPECT_TRUE(r->is_pending());
744 r->Cancel();
745 }
746 // Async cancellation should be safe even when URLRequest has been already
747 // destroyed.
748 base::RunLoop().RunUntilIdle();
749 }
750
TEST_F(URLRequestTest,FileTestFullSpecifiedRange)751 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
752 const size_t buffer_size = 4000;
753 scoped_ptr<char[]> buffer(new char[buffer_size]);
754 FillBuffer(buffer.get(), buffer_size);
755
756 base::FilePath temp_path;
757 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
758 GURL temp_url = FilePathToFileURL(temp_path);
759 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
760
761 int64 file_size;
762 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
763
764 const size_t first_byte_position = 500;
765 const size_t last_byte_position = buffer_size - first_byte_position;
766 const size_t content_length = last_byte_position - first_byte_position + 1;
767 std::string partial_buffer_string(buffer.get() + first_byte_position,
768 buffer.get() + last_byte_position + 1);
769
770 TestDelegate d;
771 {
772 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
773 temp_url, DEFAULT_PRIORITY, &d, NULL));
774
775 HttpRequestHeaders headers;
776 headers.SetHeader(
777 HttpRequestHeaders::kRange,
778 HttpByteRange::Bounded(
779 first_byte_position, last_byte_position).GetHeaderValue());
780 r->SetExtraRequestHeaders(headers);
781 r->Start();
782 EXPECT_TRUE(r->is_pending());
783
784 base::RunLoop().Run();
785 EXPECT_TRUE(!r->is_pending());
786 EXPECT_EQ(1, d.response_started_count());
787 EXPECT_FALSE(d.received_data_before_response());
788 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
789 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
790 EXPECT_TRUE(partial_buffer_string == d.data_received());
791 }
792
793 EXPECT_TRUE(base::DeleteFile(temp_path, false));
794 }
795
TEST_F(URLRequestTest,FileTestHalfSpecifiedRange)796 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
797 const size_t buffer_size = 4000;
798 scoped_ptr<char[]> buffer(new char[buffer_size]);
799 FillBuffer(buffer.get(), buffer_size);
800
801 base::FilePath temp_path;
802 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
803 GURL temp_url = FilePathToFileURL(temp_path);
804 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
805
806 int64 file_size;
807 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
808
809 const size_t first_byte_position = 500;
810 const size_t last_byte_position = buffer_size - 1;
811 const size_t content_length = last_byte_position - first_byte_position + 1;
812 std::string partial_buffer_string(buffer.get() + first_byte_position,
813 buffer.get() + last_byte_position + 1);
814
815 TestDelegate d;
816 {
817 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
818 temp_url, DEFAULT_PRIORITY, &d, NULL));
819
820 HttpRequestHeaders headers;
821 headers.SetHeader(HttpRequestHeaders::kRange,
822 HttpByteRange::RightUnbounded(
823 first_byte_position).GetHeaderValue());
824 r->SetExtraRequestHeaders(headers);
825 r->Start();
826 EXPECT_TRUE(r->is_pending());
827
828 base::RunLoop().Run();
829 EXPECT_TRUE(!r->is_pending());
830 EXPECT_EQ(1, d.response_started_count());
831 EXPECT_FALSE(d.received_data_before_response());
832 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
833 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
834 EXPECT_TRUE(partial_buffer_string == d.data_received());
835 }
836
837 EXPECT_TRUE(base::DeleteFile(temp_path, false));
838 }
839
TEST_F(URLRequestTest,FileTestMultipleRanges)840 TEST_F(URLRequestTest, FileTestMultipleRanges) {
841 const size_t buffer_size = 400000;
842 scoped_ptr<char[]> buffer(new char[buffer_size]);
843 FillBuffer(buffer.get(), buffer_size);
844
845 base::FilePath temp_path;
846 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
847 GURL temp_url = FilePathToFileURL(temp_path);
848 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
849
850 int64 file_size;
851 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
852
853 TestDelegate d;
854 {
855 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
856 temp_url, DEFAULT_PRIORITY, &d, NULL));
857
858 HttpRequestHeaders headers;
859 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
860 r->SetExtraRequestHeaders(headers);
861 r->Start();
862 EXPECT_TRUE(r->is_pending());
863
864 base::RunLoop().Run();
865 EXPECT_TRUE(d.request_failed());
866 }
867
868 EXPECT_TRUE(base::DeleteFile(temp_path, false));
869 }
870
TEST_F(URLRequestTest,AllowFileURLs)871 TEST_F(URLRequestTest, AllowFileURLs) {
872 base::ScopedTempDir temp_dir;
873 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
874 base::FilePath test_file;
875 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
876 std::string test_data("monkey");
877 base::WriteFile(test_file, test_data.data(), test_data.size());
878 GURL test_file_url = FilePathToFileURL(test_file);
879
880 {
881 TestDelegate d;
882 TestNetworkDelegate network_delegate;
883 network_delegate.set_can_access_files(true);
884 default_context_.set_network_delegate(&network_delegate);
885 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
886 test_file_url, DEFAULT_PRIORITY, &d, NULL));
887 r->Start();
888 base::RunLoop().Run();
889 EXPECT_FALSE(d.request_failed());
890 EXPECT_EQ(test_data, d.data_received());
891 }
892
893 {
894 TestDelegate d;
895 TestNetworkDelegate network_delegate;
896 network_delegate.set_can_access_files(false);
897 default_context_.set_network_delegate(&network_delegate);
898 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
899 test_file_url, DEFAULT_PRIORITY, &d, NULL));
900 r->Start();
901 base::RunLoop().Run();
902 EXPECT_TRUE(d.request_failed());
903 EXPECT_EQ("", d.data_received());
904 }
905 }
906
907
TEST_F(URLRequestTest,FileDirCancelTest)908 TEST_F(URLRequestTest, FileDirCancelTest) {
909 // Put in mock resource provider.
910 NetModule::SetResourceProvider(TestNetResourceProvider);
911
912 TestDelegate d;
913 {
914 base::FilePath file_path;
915 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
916 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
917 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
918
919 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
920 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, NULL));
921 req->Start();
922 EXPECT_TRUE(req->is_pending());
923
924 d.set_cancel_in_received_data_pending(true);
925
926 base::RunLoop().Run();
927 }
928
929 // Take out mock resource provider.
930 NetModule::SetResourceProvider(NULL);
931 }
932
TEST_F(URLRequestTest,FileDirOutputSanity)933 TEST_F(URLRequestTest, FileDirOutputSanity) {
934 // Verify the general sanity of the the output of the file:
935 // directory lister by checking for the output of a known existing
936 // file.
937 const char sentinel_name[] = "filedir-sentinel";
938
939 base::FilePath path;
940 PathService::Get(base::DIR_SOURCE_ROOT, &path);
941 path = path.Append(FILE_PATH_LITERAL("net"));
942 path = path.Append(FILE_PATH_LITERAL("data"));
943 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
944
945 TestDelegate d;
946 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
947 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
948 req->Start();
949 base::RunLoop().Run();
950
951 // Generate entry for the sentinel file.
952 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
953 base::File::Info info;
954 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
955 EXPECT_GT(info.size, 0);
956 std::string sentinel_output = GetDirectoryListingEntry(
957 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
958 std::string(sentinel_name),
959 false /* is_dir */,
960 info.size,
961 info.last_modified);
962
963 ASSERT_LT(0, d.bytes_received());
964 ASSERT_FALSE(d.request_failed());
965 ASSERT_TRUE(req->status().is_success());
966 // Check for the entry generated for the "sentinel" file.
967 const std::string& data = d.data_received();
968 ASSERT_NE(data.find(sentinel_output), std::string::npos);
969 }
970
TEST_F(URLRequestTest,FileDirRedirectNoCrash)971 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
972 // There is an implicit redirect when loading a file path that matches a
973 // directory and does not end with a slash. Ensure that following such
974 // redirects does not crash. See http://crbug.com/18686.
975
976 base::FilePath path;
977 PathService::Get(base::DIR_SOURCE_ROOT, &path);
978 path = path.Append(FILE_PATH_LITERAL("net"));
979 path = path.Append(FILE_PATH_LITERAL("data"));
980 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
981
982 TestDelegate d;
983 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
984 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
985 req->Start();
986 base::RunLoop().Run();
987
988 ASSERT_EQ(1, d.received_redirect_count());
989 ASSERT_LT(0, d.bytes_received());
990 ASSERT_FALSE(d.request_failed());
991 ASSERT_TRUE(req->status().is_success());
992 }
993
994 #if defined(OS_WIN)
995 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
TEST_F(URLRequestTest,FileDirRedirectSingleSlash)996 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
997 TestDelegate d;
998 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
999 GURL("file:///"), DEFAULT_PRIORITY, &d, NULL));
1000 req->Start();
1001 base::RunLoop().Run();
1002
1003 ASSERT_EQ(1, d.received_redirect_count());
1004 ASSERT_FALSE(req->status().is_success());
1005 }
1006 #endif // defined(OS_WIN)
1007
1008 #endif // !defined(DISABLE_FILE_SUPPORT)
1009
TEST_F(URLRequestTest,InvalidUrlTest)1010 TEST_F(URLRequestTest, InvalidUrlTest) {
1011 TestDelegate d;
1012 {
1013 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1014 GURL("invalid url"), DEFAULT_PRIORITY, &d, NULL));
1015
1016 r->Start();
1017 EXPECT_TRUE(r->is_pending());
1018
1019 base::RunLoop().Run();
1020 EXPECT_TRUE(d.request_failed());
1021 }
1022 }
1023
TEST_F(URLRequestTest,InvalidReferrerTest)1024 TEST_F(URLRequestTest, InvalidReferrerTest) {
1025 TestURLRequestContext context;
1026 TestNetworkDelegate network_delegate;
1027 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1028 context.set_network_delegate(&network_delegate);
1029 TestDelegate d;
1030 scoped_ptr<URLRequest> req(context.CreateRequest(
1031 GURL("http://localhost/"), DEFAULT_PRIORITY, &d, NULL));
1032 req->SetReferrer("https://somewhere.com/");
1033
1034 req->Start();
1035 base::RunLoop().Run();
1036 EXPECT_TRUE(d.request_failed());
1037 }
1038
1039 #if defined(OS_WIN)
TEST_F(URLRequestTest,ResolveShortcutTest)1040 TEST_F(URLRequestTest, ResolveShortcutTest) {
1041 base::FilePath app_path;
1042 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1043 app_path = app_path.AppendASCII("net");
1044 app_path = app_path.AppendASCII("data");
1045 app_path = app_path.AppendASCII("url_request_unittest");
1046 app_path = app_path.AppendASCII("with-headers.html");
1047
1048 std::wstring lnk_path = app_path.value() + L".lnk";
1049
1050 base::win::ScopedCOMInitializer com_initializer;
1051
1052 // Temporarily create a shortcut for test
1053 {
1054 base::win::ScopedComPtr<IShellLink> shell;
1055 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1056 CLSCTX_INPROC_SERVER)));
1057 base::win::ScopedComPtr<IPersistFile> persist;
1058 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1059 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1060 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1061 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1062 }
1063
1064 TestDelegate d;
1065 {
1066 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1067 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1068 NULL));
1069
1070 r->Start();
1071 EXPECT_TRUE(r->is_pending());
1072
1073 base::RunLoop().Run();
1074
1075 WIN32_FILE_ATTRIBUTE_DATA data;
1076 GetFileAttributesEx(app_path.value().c_str(),
1077 GetFileExInfoStandard, &data);
1078 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1079 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1080 FILE_ATTRIBUTE_NORMAL, NULL);
1081 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1082 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1083 DWORD read_size;
1084 BOOL result;
1085 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1086 &read_size, NULL);
1087 std::string content(buffer.get(), read_size);
1088 CloseHandle(file);
1089
1090 EXPECT_TRUE(!r->is_pending());
1091 EXPECT_EQ(1, d.received_redirect_count());
1092 EXPECT_EQ(content, d.data_received());
1093 }
1094
1095 // Clean the shortcut
1096 DeleteFile(lnk_path.c_str());
1097 }
1098 #endif // defined(OS_WIN)
1099
1100 // Custom URLRequestJobs for use with interceptor tests
1101 class RestartTestJob : public URLRequestTestJob {
1102 public:
RestartTestJob(URLRequest * request,NetworkDelegate * network_delegate)1103 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1104 : URLRequestTestJob(request, network_delegate, true) {}
1105 protected:
StartAsync()1106 virtual void StartAsync() OVERRIDE {
1107 this->NotifyRestartRequired();
1108 }
1109 private:
~RestartTestJob()1110 virtual ~RestartTestJob() {}
1111 };
1112
1113 class CancelTestJob : public URLRequestTestJob {
1114 public:
CancelTestJob(URLRequest * request,NetworkDelegate * network_delegate)1115 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1116 : URLRequestTestJob(request, network_delegate, true) {}
1117 protected:
StartAsync()1118 virtual void StartAsync() OVERRIDE {
1119 request_->Cancel();
1120 }
1121 private:
~CancelTestJob()1122 virtual ~CancelTestJob() {}
1123 };
1124
1125 class CancelThenRestartTestJob : public URLRequestTestJob {
1126 public:
CancelThenRestartTestJob(URLRequest * request,NetworkDelegate * network_delegate)1127 explicit CancelThenRestartTestJob(URLRequest* request,
1128 NetworkDelegate* network_delegate)
1129 : URLRequestTestJob(request, network_delegate, true) {
1130 }
1131 protected:
StartAsync()1132 virtual void StartAsync() OVERRIDE {
1133 request_->Cancel();
1134 this->NotifyRestartRequired();
1135 }
1136 private:
~CancelThenRestartTestJob()1137 virtual ~CancelThenRestartTestJob() {}
1138 };
1139
1140 // An Interceptor for use with interceptor tests
1141 class TestInterceptor : URLRequest::Interceptor {
1142 public:
TestInterceptor()1143 TestInterceptor()
1144 : intercept_main_request_(false), restart_main_request_(false),
1145 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1146 simulate_main_network_error_(false),
1147 intercept_redirect_(false), cancel_redirect_request_(false),
1148 intercept_final_response_(false), cancel_final_request_(false),
1149 did_intercept_main_(false), did_restart_main_(false),
1150 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1151 did_simulate_error_main_(false),
1152 did_intercept_redirect_(false), did_cancel_redirect_(false),
1153 did_intercept_final_(false), did_cancel_final_(false) {
1154 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1155 }
1156
~TestInterceptor()1157 virtual ~TestInterceptor() {
1158 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1159 }
1160
MaybeIntercept(URLRequest * request,NetworkDelegate * network_delegate)1161 virtual URLRequestJob* MaybeIntercept(
1162 URLRequest* request,
1163 NetworkDelegate* network_delegate) OVERRIDE {
1164 if (restart_main_request_) {
1165 restart_main_request_ = false;
1166 did_restart_main_ = true;
1167 return new RestartTestJob(request, network_delegate);
1168 }
1169 if (cancel_main_request_) {
1170 cancel_main_request_ = false;
1171 did_cancel_main_ = true;
1172 return new CancelTestJob(request, network_delegate);
1173 }
1174 if (cancel_then_restart_main_request_) {
1175 cancel_then_restart_main_request_ = false;
1176 did_cancel_then_restart_main_ = true;
1177 return new CancelThenRestartTestJob(request, network_delegate);
1178 }
1179 if (simulate_main_network_error_) {
1180 simulate_main_network_error_ = false;
1181 did_simulate_error_main_ = true;
1182 // will error since the requeted url is not one of its canned urls
1183 return new URLRequestTestJob(request, network_delegate, true);
1184 }
1185 if (!intercept_main_request_)
1186 return NULL;
1187 intercept_main_request_ = false;
1188 did_intercept_main_ = true;
1189 URLRequestTestJob* job = new URLRequestTestJob(request,
1190 network_delegate,
1191 main_headers_,
1192 main_data_,
1193 true);
1194 job->set_load_timing_info(main_request_load_timing_info_);
1195 return job;
1196 }
1197
MaybeInterceptRedirect(URLRequest * request,NetworkDelegate * network_delegate,const GURL & location)1198 virtual URLRequestJob* MaybeInterceptRedirect(
1199 URLRequest* request,
1200 NetworkDelegate* network_delegate,
1201 const GURL& location) OVERRIDE {
1202 if (cancel_redirect_request_) {
1203 cancel_redirect_request_ = false;
1204 did_cancel_redirect_ = true;
1205 return new CancelTestJob(request, network_delegate);
1206 }
1207 if (!intercept_redirect_)
1208 return NULL;
1209 intercept_redirect_ = false;
1210 did_intercept_redirect_ = true;
1211 return new URLRequestTestJob(request,
1212 network_delegate,
1213 redirect_headers_,
1214 redirect_data_,
1215 true);
1216 }
1217
MaybeInterceptResponse(URLRequest * request,NetworkDelegate * network_delegate)1218 virtual URLRequestJob* MaybeInterceptResponse(
1219 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
1220 if (cancel_final_request_) {
1221 cancel_final_request_ = false;
1222 did_cancel_final_ = true;
1223 return new CancelTestJob(request, network_delegate);
1224 }
1225 if (!intercept_final_response_)
1226 return NULL;
1227 intercept_final_response_ = false;
1228 did_intercept_final_ = true;
1229 return new URLRequestTestJob(request,
1230 network_delegate,
1231 final_headers_,
1232 final_data_,
1233 true);
1234 }
1235
1236 // Whether to intercept the main request, and if so the response to return and
1237 // the LoadTimingInfo to use.
1238 bool intercept_main_request_;
1239 std::string main_headers_;
1240 std::string main_data_;
1241 LoadTimingInfo main_request_load_timing_info_;
1242
1243 // Other actions we take at MaybeIntercept time
1244 bool restart_main_request_;
1245 bool cancel_main_request_;
1246 bool cancel_then_restart_main_request_;
1247 bool simulate_main_network_error_;
1248
1249 // Whether to intercept redirects, and if so the response to return.
1250 bool intercept_redirect_;
1251 std::string redirect_headers_;
1252 std::string redirect_data_;
1253
1254 // Other actions we can take at MaybeInterceptRedirect time
1255 bool cancel_redirect_request_;
1256
1257 // Whether to intercept final response, and if so the response to return.
1258 bool intercept_final_response_;
1259 std::string final_headers_;
1260 std::string final_data_;
1261
1262 // Other actions we can take at MaybeInterceptResponse time
1263 bool cancel_final_request_;
1264
1265 // If we did something or not
1266 bool did_intercept_main_;
1267 bool did_restart_main_;
1268 bool did_cancel_main_;
1269 bool did_cancel_then_restart_main_;
1270 bool did_simulate_error_main_;
1271 bool did_intercept_redirect_;
1272 bool did_cancel_redirect_;
1273 bool did_intercept_final_;
1274 bool did_cancel_final_;
1275
1276 // Static getters for canned response header and data strings
1277
ok_data()1278 static std::string ok_data() {
1279 return URLRequestTestJob::test_data_1();
1280 }
1281
ok_headers()1282 static std::string ok_headers() {
1283 return URLRequestTestJob::test_headers();
1284 }
1285
redirect_data()1286 static std::string redirect_data() {
1287 return std::string();
1288 }
1289
redirect_headers()1290 static std::string redirect_headers() {
1291 return URLRequestTestJob::test_redirect_headers();
1292 }
1293
error_data()1294 static std::string error_data() {
1295 return std::string("ohhh nooooo mr. bill!");
1296 }
1297
error_headers()1298 static std::string error_headers() {
1299 return URLRequestTestJob::test_error_headers();
1300 }
1301 };
1302
TEST_F(URLRequestTest,Intercept)1303 TEST_F(URLRequestTest, Intercept) {
1304 TestInterceptor interceptor;
1305
1306 // intercept the main request and respond with a simple response
1307 interceptor.intercept_main_request_ = true;
1308 interceptor.main_headers_ = TestInterceptor::ok_headers();
1309 interceptor.main_data_ = TestInterceptor::ok_data();
1310
1311 TestDelegate d;
1312 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1313 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1314 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1315 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1316 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1317 req->SetUserData(NULL, user_data0);
1318 req->SetUserData(&user_data1, user_data1);
1319 req->SetUserData(&user_data2, user_data2);
1320 req->set_method("GET");
1321 req->Start();
1322 base::RunLoop().Run();
1323
1324 // Make sure we can retrieve our specific user data
1325 EXPECT_EQ(user_data0, req->GetUserData(NULL));
1326 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1327 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1328
1329 // Check the interceptor got called as expected
1330 EXPECT_TRUE(interceptor.did_intercept_main_);
1331
1332 // Check we got one good response
1333 EXPECT_TRUE(req->status().is_success());
1334 EXPECT_EQ(200, req->response_headers()->response_code());
1335 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1336 EXPECT_EQ(1, d.response_started_count());
1337 EXPECT_EQ(0, d.received_redirect_count());
1338 }
1339
TEST_F(URLRequestTest,InterceptRedirect)1340 TEST_F(URLRequestTest, InterceptRedirect) {
1341 TestInterceptor interceptor;
1342
1343 // intercept the main request and respond with a redirect
1344 interceptor.intercept_main_request_ = true;
1345 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1346 interceptor.main_data_ = TestInterceptor::redirect_data();
1347
1348 // intercept that redirect and respond a final OK response
1349 interceptor.intercept_redirect_ = true;
1350 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1351 interceptor.redirect_data_ = TestInterceptor::ok_data();
1352
1353 TestDelegate d;
1354 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1355 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1356 req->set_method("GET");
1357 req->Start();
1358 base::RunLoop().Run();
1359
1360 // Check the interceptor got called as expected
1361 EXPECT_TRUE(interceptor.did_intercept_main_);
1362 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1363
1364 // Check we got one good response
1365 EXPECT_TRUE(req->status().is_success());
1366 if (req->status().is_success()) {
1367 EXPECT_EQ(200, req->response_headers()->response_code());
1368 }
1369 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1370 EXPECT_EQ(1, d.response_started_count());
1371 EXPECT_EQ(0, d.received_redirect_count());
1372 }
1373
TEST_F(URLRequestTest,InterceptServerError)1374 TEST_F(URLRequestTest, InterceptServerError) {
1375 TestInterceptor interceptor;
1376
1377 // intercept the main request to generate a server error response
1378 interceptor.intercept_main_request_ = true;
1379 interceptor.main_headers_ = TestInterceptor::error_headers();
1380 interceptor.main_data_ = TestInterceptor::error_data();
1381
1382 // intercept that error and respond with an OK response
1383 interceptor.intercept_final_response_ = true;
1384 interceptor.final_headers_ = TestInterceptor::ok_headers();
1385 interceptor.final_data_ = TestInterceptor::ok_data();
1386
1387 TestDelegate d;
1388 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1389 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1390 req->set_method("GET");
1391 req->Start();
1392 base::RunLoop().Run();
1393
1394 // Check the interceptor got called as expected
1395 EXPECT_TRUE(interceptor.did_intercept_main_);
1396 EXPECT_TRUE(interceptor.did_intercept_final_);
1397
1398 // Check we got one good response
1399 EXPECT_TRUE(req->status().is_success());
1400 EXPECT_EQ(200, req->response_headers()->response_code());
1401 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1402 EXPECT_EQ(1, d.response_started_count());
1403 EXPECT_EQ(0, d.received_redirect_count());
1404 }
1405
TEST_F(URLRequestTest,InterceptNetworkError)1406 TEST_F(URLRequestTest, InterceptNetworkError) {
1407 TestInterceptor interceptor;
1408
1409 // intercept the main request to simulate a network error
1410 interceptor.simulate_main_network_error_ = true;
1411
1412 // intercept that error and respond with an OK response
1413 interceptor.intercept_final_response_ = true;
1414 interceptor.final_headers_ = TestInterceptor::ok_headers();
1415 interceptor.final_data_ = TestInterceptor::ok_data();
1416
1417 TestDelegate d;
1418 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1419 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1420 req->set_method("GET");
1421 req->Start();
1422 base::RunLoop().Run();
1423
1424 // Check the interceptor got called as expected
1425 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1426 EXPECT_TRUE(interceptor.did_intercept_final_);
1427
1428 // Check we received one good response
1429 EXPECT_TRUE(req->status().is_success());
1430 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());
1434 }
1435
TEST_F(URLRequestTest,InterceptRestartRequired)1436 TEST_F(URLRequestTest, InterceptRestartRequired) {
1437 TestInterceptor interceptor;
1438
1439 // restart the main request
1440 interceptor.restart_main_request_ = true;
1441
1442 // then intercept the new main request and respond with an OK response
1443 interceptor.intercept_main_request_ = true;
1444 interceptor.main_headers_ = TestInterceptor::ok_headers();
1445 interceptor.main_data_ = TestInterceptor::ok_data();
1446
1447 TestDelegate d;
1448 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1449 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1450 req->set_method("GET");
1451 req->Start();
1452 base::RunLoop().Run();
1453
1454 // Check the interceptor got called as expected
1455 EXPECT_TRUE(interceptor.did_restart_main_);
1456 EXPECT_TRUE(interceptor.did_intercept_main_);
1457
1458 // Check we received one good response
1459 EXPECT_TRUE(req->status().is_success());
1460 if (req->status().is_success()) {
1461 EXPECT_EQ(200, req->response_headers()->response_code());
1462 }
1463 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1464 EXPECT_EQ(1, d.response_started_count());
1465 EXPECT_EQ(0, d.received_redirect_count());
1466 }
1467
TEST_F(URLRequestTest,InterceptRespectsCancelMain)1468 TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1469 TestInterceptor interceptor;
1470
1471 // intercept the main request and cancel from within the restarted job
1472 interceptor.cancel_main_request_ = true;
1473
1474 // setup to intercept final response and override it with an OK response
1475 interceptor.intercept_final_response_ = true;
1476 interceptor.final_headers_ = TestInterceptor::ok_headers();
1477 interceptor.final_data_ = TestInterceptor::ok_data();
1478
1479 TestDelegate d;
1480 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1481 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1482 req->set_method("GET");
1483 req->Start();
1484 base::RunLoop().Run();
1485
1486 // Check the interceptor got called as expected
1487 EXPECT_TRUE(interceptor.did_cancel_main_);
1488 EXPECT_FALSE(interceptor.did_intercept_final_);
1489
1490 // Check we see a canceled request
1491 EXPECT_FALSE(req->status().is_success());
1492 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1493 }
1494
TEST_F(URLRequestTest,InterceptRespectsCancelRedirect)1495 TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1496 TestInterceptor interceptor;
1497
1498 // intercept the main request and respond with a redirect
1499 interceptor.intercept_main_request_ = true;
1500 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1501 interceptor.main_data_ = TestInterceptor::redirect_data();
1502
1503 // intercept the redirect and cancel from within that job
1504 interceptor.cancel_redirect_request_ = true;
1505
1506 // setup to intercept final response and override it with an OK response
1507 interceptor.intercept_final_response_ = true;
1508 interceptor.final_headers_ = TestInterceptor::ok_headers();
1509 interceptor.final_data_ = TestInterceptor::ok_data();
1510
1511 TestDelegate d;
1512 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1513 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1514 req->set_method("GET");
1515 req->Start();
1516 base::RunLoop().Run();
1517
1518 // Check the interceptor got called as expected
1519 EXPECT_TRUE(interceptor.did_intercept_main_);
1520 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1521 EXPECT_FALSE(interceptor.did_intercept_final_);
1522
1523 // Check we see a canceled request
1524 EXPECT_FALSE(req->status().is_success());
1525 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1526 }
1527
TEST_F(URLRequestTest,InterceptRespectsCancelFinal)1528 TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1529 TestInterceptor interceptor;
1530
1531 // intercept the main request to simulate a network error
1532 interceptor.simulate_main_network_error_ = true;
1533
1534 // setup to intercept final response and cancel from within that job
1535 interceptor.cancel_final_request_ = true;
1536
1537 TestDelegate d;
1538 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1539 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1540 req->set_method("GET");
1541 req->Start();
1542 base::RunLoop().Run();
1543
1544 // Check the interceptor got called as expected
1545 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1546 EXPECT_TRUE(interceptor.did_cancel_final_);
1547
1548 // Check we see a canceled request
1549 EXPECT_FALSE(req->status().is_success());
1550 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1551 }
1552
TEST_F(URLRequestTest,InterceptRespectsCancelInRestart)1553 TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1554 TestInterceptor interceptor;
1555
1556 // intercept the main request and cancel then restart from within that job
1557 interceptor.cancel_then_restart_main_request_ = true;
1558
1559 // setup to intercept final response and override it with an OK response
1560 interceptor.intercept_final_response_ = true;
1561 interceptor.final_headers_ = TestInterceptor::ok_headers();
1562 interceptor.final_data_ = TestInterceptor::ok_data();
1563
1564 TestDelegate d;
1565 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1566 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1567 req->set_method("GET");
1568 req->Start();
1569 base::RunLoop().Run();
1570
1571 // Check the interceptor got called as expected
1572 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1573 EXPECT_FALSE(interceptor.did_intercept_final_);
1574
1575 // Check we see a canceled request
1576 EXPECT_FALSE(req->status().is_success());
1577 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1578 }
1579
RunLoadTimingTest(const LoadTimingInfo & job_load_timing,URLRequestContext * context)1580 LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1581 URLRequestContext* context) {
1582 TestInterceptor interceptor;
1583 interceptor.intercept_main_request_ = true;
1584 interceptor.main_request_load_timing_info_ = job_load_timing;
1585 TestDelegate d;
1586 scoped_ptr<URLRequest> req(context->CreateRequest(
1587 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1588 req->Start();
1589 base::RunLoop().Run();
1590
1591 LoadTimingInfo resulting_load_timing;
1592 req->GetLoadTimingInfo(&resulting_load_timing);
1593
1594 // None of these should be modified by the URLRequest.
1595 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1596 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1597 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1598 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1599 EXPECT_EQ(job_load_timing.receive_headers_end,
1600 resulting_load_timing.receive_headers_end);
1601
1602 return resulting_load_timing;
1603 }
1604
1605 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1606 // reused. |connect_time_flags| is used to indicate if there should be dns
1607 // or SSL times, and |used_proxy| is used for proxy times.
NormalLoadTimingInfo(base::TimeTicks now,int connect_time_flags,bool used_proxy)1608 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1609 int connect_time_flags,
1610 bool used_proxy) {
1611 LoadTimingInfo load_timing;
1612 load_timing.socket_log_id = 1;
1613
1614 if (used_proxy) {
1615 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1616 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1617 }
1618
1619 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1620 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1621 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1622 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1623 }
1624 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1625 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1626 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1627 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1628 }
1629 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1630
1631 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1632 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1633 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1634 return load_timing;
1635 }
1636
1637 // Same as above, but in the case of a reused socket.
NormalLoadTimingInfoReused(base::TimeTicks now,bool used_proxy)1638 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1639 bool used_proxy) {
1640 LoadTimingInfo load_timing;
1641 load_timing.socket_log_id = 1;
1642 load_timing.socket_reused = true;
1643
1644 if (used_proxy) {
1645 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1646 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1647 }
1648
1649 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1650 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1651 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1652 return load_timing;
1653 }
1654
1655 // Basic test that the intercept + load timing tests work.
TEST_F(URLRequestTest,InterceptLoadTiming)1656 TEST_F(URLRequestTest, InterceptLoadTiming) {
1657 base::TimeTicks now = base::TimeTicks::Now();
1658 LoadTimingInfo job_load_timing =
1659 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1660
1661 LoadTimingInfo load_timing_result =
1662 RunLoadTimingTest(job_load_timing, &default_context_);
1663
1664 // Nothing should have been changed by the URLRequest.
1665 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1666 load_timing_result.proxy_resolve_start);
1667 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1668 load_timing_result.proxy_resolve_end);
1669 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1670 load_timing_result.connect_timing.dns_start);
1671 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1672 load_timing_result.connect_timing.dns_end);
1673 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1674 load_timing_result.connect_timing.connect_start);
1675 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1676 load_timing_result.connect_timing.connect_end);
1677 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1678 load_timing_result.connect_timing.ssl_start);
1679 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1680 load_timing_result.connect_timing.ssl_end);
1681
1682 // Redundant sanity check.
1683 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1684 }
1685
1686 // Another basic test, with proxy and SSL times, but no DNS times.
TEST_F(URLRequestTest,InterceptLoadTimingProxy)1687 TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1688 base::TimeTicks now = base::TimeTicks::Now();
1689 LoadTimingInfo job_load_timing =
1690 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1691
1692 LoadTimingInfo load_timing_result =
1693 RunLoadTimingTest(job_load_timing, &default_context_);
1694
1695 // Nothing should have been changed by the URLRequest.
1696 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1697 load_timing_result.proxy_resolve_start);
1698 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1699 load_timing_result.proxy_resolve_end);
1700 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1701 load_timing_result.connect_timing.dns_start);
1702 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1703 load_timing_result.connect_timing.dns_end);
1704 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1705 load_timing_result.connect_timing.connect_start);
1706 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1707 load_timing_result.connect_timing.connect_end);
1708 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1709 load_timing_result.connect_timing.ssl_start);
1710 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1711 load_timing_result.connect_timing.ssl_end);
1712
1713 // Redundant sanity check.
1714 TestLoadTimingNotReusedWithProxy(load_timing_result,
1715 CONNECT_TIMING_HAS_SSL_TIMES);
1716 }
1717
1718 // Make sure that URLRequest correctly adjusts proxy times when they're before
1719 // |request_start|, due to already having a connected socket. This happens in
1720 // the case of reusing a SPDY session. The connected socket is not considered
1721 // reused in this test (May be a preconnect).
1722 //
1723 // To mix things up from the test above, assumes DNS times but no SSL times.
TEST_F(URLRequestTest,InterceptLoadTimingEarlyProxyResolution)1724 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1725 base::TimeTicks now = base::TimeTicks::Now();
1726 LoadTimingInfo job_load_timing =
1727 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1728 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1729 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1730 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1731 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1732 job_load_timing.connect_timing.connect_start =
1733 now - base::TimeDelta::FromDays(2);
1734 job_load_timing.connect_timing.connect_end =
1735 now - base::TimeDelta::FromDays(1);
1736
1737 LoadTimingInfo load_timing_result =
1738 RunLoadTimingTest(job_load_timing, &default_context_);
1739
1740 // Proxy times, connect times, and DNS times should all be replaced with
1741 // request_start.
1742 EXPECT_EQ(load_timing_result.request_start,
1743 load_timing_result.proxy_resolve_start);
1744 EXPECT_EQ(load_timing_result.request_start,
1745 load_timing_result.proxy_resolve_end);
1746 EXPECT_EQ(load_timing_result.request_start,
1747 load_timing_result.connect_timing.dns_start);
1748 EXPECT_EQ(load_timing_result.request_start,
1749 load_timing_result.connect_timing.dns_end);
1750 EXPECT_EQ(load_timing_result.request_start,
1751 load_timing_result.connect_timing.connect_start);
1752 EXPECT_EQ(load_timing_result.request_start,
1753 load_timing_result.connect_timing.connect_end);
1754
1755 // Other times should have been left null.
1756 TestLoadTimingNotReusedWithProxy(load_timing_result,
1757 CONNECT_TIMING_HAS_DNS_TIMES);
1758 }
1759
1760 // Same as above, but in the reused case.
TEST_F(URLRequestTest,InterceptLoadTimingEarlyProxyResolutionReused)1761 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1762 base::TimeTicks now = base::TimeTicks::Now();
1763 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1764 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1765 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1766
1767 LoadTimingInfo load_timing_result =
1768 RunLoadTimingTest(job_load_timing, &default_context_);
1769
1770 // Proxy times and connect times should all be replaced with request_start.
1771 EXPECT_EQ(load_timing_result.request_start,
1772 load_timing_result.proxy_resolve_start);
1773 EXPECT_EQ(load_timing_result.request_start,
1774 load_timing_result.proxy_resolve_end);
1775
1776 // Other times should have been left null.
1777 TestLoadTimingReusedWithProxy(load_timing_result);
1778 }
1779
1780 // Make sure that URLRequest correctly adjusts connect times when they're before
1781 // |request_start|, due to reusing a connected socket. The connected socket is
1782 // not considered reused in this test (May be a preconnect).
1783 //
1784 // To mix things up, the request has SSL times, but no DNS times.
TEST_F(URLRequestTest,InterceptLoadTimingEarlyConnect)1785 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1786 base::TimeTicks now = base::TimeTicks::Now();
1787 LoadTimingInfo job_load_timing =
1788 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1789 job_load_timing.connect_timing.connect_start =
1790 now - base::TimeDelta::FromDays(1);
1791 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1792 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1793 job_load_timing.connect_timing.connect_end =
1794 now - base::TimeDelta::FromDays(4);
1795
1796 LoadTimingInfo load_timing_result =
1797 RunLoadTimingTest(job_load_timing, &default_context_);
1798
1799 // Connect times, and SSL times should be replaced with request_start.
1800 EXPECT_EQ(load_timing_result.request_start,
1801 load_timing_result.connect_timing.connect_start);
1802 EXPECT_EQ(load_timing_result.request_start,
1803 load_timing_result.connect_timing.ssl_start);
1804 EXPECT_EQ(load_timing_result.request_start,
1805 load_timing_result.connect_timing.ssl_end);
1806 EXPECT_EQ(load_timing_result.request_start,
1807 load_timing_result.connect_timing.connect_end);
1808
1809 // Other times should have been left null.
1810 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1811 }
1812
1813 // Make sure that URLRequest correctly adjusts connect times when they're before
1814 // |request_start|, due to reusing a connected socket in the case that there
1815 // are also proxy times. The connected socket is not considered reused in this
1816 // test (May be a preconnect).
1817 //
1818 // In this test, there are no SSL or DNS times.
TEST_F(URLRequestTest,InterceptLoadTimingEarlyConnectWithProxy)1819 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1820 base::TimeTicks now = base::TimeTicks::Now();
1821 LoadTimingInfo job_load_timing =
1822 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1823 job_load_timing.connect_timing.connect_start =
1824 now - base::TimeDelta::FromDays(1);
1825 job_load_timing.connect_timing.connect_end =
1826 now - base::TimeDelta::FromDays(2);
1827
1828 LoadTimingInfo load_timing_result =
1829 RunLoadTimingTest(job_load_timing, &default_context_);
1830
1831 // Connect times should be replaced with proxy_resolve_end.
1832 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1833 load_timing_result.connect_timing.connect_start);
1834 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1835 load_timing_result.connect_timing.connect_end);
1836
1837 // Other times should have been left null.
1838 TestLoadTimingNotReusedWithProxy(load_timing_result,
1839 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1840 }
1841
1842 // Check that two different URL requests have different identifiers.
TEST_F(URLRequestTest,Identifiers)1843 TEST_F(URLRequestTest, Identifiers) {
1844 TestDelegate d;
1845 TestURLRequestContext context;
1846 scoped_ptr<URLRequest> req(context.CreateRequest(
1847 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1848 scoped_ptr<URLRequest> other_req(context.CreateRequest(
1849 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1850
1851 ASSERT_NE(req->identifier(), other_req->identifier());
1852 }
1853
1854 // Check that a failure to connect to the proxy is reported to the network
1855 // delegate.
TEST_F(URLRequestTest,NetworkDelegateProxyError)1856 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1857 MockHostResolver host_resolver;
1858 host_resolver.rules()->AddSimulatedFailure("*");
1859
1860 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
1861 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1862
1863 TestDelegate d;
1864 scoped_ptr<URLRequest> req(context.CreateRequest(
1865 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1866 req->set_method("GET");
1867
1868 req->Start();
1869 base::RunLoop().Run();
1870
1871 // Check we see a failed request.
1872 EXPECT_FALSE(req->status().is_success());
1873 // The proxy server is not set before failure.
1874 EXPECT_TRUE(req->proxy_server().IsEmpty());
1875 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
1876 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
1877
1878 EXPECT_EQ(1, network_delegate.error_count());
1879 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1880 EXPECT_EQ(1, network_delegate.completed_requests());
1881 }
1882
1883 // Make sure that NetworkDelegate::NotifyCompleted is called if
1884 // content is empty.
TEST_F(URLRequestTest,RequestCompletionForEmptyResponse)1885 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1886 TestDelegate d;
1887 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1888 GURL("data:,"), DEFAULT_PRIORITY, &d, NULL));
1889 req->Start();
1890 base::RunLoop().Run();
1891 EXPECT_EQ("", d.data_received());
1892 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1893 }
1894
1895 // Make sure that SetPriority actually sets the URLRequest's priority
1896 // correctly, both before and after start.
TEST_F(URLRequestTest,SetPriorityBasic)1897 TEST_F(URLRequestTest, SetPriorityBasic) {
1898 TestDelegate d;
1899 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1900 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1901 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
1902
1903 req->SetPriority(LOW);
1904 EXPECT_EQ(LOW, req->priority());
1905
1906 req->Start();
1907 EXPECT_EQ(LOW, req->priority());
1908
1909 req->SetPriority(MEDIUM);
1910 EXPECT_EQ(MEDIUM, req->priority());
1911 }
1912
1913 // Make sure that URLRequest calls SetPriority on a job before calling
1914 // Start on it.
TEST_F(URLRequestTest,SetJobPriorityBeforeJobStart)1915 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1916 TestDelegate d;
1917 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1918 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1919 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
1920
1921 scoped_refptr<URLRequestTestJob> job =
1922 new URLRequestTestJob(req.get(), &default_network_delegate_);
1923 AddTestInterceptor()->set_main_intercept_job(job.get());
1924 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1925
1926 req->SetPriority(LOW);
1927
1928 req->Start();
1929 EXPECT_EQ(LOW, job->priority());
1930 }
1931
1932 // Make sure that URLRequest passes on its priority updates to its
1933 // job.
TEST_F(URLRequestTest,SetJobPriority)1934 TEST_F(URLRequestTest, SetJobPriority) {
1935 TestDelegate d;
1936 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1937 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1938
1939 scoped_refptr<URLRequestTestJob> job =
1940 new URLRequestTestJob(req.get(), &default_network_delegate_);
1941 AddTestInterceptor()->set_main_intercept_job(job.get());
1942
1943 req->SetPriority(LOW);
1944 req->Start();
1945 EXPECT_EQ(LOW, job->priority());
1946
1947 req->SetPriority(MEDIUM);
1948 EXPECT_EQ(MEDIUM, req->priority());
1949 EXPECT_EQ(MEDIUM, job->priority());
1950 }
1951
1952 // Setting the IGNORE_LIMITS load flag should be okay if the priority
1953 // is MAXIMUM_PRIORITY.
TEST_F(URLRequestTest,PriorityIgnoreLimits)1954 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1955 TestDelegate d;
1956 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1957 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d, NULL));
1958 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1959
1960 scoped_refptr<URLRequestTestJob> job =
1961 new URLRequestTestJob(req.get(), &default_network_delegate_);
1962 AddTestInterceptor()->set_main_intercept_job(job.get());
1963
1964 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
1965 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1966
1967 req->SetPriority(MAXIMUM_PRIORITY);
1968 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1969
1970 req->Start();
1971 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1972 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1973 }
1974
1975 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1976 #if !defined(OS_IOS)
1977 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
1978 // This is to work around mysterious failures in chrome_frame_net_tests. See:
1979 // http://crbug.com/114369
1980 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1981 class LocalHttpTestServer : public SpawnedTestServer {
1982 public:
LocalHttpTestServer(const base::FilePath & document_root)1983 explicit LocalHttpTestServer(const base::FilePath& document_root)
1984 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1985 ScopedCustomUrlRequestTestHttpHost::value(),
1986 document_root) {}
LocalHttpTestServer()1987 LocalHttpTestServer()
1988 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1989 ScopedCustomUrlRequestTestHttpHost::value(),
1990 base::FilePath()) {}
1991 };
1992
TEST_F(URLRequestTest,DelayedCookieCallback)1993 TEST_F(URLRequestTest, DelayedCookieCallback) {
1994 LocalHttpTestServer test_server;
1995 ASSERT_TRUE(test_server.Start());
1996
1997 TestURLRequestContext context;
1998 scoped_refptr<DelayedCookieMonster> delayed_cm =
1999 new DelayedCookieMonster();
2000 scoped_refptr<CookieStore> cookie_store = delayed_cm;
2001 context.set_cookie_store(delayed_cm.get());
2002
2003 // Set up a cookie.
2004 {
2005 TestNetworkDelegate network_delegate;
2006 context.set_network_delegate(&network_delegate);
2007 TestDelegate d;
2008 scoped_ptr<URLRequest> req(context.CreateRequest(
2009 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2010 &d, NULL));
2011 req->Start();
2012 base::RunLoop().Run();
2013 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2014 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2015 EXPECT_EQ(1, network_delegate.set_cookie_count());
2016 }
2017
2018 // Verify that the cookie is set.
2019 {
2020 TestNetworkDelegate network_delegate;
2021 context.set_network_delegate(&network_delegate);
2022 TestDelegate d;
2023 scoped_ptr<URLRequest> req(context.CreateRequest(
2024 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2025 req->Start();
2026 base::RunLoop().Run();
2027
2028 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2029 != std::string::npos);
2030 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2031 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2032 }
2033 }
2034
TEST_F(URLRequestTest,DoNotSendCookies)2035 TEST_F(URLRequestTest, DoNotSendCookies) {
2036 LocalHttpTestServer test_server;
2037 ASSERT_TRUE(test_server.Start());
2038
2039 // Set up a cookie.
2040 {
2041 TestNetworkDelegate network_delegate;
2042 default_context_.set_network_delegate(&network_delegate);
2043 TestDelegate d;
2044 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2045 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2046 &d, NULL));
2047 req->Start();
2048 base::RunLoop().Run();
2049 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2050 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2051 }
2052
2053 // Verify that the cookie is set.
2054 {
2055 TestNetworkDelegate network_delegate;
2056 default_context_.set_network_delegate(&network_delegate);
2057 TestDelegate d;
2058 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2059 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2060 req->Start();
2061 base::RunLoop().Run();
2062
2063 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2064 != std::string::npos);
2065 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2066 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2067 }
2068
2069 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2070 {
2071 TestNetworkDelegate network_delegate;
2072 default_context_.set_network_delegate(&network_delegate);
2073 TestDelegate d;
2074 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2075 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2076 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2077 req->Start();
2078 base::RunLoop().Run();
2079
2080 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2081 == std::string::npos);
2082
2083 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2084 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2085 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2086 }
2087 }
2088
TEST_F(URLRequestTest,DoNotSaveCookies)2089 TEST_F(URLRequestTest, DoNotSaveCookies) {
2090 LocalHttpTestServer test_server;
2091 ASSERT_TRUE(test_server.Start());
2092
2093 // Set up a cookie.
2094 {
2095 TestNetworkDelegate network_delegate;
2096 default_context_.set_network_delegate(&network_delegate);
2097 TestDelegate d;
2098 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2099 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2100 &d, NULL));
2101 req->Start();
2102 base::RunLoop().Run();
2103
2104 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2105 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2106 EXPECT_EQ(1, network_delegate.set_cookie_count());
2107 }
2108
2109 // Try to set-up another cookie and update the previous cookie.
2110 {
2111 TestNetworkDelegate network_delegate;
2112 default_context_.set_network_delegate(&network_delegate);
2113 TestDelegate d;
2114 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2115 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2116 DEFAULT_PRIORITY, &d, NULL));
2117 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2118 req->Start();
2119
2120 base::RunLoop().Run();
2121
2122 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2123 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2124 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2125 EXPECT_EQ(0, network_delegate.set_cookie_count());
2126 }
2127
2128 // Verify the cookies weren't saved or updated.
2129 {
2130 TestNetworkDelegate network_delegate;
2131 default_context_.set_network_delegate(&network_delegate);
2132 TestDelegate d;
2133 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2134 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2135 req->Start();
2136 base::RunLoop().Run();
2137
2138 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2139 == std::string::npos);
2140 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2141 != std::string::npos);
2142
2143 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2144 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2145 EXPECT_EQ(0, network_delegate.set_cookie_count());
2146 }
2147 }
2148
TEST_F(URLRequestTest,DoNotSendCookies_ViaPolicy)2149 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2150 LocalHttpTestServer test_server;
2151 ASSERT_TRUE(test_server.Start());
2152
2153 // Set up a cookie.
2154 {
2155 TestNetworkDelegate network_delegate;
2156 default_context_.set_network_delegate(&network_delegate);
2157 TestDelegate d;
2158 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2159 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2160 &d, NULL));
2161 req->Start();
2162 base::RunLoop().Run();
2163
2164 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2165 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2166 }
2167
2168 // Verify that the cookie is set.
2169 {
2170 TestNetworkDelegate network_delegate;
2171 default_context_.set_network_delegate(&network_delegate);
2172 TestDelegate d;
2173 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2174 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2175 req->Start();
2176 base::RunLoop().Run();
2177
2178 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2179 != std::string::npos);
2180
2181 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2182 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2183 }
2184
2185 // Verify that the cookie isn't sent.
2186 {
2187 TestNetworkDelegate network_delegate;
2188 default_context_.set_network_delegate(&network_delegate);
2189 TestDelegate d;
2190 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2191 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2192 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2193 req->Start();
2194 base::RunLoop().Run();
2195
2196 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2197 == std::string::npos);
2198
2199 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2200 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2201 }
2202 }
2203
TEST_F(URLRequestTest,DoNotSaveCookies_ViaPolicy)2204 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2205 LocalHttpTestServer test_server;
2206 ASSERT_TRUE(test_server.Start());
2207
2208 // Set up a cookie.
2209 {
2210 TestNetworkDelegate network_delegate;
2211 default_context_.set_network_delegate(&network_delegate);
2212 TestDelegate d;
2213 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2214 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2215 &d, NULL));
2216 req->Start();
2217 base::RunLoop().Run();
2218
2219 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2220 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2221 }
2222
2223 // Try to set-up another cookie and update the previous cookie.
2224 {
2225 TestNetworkDelegate network_delegate;
2226 default_context_.set_network_delegate(&network_delegate);
2227 TestDelegate d;
2228 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2229 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2230 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2231 DEFAULT_PRIORITY, &d, NULL));
2232 req->Start();
2233
2234 base::RunLoop().Run();
2235
2236 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2237 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2238 }
2239
2240 // Verify the cookies weren't saved or updated.
2241 {
2242 TestNetworkDelegate network_delegate;
2243 default_context_.set_network_delegate(&network_delegate);
2244 TestDelegate d;
2245 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2246 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2247 req->Start();
2248 base::RunLoop().Run();
2249
2250 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2251 == std::string::npos);
2252 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2253 != std::string::npos);
2254
2255 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2256 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2257 }
2258 }
2259
TEST_F(URLRequestTest,DoNotSaveEmptyCookies)2260 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2261 LocalHttpTestServer test_server;
2262 ASSERT_TRUE(test_server.Start());
2263
2264 // Set up an empty cookie.
2265 {
2266 TestNetworkDelegate network_delegate;
2267 default_context_.set_network_delegate(&network_delegate);
2268 TestDelegate d;
2269 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2270 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d, NULL));
2271 req->Start();
2272 base::RunLoop().Run();
2273
2274 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2275 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2276 EXPECT_EQ(0, network_delegate.set_cookie_count());
2277 }
2278 }
2279
TEST_F(URLRequestTest,DoNotSendCookies_ViaPolicy_Async)2280 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2281 LocalHttpTestServer test_server;
2282 ASSERT_TRUE(test_server.Start());
2283
2284 // Set up a cookie.
2285 {
2286 TestNetworkDelegate network_delegate;
2287 default_context_.set_network_delegate(&network_delegate);
2288 TestDelegate d;
2289 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2290 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2291 &d, NULL));
2292 req->Start();
2293 base::RunLoop().Run();
2294
2295 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2296 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2297 }
2298
2299 // Verify that the cookie is set.
2300 {
2301 TestNetworkDelegate network_delegate;
2302 default_context_.set_network_delegate(&network_delegate);
2303 TestDelegate d;
2304 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2305 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2306 req->Start();
2307 base::RunLoop().Run();
2308
2309 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2310 != std::string::npos);
2311
2312 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2313 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2314 }
2315
2316 // Verify that the cookie isn't sent.
2317 {
2318 TestNetworkDelegate network_delegate;
2319 default_context_.set_network_delegate(&network_delegate);
2320 TestDelegate d;
2321 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2322 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2323 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2324 req->Start();
2325 base::RunLoop().Run();
2326
2327 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2328 == std::string::npos);
2329
2330 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2331 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2332 }
2333 }
2334
TEST_F(URLRequestTest,DoNotSaveCookies_ViaPolicy_Async)2335 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2336 LocalHttpTestServer test_server;
2337 ASSERT_TRUE(test_server.Start());
2338
2339 // Set up a cookie.
2340 {
2341 TestNetworkDelegate network_delegate;
2342 default_context_.set_network_delegate(&network_delegate);
2343 TestDelegate d;
2344 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2345 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2346 &d, NULL));
2347 req->Start();
2348 base::RunLoop().Run();
2349
2350 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2351 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2352 }
2353
2354 // Try to set-up another cookie and update the previous cookie.
2355 {
2356 TestNetworkDelegate network_delegate;
2357 default_context_.set_network_delegate(&network_delegate);
2358 TestDelegate d;
2359 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2360 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2361 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2362 DEFAULT_PRIORITY, &d, NULL));
2363 req->Start();
2364
2365 base::RunLoop().Run();
2366
2367 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2368 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2369 }
2370
2371 // Verify the cookies weren't saved or updated.
2372 {
2373 TestNetworkDelegate network_delegate;
2374 default_context_.set_network_delegate(&network_delegate);
2375 TestDelegate d;
2376 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2377 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2378 req->Start();
2379 base::RunLoop().Run();
2380
2381 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2382 == std::string::npos);
2383 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2384 != std::string::npos);
2385
2386 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2387 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2388 }
2389 }
2390
2391 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2392 // value for the |fixed_date| argument given to the constructor.
2393 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2394 public:
FixedDateNetworkDelegate(const std::string & fixed_date)2395 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2396 : fixed_date_(fixed_date) {}
~FixedDateNetworkDelegate()2397 virtual ~FixedDateNetworkDelegate() {}
2398
2399 // NetworkDelegate implementation
2400 virtual int OnHeadersReceived(
2401 URLRequest* request,
2402 const CompletionCallback& callback,
2403 const HttpResponseHeaders* original_response_headers,
2404 scoped_refptr<HttpResponseHeaders>* override_response_headers,
2405 GURL* allowed_unsafe_redirect_url) OVERRIDE;
2406
2407 private:
2408 std::string fixed_date_;
2409
2410 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2411 };
2412
OnHeadersReceived(URLRequest * request,const CompletionCallback & callback,const HttpResponseHeaders * original_response_headers,scoped_refptr<HttpResponseHeaders> * override_response_headers,GURL * allowed_unsafe_redirect_url)2413 int FixedDateNetworkDelegate::OnHeadersReceived(
2414 URLRequest* request,
2415 const CompletionCallback& callback,
2416 const HttpResponseHeaders* original_response_headers,
2417 scoped_refptr<HttpResponseHeaders>* override_response_headers,
2418 GURL* allowed_unsafe_redirect_url) {
2419 HttpResponseHeaders* new_response_headers =
2420 new HttpResponseHeaders(original_response_headers->raw_headers());
2421
2422 new_response_headers->RemoveHeader("Date");
2423 new_response_headers->AddHeader("Date: " + fixed_date_);
2424
2425 *override_response_headers = new_response_headers;
2426 return TestNetworkDelegate::OnHeadersReceived(request,
2427 callback,
2428 original_response_headers,
2429 override_response_headers,
2430 allowed_unsafe_redirect_url);
2431 }
2432
2433 // Test that cookie expiration times are adjusted for server/client clock
2434 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2435 // headers by defaulting to GMT. (crbug.com/135131)
TEST_F(URLRequestTest,AcceptClockSkewCookieWithWrongDateTimezone)2436 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2437 LocalHttpTestServer test_server;
2438 ASSERT_TRUE(test_server.Start());
2439
2440 // Set up an expired cookie.
2441 {
2442 TestNetworkDelegate network_delegate;
2443 default_context_.set_network_delegate(&network_delegate);
2444 TestDelegate d;
2445 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2446 test_server.GetURL(
2447 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2448 DEFAULT_PRIORITY, &d, NULL));
2449 req->Start();
2450 base::RunLoop().Run();
2451 }
2452 // Verify that the cookie is not set.
2453 {
2454 TestNetworkDelegate network_delegate;
2455 default_context_.set_network_delegate(&network_delegate);
2456 TestDelegate d;
2457 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2458 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2459 req->Start();
2460 base::RunLoop().Run();
2461
2462 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2463 }
2464 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2465 {
2466 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2467 default_context_.set_network_delegate(&network_delegate);
2468 TestDelegate d;
2469 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2470 test_server.GetURL(
2471 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2472 DEFAULT_PRIORITY, &d, NULL));
2473 req->Start();
2474 base::RunLoop().Run();
2475 }
2476 // Verify that the cookie is set.
2477 {
2478 TestNetworkDelegate network_delegate;
2479 default_context_.set_network_delegate(&network_delegate);
2480 TestDelegate d;
2481 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2482 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2483 req->Start();
2484 base::RunLoop().Run();
2485
2486 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2487 }
2488 }
2489
2490
2491 // Check that it is impossible to change the referrer in the extra headers of
2492 // an URLRequest.
TEST_F(URLRequestTest,DoNotOverrideReferrer)2493 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2494 LocalHttpTestServer test_server;
2495 ASSERT_TRUE(test_server.Start());
2496
2497 // If extra headers contain referer and the request contains a referer,
2498 // only the latter shall be respected.
2499 {
2500 TestDelegate d;
2501 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2502 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
2503 req->SetReferrer("http://foo.com/");
2504
2505 HttpRequestHeaders headers;
2506 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2507 req->SetExtraRequestHeaders(headers);
2508
2509 req->Start();
2510 base::RunLoop().Run();
2511
2512 EXPECT_EQ("http://foo.com/", d.data_received());
2513 }
2514
2515 // If extra headers contain a referer but the request does not, no referer
2516 // shall be sent in the header.
2517 {
2518 TestDelegate d;
2519 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2520 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
2521
2522 HttpRequestHeaders headers;
2523 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2524 req->SetExtraRequestHeaders(headers);
2525 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
2526
2527 req->Start();
2528 base::RunLoop().Run();
2529
2530 EXPECT_EQ("None", d.data_received());
2531 }
2532 }
2533
2534 class URLRequestTestHTTP : public URLRequestTest {
2535 public:
URLRequestTestHTTP()2536 URLRequestTestHTTP()
2537 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2538 "net/data/url_request_unittest"))) {
2539 }
2540
2541 protected:
2542 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2543 // |request_method| is the method to use for the initial request.
2544 // |redirect_method| is the method that is expected to be used for the second
2545 // request, after redirection.
2546 // If |include_data| is true, data is uploaded with the request. The
2547 // response body is expected to match it exactly, if and only if
2548 // |request_method| == |redirect_method|.
HTTPRedirectMethodTest(const GURL & redirect_url,const std::string & request_method,const std::string & redirect_method,bool include_data)2549 void HTTPRedirectMethodTest(const GURL& redirect_url,
2550 const std::string& request_method,
2551 const std::string& redirect_method,
2552 bool include_data) {
2553 static const char kData[] = "hello world";
2554 TestDelegate d;
2555 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2556 redirect_url, DEFAULT_PRIORITY, &d, NULL));
2557 req->set_method(request_method);
2558 if (include_data) {
2559 req->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2560 HttpRequestHeaders headers;
2561 headers.SetHeader(HttpRequestHeaders::kContentLength,
2562 base::UintToString(arraysize(kData) - 1));
2563 req->SetExtraRequestHeaders(headers);
2564 }
2565 req->Start();
2566 base::RunLoop().Run();
2567 EXPECT_EQ(redirect_method, req->method());
2568 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2569 EXPECT_EQ(OK, req->status().error());
2570 if (include_data) {
2571 if (request_method == redirect_method) {
2572 EXPECT_EQ(kData, d.data_received());
2573 } else {
2574 EXPECT_NE(kData, d.data_received());
2575 }
2576 }
2577 if (HasFailure())
2578 LOG(WARNING) << "Request method was: " << request_method;
2579 }
2580
HTTPUploadDataOperationTest(const std::string & method)2581 void HTTPUploadDataOperationTest(const std::string& method) {
2582 const int kMsgSize = 20000; // multiple of 10
2583 const int kIterations = 50;
2584 char* uploadBytes = new char[kMsgSize+1];
2585 char* ptr = uploadBytes;
2586 char marker = 'a';
2587 for (int idx = 0; idx < kMsgSize/10; idx++) {
2588 memcpy(ptr, "----------", 10);
2589 ptr += 10;
2590 if (idx % 100 == 0) {
2591 ptr--;
2592 *ptr++ = marker;
2593 if (++marker > 'z')
2594 marker = 'a';
2595 }
2596 }
2597 uploadBytes[kMsgSize] = '\0';
2598
2599 for (int i = 0; i < kIterations; ++i) {
2600 TestDelegate d;
2601 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2602 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
2603 r->set_method(method.c_str());
2604
2605 r->set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
2606
2607 r->Start();
2608 EXPECT_TRUE(r->is_pending());
2609
2610 base::RunLoop().Run();
2611
2612 ASSERT_EQ(1, d.response_started_count())
2613 << "request failed: " << r->status().status()
2614 << ", os error: " << r->status().error();
2615
2616 EXPECT_FALSE(d.received_data_before_response());
2617 EXPECT_EQ(uploadBytes, d.data_received());
2618 }
2619 delete[] uploadBytes;
2620 }
2621
AddChunksToUpload(URLRequest * r)2622 void AddChunksToUpload(URLRequest* r) {
2623 r->AppendChunkToUpload("a", 1, false);
2624 r->AppendChunkToUpload("bcd", 3, false);
2625 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2626 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2627 r->AppendChunkToUpload("0", 1, false);
2628 r->AppendChunkToUpload("2323", 4, true);
2629 }
2630
VerifyReceivedDataMatchesChunks(URLRequest * r,TestDelegate * d)2631 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2632 // This should match the chunks sent by AddChunksToUpload().
2633 const std::string expected_data =
2634 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2635
2636 ASSERT_EQ(1, d->response_started_count())
2637 << "request failed: " << r->status().status()
2638 << ", os error: " << r->status().error();
2639
2640 EXPECT_FALSE(d->received_data_before_response());
2641
2642 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2643 EXPECT_EQ(expected_data, d->data_received());
2644 }
2645
DoManyCookiesRequest(int num_cookies)2646 bool DoManyCookiesRequest(int num_cookies) {
2647 TestDelegate d;
2648 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2649 test_server_.GetURL("set-many-cookies?" +
2650 base::IntToString(num_cookies)),
2651 DEFAULT_PRIORITY, &d, NULL));
2652
2653 r->Start();
2654 EXPECT_TRUE(r->is_pending());
2655
2656 base::RunLoop().Run();
2657
2658 bool is_success = r->status().is_success();
2659
2660 if (!is_success) {
2661 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2662 // The test server appears to be unable to handle subsequent requests
2663 // after this error is triggered. Force it to restart.
2664 EXPECT_TRUE(test_server_.Stop());
2665 EXPECT_TRUE(test_server_.Start());
2666 }
2667
2668 return is_success;
2669 }
2670
2671 LocalHttpTestServer test_server_;
2672 };
2673
2674 // In this unit test, we're using the HTTPTestServer as a proxy server and
2675 // issuing a CONNECT request with the magic host name "www.redirect.com".
2676 // The HTTPTestServer will return a 302 response, which we should not
2677 // follow.
TEST_F(URLRequestTestHTTP,ProxyTunnelRedirectTest)2678 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2679 ASSERT_TRUE(test_server_.Start());
2680
2681 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2682 TestURLRequestContextWithProxy context(
2683 test_server_.host_port_pair().ToString(), &network_delegate);
2684
2685 TestDelegate d;
2686 {
2687 scoped_ptr<URLRequest> r(context.CreateRequest(
2688 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2689 r->Start();
2690 EXPECT_TRUE(r->is_pending());
2691
2692 base::RunLoop().Run();
2693
2694 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2695 // The proxy server is not set before failure.
2696 EXPECT_TRUE(r->proxy_server().IsEmpty());
2697 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
2698 EXPECT_EQ(1, d.response_started_count());
2699 // We should not have followed the redirect.
2700 EXPECT_EQ(0, d.received_redirect_count());
2701 }
2702 }
2703
2704 // This is the same as the previous test, but checks that the network delegate
2705 // registers the error.
TEST_F(URLRequestTestHTTP,NetworkDelegateTunnelConnectionFailed)2706 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
2707 ASSERT_TRUE(test_server_.Start());
2708
2709 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2710 TestURLRequestContextWithProxy context(
2711 test_server_.host_port_pair().ToString(), &network_delegate);
2712
2713 TestDelegate d;
2714 {
2715 scoped_ptr<URLRequest> r(context.CreateRequest(
2716 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2717 r->Start();
2718 EXPECT_TRUE(r->is_pending());
2719
2720 base::RunLoop().Run();
2721
2722 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2723 // The proxy server is not set before failure.
2724 EXPECT_TRUE(r->proxy_server().IsEmpty());
2725 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
2726 EXPECT_EQ(1, d.response_started_count());
2727 // We should not have followed the redirect.
2728 EXPECT_EQ(0, d.received_redirect_count());
2729
2730 EXPECT_EQ(1, network_delegate.error_count());
2731 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
2732 }
2733 }
2734
2735 // Tests that we can block and asynchronously return OK in various stages.
TEST_F(URLRequestTestHTTP,NetworkDelegateBlockAsynchronously)2736 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2737 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2738 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2739 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2740 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2741 };
2742 static const size_t blocking_stages_length = arraysize(blocking_stages);
2743
2744 ASSERT_TRUE(test_server_.Start());
2745
2746 TestDelegate d;
2747 BlockingNetworkDelegate network_delegate(
2748 BlockingNetworkDelegate::USER_CALLBACK);
2749 network_delegate.set_block_on(
2750 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2751 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2752 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2753
2754 TestURLRequestContext context(true);
2755 context.set_network_delegate(&network_delegate);
2756 context.Init();
2757
2758 {
2759 scoped_ptr<URLRequest> r(context.CreateRequest(
2760 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
2761
2762 r->Start();
2763 for (size_t i = 0; i < blocking_stages_length; ++i) {
2764 base::RunLoop().Run();
2765 EXPECT_EQ(blocking_stages[i],
2766 network_delegate.stage_blocked_for_callback());
2767 network_delegate.DoCallback(OK);
2768 }
2769 base::RunLoop().Run();
2770 EXPECT_EQ(200, r->GetResponseCode());
2771 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2772 EXPECT_EQ(1, network_delegate.created_requests());
2773 EXPECT_EQ(0, network_delegate.destroyed_requests());
2774 }
2775 EXPECT_EQ(1, network_delegate.destroyed_requests());
2776 }
2777
2778 // Tests that the network delegate can block and cancel a request.
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelRequest)2779 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2780 ASSERT_TRUE(test_server_.Start());
2781
2782 TestDelegate d;
2783 BlockingNetworkDelegate network_delegate(
2784 BlockingNetworkDelegate::AUTO_CALLBACK);
2785 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2786 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
2787
2788 TestURLRequestContextWithProxy context(
2789 test_server_.host_port_pair().ToString(), &network_delegate);
2790
2791 {
2792 scoped_ptr<URLRequest> r(context.CreateRequest(
2793 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
2794
2795 r->Start();
2796 base::RunLoop().Run();
2797
2798 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2799 // The proxy server is not set before cancellation.
2800 EXPECT_TRUE(r->proxy_server().IsEmpty());
2801 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
2802 EXPECT_EQ(1, network_delegate.created_requests());
2803 EXPECT_EQ(0, network_delegate.destroyed_requests());
2804 }
2805 EXPECT_EQ(1, network_delegate.destroyed_requests());
2806 }
2807
2808 // Helper function for NetworkDelegateCancelRequestAsynchronously and
2809 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2810 // delegate operating in |block_mode| and a request for |url|. It blocks the
2811 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,BlockingNetworkDelegate::Stage stage,const GURL & url)2812 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2813 BlockingNetworkDelegate::Stage stage,
2814 const GURL& url) {
2815 TestDelegate d;
2816 BlockingNetworkDelegate network_delegate(block_mode);
2817 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2818 network_delegate.set_block_on(stage);
2819
2820 TestURLRequestContext context(true);
2821 context.set_network_delegate(&network_delegate);
2822 context.Init();
2823
2824 {
2825 scoped_ptr<URLRequest> r(context.CreateRequest(
2826 url, DEFAULT_PRIORITY, &d, NULL));
2827
2828 r->Start();
2829 base::RunLoop().Run();
2830
2831 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2832 // The proxy server is not set before cancellation.
2833 EXPECT_TRUE(r->proxy_server().IsEmpty());
2834 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
2835 EXPECT_EQ(1, network_delegate.created_requests());
2836 EXPECT_EQ(0, network_delegate.destroyed_requests());
2837 }
2838 EXPECT_EQ(1, network_delegate.destroyed_requests());
2839 }
2840
2841 // The following 3 tests check that the network delegate can cancel a request
2842 // synchronously in various stages of the request.
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelRequestSynchronously1)2843 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2844 ASSERT_TRUE(test_server_.Start());
2845 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2846 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2847 test_server_.GetURL(std::string()));
2848 }
2849
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelRequestSynchronously2)2850 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2851 ASSERT_TRUE(test_server_.Start());
2852 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2853 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2854 test_server_.GetURL(std::string()));
2855 }
2856
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelRequestSynchronously3)2857 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2858 ASSERT_TRUE(test_server_.Start());
2859 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2860 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2861 test_server_.GetURL(std::string()));
2862 }
2863
2864 // The following 3 tests check that the network delegate can cancel a request
2865 // asynchronously in various stages of the request.
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelRequestAsynchronously1)2866 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2867 ASSERT_TRUE(test_server_.Start());
2868 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2869 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2870 test_server_.GetURL(std::string()));
2871 }
2872
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelRequestAsynchronously2)2873 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2874 ASSERT_TRUE(test_server_.Start());
2875 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2876 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2877 test_server_.GetURL(std::string()));
2878 }
2879
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelRequestAsynchronously3)2880 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2881 ASSERT_TRUE(test_server_.Start());
2882 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2883 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2884 test_server_.GetURL(std::string()));
2885 }
2886
2887 // Tests that the network delegate can block and redirect a request to a new
2888 // URL.
TEST_F(URLRequestTestHTTP,NetworkDelegateRedirectRequest)2889 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2890 ASSERT_TRUE(test_server_.Start());
2891
2892 TestDelegate d;
2893 BlockingNetworkDelegate network_delegate(
2894 BlockingNetworkDelegate::AUTO_CALLBACK);
2895 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2896 GURL redirect_url(test_server_.GetURL("simple.html"));
2897 network_delegate.set_redirect_url(redirect_url);
2898
2899 TestURLRequestContextWithProxy context(
2900 test_server_.host_port_pair().ToString(), &network_delegate);
2901
2902 {
2903 GURL original_url(test_server_.GetURL("empty.html"));
2904 scoped_ptr<URLRequest> r(context.CreateRequest(
2905 original_url, DEFAULT_PRIORITY, &d, NULL));
2906
2907 // Quit after hitting the redirect, so can check the headers.
2908 d.set_quit_on_redirect(true);
2909 r->Start();
2910 base::RunLoop().Run();
2911
2912 // Check headers from URLRequestJob.
2913 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2914 EXPECT_EQ(307, r->GetResponseCode());
2915 EXPECT_EQ(307, r->response_headers()->response_code());
2916 std::string location;
2917 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
2918 &location));
2919 EXPECT_EQ(redirect_url, GURL(location));
2920
2921 // Let the request finish.
2922 r->FollowDeferredRedirect();
2923 base::RunLoop().Run();
2924 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2925 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
2926 EXPECT_EQ(
2927 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2928 EXPECT_TRUE(
2929 network_delegate.last_observed_proxy().Equals(
2930 test_server_.host_port_pair()));
2931
2932 EXPECT_EQ(0, r->status().error());
2933 EXPECT_EQ(redirect_url, r->url());
2934 EXPECT_EQ(original_url, r->original_url());
2935 EXPECT_EQ(2U, r->url_chain().size());
2936 EXPECT_EQ(1, network_delegate.created_requests());
2937 EXPECT_EQ(0, network_delegate.destroyed_requests());
2938 }
2939 EXPECT_EQ(1, network_delegate.destroyed_requests());
2940 }
2941
2942 // Tests that the network delegate can block and redirect a request to a new
2943 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
TEST_F(URLRequestTestHTTP,NetworkDelegateRedirectRequestSynchronously)2944 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2945 ASSERT_TRUE(test_server_.Start());
2946
2947 TestDelegate d;
2948 BlockingNetworkDelegate network_delegate(
2949 BlockingNetworkDelegate::SYNCHRONOUS);
2950 GURL redirect_url(test_server_.GetURL("simple.html"));
2951 network_delegate.set_redirect_url(redirect_url);
2952
2953 TestURLRequestContextWithProxy context(
2954 test_server_.host_port_pair().ToString(), &network_delegate);
2955
2956 {
2957 GURL original_url(test_server_.GetURL("empty.html"));
2958 scoped_ptr<URLRequest> r(context.CreateRequest(
2959 original_url, DEFAULT_PRIORITY, &d, NULL));
2960
2961 // Quit after hitting the redirect, so can check the headers.
2962 d.set_quit_on_redirect(true);
2963 r->Start();
2964 base::RunLoop().Run();
2965
2966 // Check headers from URLRequestJob.
2967 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2968 EXPECT_EQ(307, r->GetResponseCode());
2969 EXPECT_EQ(307, r->response_headers()->response_code());
2970 std::string location;
2971 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
2972 &location));
2973 EXPECT_EQ(redirect_url, GURL(location));
2974
2975 // Let the request finish.
2976 r->FollowDeferredRedirect();
2977 base::RunLoop().Run();
2978
2979 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2980 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
2981 EXPECT_EQ(
2982 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2983 EXPECT_TRUE(
2984 network_delegate.last_observed_proxy().Equals(
2985 test_server_.host_port_pair()));
2986 EXPECT_EQ(0, r->status().error());
2987 EXPECT_EQ(redirect_url, r->url());
2988 EXPECT_EQ(original_url, r->original_url());
2989 EXPECT_EQ(2U, r->url_chain().size());
2990 EXPECT_EQ(1, network_delegate.created_requests());
2991 EXPECT_EQ(0, network_delegate.destroyed_requests());
2992 }
2993 EXPECT_EQ(1, network_delegate.destroyed_requests());
2994 }
2995
2996 // Tests that redirects caused by the network delegate preserve POST data.
TEST_F(URLRequestTestHTTP,NetworkDelegateRedirectRequestPost)2997 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2998 ASSERT_TRUE(test_server_.Start());
2999
3000 const char kData[] = "hello world";
3001
3002 TestDelegate d;
3003 BlockingNetworkDelegate network_delegate(
3004 BlockingNetworkDelegate::AUTO_CALLBACK);
3005 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3006 GURL redirect_url(test_server_.GetURL("echo"));
3007 network_delegate.set_redirect_url(redirect_url);
3008
3009 TestURLRequestContext context(true);
3010 context.set_network_delegate(&network_delegate);
3011 context.Init();
3012
3013 {
3014 GURL original_url(test_server_.GetURL("empty.html"));
3015 scoped_ptr<URLRequest> r(context.CreateRequest(
3016 original_url, DEFAULT_PRIORITY, &d, NULL));
3017 r->set_method("POST");
3018 r->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
3019 HttpRequestHeaders headers;
3020 headers.SetHeader(HttpRequestHeaders::kContentLength,
3021 base::UintToString(arraysize(kData) - 1));
3022 r->SetExtraRequestHeaders(headers);
3023
3024 // Quit after hitting the redirect, so can check the headers.
3025 d.set_quit_on_redirect(true);
3026 r->Start();
3027 base::RunLoop().Run();
3028
3029 // Check headers from URLRequestJob.
3030 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3031 EXPECT_EQ(307, r->GetResponseCode());
3032 EXPECT_EQ(307, r->response_headers()->response_code());
3033 std::string location;
3034 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3035 &location));
3036 EXPECT_EQ(redirect_url, GURL(location));
3037
3038 // Let the request finish.
3039 r->FollowDeferredRedirect();
3040 base::RunLoop().Run();
3041
3042 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3043 EXPECT_EQ(0, r->status().error());
3044 EXPECT_EQ(redirect_url, r->url());
3045 EXPECT_EQ(original_url, r->original_url());
3046 EXPECT_EQ(2U, r->url_chain().size());
3047 EXPECT_EQ(1, network_delegate.created_requests());
3048 EXPECT_EQ(0, network_delegate.destroyed_requests());
3049 EXPECT_EQ("POST", r->method());
3050 EXPECT_EQ(kData, d.data_received());
3051 }
3052 EXPECT_EQ(1, network_delegate.destroyed_requests());
3053 }
3054
3055 // Tests that the network delegate can block and redirect a request to a new
3056 // URL during OnHeadersReceived.
TEST_F(URLRequestTestHTTP,NetworkDelegateRedirectRequestOnHeadersReceived)3057 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3058 ASSERT_TRUE(test_server_.Start());
3059
3060 TestDelegate d;
3061 BlockingNetworkDelegate network_delegate(
3062 BlockingNetworkDelegate::AUTO_CALLBACK);
3063 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3064 GURL redirect_url(test_server_.GetURL("simple.html"));
3065 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3066
3067 TestURLRequestContextWithProxy context(
3068 test_server_.host_port_pair().ToString(), &network_delegate);
3069
3070 {
3071 GURL original_url(test_server_.GetURL("empty.html"));
3072 scoped_ptr<URLRequest> r(context.CreateRequest(
3073 original_url, DEFAULT_PRIORITY, &d, NULL));
3074
3075 r->Start();
3076 base::RunLoop().Run();
3077
3078 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3079 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3080 EXPECT_EQ(
3081 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3082 EXPECT_TRUE(
3083 network_delegate.last_observed_proxy().Equals(
3084 test_server_.host_port_pair()));
3085
3086 EXPECT_EQ(OK, r->status().error());
3087 EXPECT_EQ(redirect_url, r->url());
3088 EXPECT_EQ(original_url, r->original_url());
3089 EXPECT_EQ(2U, r->url_chain().size());
3090 EXPECT_EQ(2, network_delegate.created_requests());
3091 EXPECT_EQ(0, network_delegate.destroyed_requests());
3092 }
3093 EXPECT_EQ(1, network_delegate.destroyed_requests());
3094 }
3095
3096 // Tests that the network delegate can synchronously complete OnAuthRequired
3097 // by taking no action. This indicates that the NetworkDelegate does not want to
3098 // handle the challenge, and is passing the buck along to the
3099 // URLRequest::Delegate.
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredSyncNoAction)3100 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3101 ASSERT_TRUE(test_server_.Start());
3102
3103 TestDelegate d;
3104 BlockingNetworkDelegate network_delegate(
3105 BlockingNetworkDelegate::SYNCHRONOUS);
3106
3107 TestURLRequestContext context(true);
3108 context.set_network_delegate(&network_delegate);
3109 context.Init();
3110
3111 d.set_credentials(AuthCredentials(kUser, kSecret));
3112
3113 {
3114 GURL url(test_server_.GetURL("auth-basic"));
3115 scoped_ptr<URLRequest> r(context.CreateRequest(
3116 url, DEFAULT_PRIORITY, &d, NULL));
3117 r->Start();
3118
3119 base::RunLoop().Run();
3120
3121 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3122 EXPECT_EQ(0, r->status().error());
3123 EXPECT_EQ(200, r->GetResponseCode());
3124 EXPECT_TRUE(d.auth_required_called());
3125 EXPECT_EQ(1, network_delegate.created_requests());
3126 EXPECT_EQ(0, network_delegate.destroyed_requests());
3127 }
3128 EXPECT_EQ(1, network_delegate.destroyed_requests());
3129 }
3130
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders)3131 TEST_F(URLRequestTestHTTP,
3132 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3133 ASSERT_TRUE(test_server_.Start());
3134
3135 TestDelegate d;
3136 BlockingNetworkDelegate network_delegate(
3137 BlockingNetworkDelegate::SYNCHRONOUS);
3138
3139 TestURLRequestContext context(true);
3140 context.set_network_delegate(&network_delegate);
3141 context.Init();
3142
3143 d.set_credentials(AuthCredentials(kUser, kSecret));
3144
3145 {
3146 GURL url(test_server_.GetURL("auth-basic"));
3147 scoped_ptr<URLRequest> r(context.CreateRequest(
3148 url, DEFAULT_PRIORITY, &d, NULL));
3149 r->Start();
3150
3151 {
3152 HttpRequestHeaders headers;
3153 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3154 EXPECT_FALSE(headers.HasHeader("Authorization"));
3155 }
3156
3157 base::RunLoop().Run();
3158
3159 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3160 EXPECT_EQ(0, r->status().error());
3161 EXPECT_EQ(200, r->GetResponseCode());
3162 EXPECT_TRUE(d.auth_required_called());
3163 EXPECT_EQ(1, network_delegate.created_requests());
3164 EXPECT_EQ(0, network_delegate.destroyed_requests());
3165 }
3166 EXPECT_EQ(1, network_delegate.destroyed_requests());
3167 }
3168
3169 // Tests that the network delegate can synchronously complete OnAuthRequired
3170 // by setting credentials.
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredSyncSetAuth)3171 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3172 ASSERT_TRUE(test_server_.Start());
3173
3174 TestDelegate d;
3175 BlockingNetworkDelegate network_delegate(
3176 BlockingNetworkDelegate::SYNCHRONOUS);
3177 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3178 network_delegate.set_auth_retval(
3179 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3180
3181 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3182
3183 TestURLRequestContext context(true);
3184 context.set_network_delegate(&network_delegate);
3185 context.Init();
3186
3187 {
3188 GURL url(test_server_.GetURL("auth-basic"));
3189 scoped_ptr<URLRequest> r(context.CreateRequest(
3190 url, DEFAULT_PRIORITY, &d, NULL));
3191 r->Start();
3192 base::RunLoop().Run();
3193
3194 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3195 EXPECT_EQ(0, r->status().error());
3196 EXPECT_EQ(200, r->GetResponseCode());
3197 EXPECT_FALSE(d.auth_required_called());
3198 EXPECT_EQ(1, network_delegate.created_requests());
3199 EXPECT_EQ(0, network_delegate.destroyed_requests());
3200 }
3201 EXPECT_EQ(1, network_delegate.destroyed_requests());
3202 }
3203
3204 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3205 // headers (for the first or second request) when called at the proper times.
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders)3206 TEST_F(URLRequestTestHTTP,
3207 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3208 ASSERT_TRUE(test_server_.Start());
3209
3210 TestDelegate d;
3211 BlockingNetworkDelegate network_delegate(
3212 BlockingNetworkDelegate::SYNCHRONOUS);
3213 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3214 network_delegate.set_auth_retval(
3215 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3216
3217 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3218
3219 TestURLRequestContext context(true);
3220 context.set_network_delegate(&network_delegate);
3221 context.Init();
3222
3223 {
3224 GURL url(test_server_.GetURL("auth-basic"));
3225 scoped_ptr<URLRequest> r(context.CreateRequest(
3226 url, DEFAULT_PRIORITY, &d, NULL));
3227 r->Start();
3228 base::RunLoop().Run();
3229
3230 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3231 EXPECT_EQ(0, r->status().error());
3232 EXPECT_EQ(200, r->GetResponseCode());
3233 EXPECT_FALSE(d.auth_required_called());
3234 EXPECT_EQ(1, network_delegate.created_requests());
3235 EXPECT_EQ(0, network_delegate.destroyed_requests());
3236
3237 {
3238 HttpRequestHeaders headers;
3239 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3240 EXPECT_TRUE(headers.HasHeader("Authorization"));
3241 }
3242 }
3243 EXPECT_EQ(1, network_delegate.destroyed_requests());
3244 }
3245
3246 // Tests that the network delegate can synchronously complete OnAuthRequired
3247 // by cancelling authentication.
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredSyncCancel)3248 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3249 ASSERT_TRUE(test_server_.Start());
3250
3251 TestDelegate d;
3252 BlockingNetworkDelegate network_delegate(
3253 BlockingNetworkDelegate::SYNCHRONOUS);
3254 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3255 network_delegate.set_auth_retval(
3256 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3257
3258 TestURLRequestContext context(true);
3259 context.set_network_delegate(&network_delegate);
3260 context.Init();
3261
3262 {
3263 GURL url(test_server_.GetURL("auth-basic"));
3264 scoped_ptr<URLRequest> r(context.CreateRequest(
3265 url, DEFAULT_PRIORITY, &d, NULL));
3266 r->Start();
3267 base::RunLoop().Run();
3268
3269 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3270 EXPECT_EQ(OK, r->status().error());
3271 EXPECT_EQ(401, r->GetResponseCode());
3272 EXPECT_FALSE(d.auth_required_called());
3273 EXPECT_EQ(1, network_delegate.created_requests());
3274 EXPECT_EQ(0, network_delegate.destroyed_requests());
3275 }
3276 EXPECT_EQ(1, network_delegate.destroyed_requests());
3277 }
3278
3279 // Tests that the network delegate can asynchronously complete OnAuthRequired
3280 // by taking no action. This indicates that the NetworkDelegate does not want
3281 // to handle the challenge, and is passing the buck along to the
3282 // URLRequest::Delegate.
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredAsyncNoAction)3283 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3284 ASSERT_TRUE(test_server_.Start());
3285
3286 TestDelegate d;
3287 BlockingNetworkDelegate network_delegate(
3288 BlockingNetworkDelegate::AUTO_CALLBACK);
3289 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3290
3291 TestURLRequestContext context(true);
3292 context.set_network_delegate(&network_delegate);
3293 context.Init();
3294
3295 d.set_credentials(AuthCredentials(kUser, kSecret));
3296
3297 {
3298 GURL url(test_server_.GetURL("auth-basic"));
3299 scoped_ptr<URLRequest> r(context.CreateRequest(
3300 url, DEFAULT_PRIORITY, &d, NULL));
3301 r->Start();
3302 base::RunLoop().Run();
3303
3304 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3305 EXPECT_EQ(0, r->status().error());
3306 EXPECT_EQ(200, r->GetResponseCode());
3307 EXPECT_TRUE(d.auth_required_called());
3308 EXPECT_EQ(1, network_delegate.created_requests());
3309 EXPECT_EQ(0, network_delegate.destroyed_requests());
3310 }
3311 EXPECT_EQ(1, network_delegate.destroyed_requests());
3312 }
3313
3314 // Tests that the network delegate can asynchronously complete OnAuthRequired
3315 // by setting credentials.
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredAsyncSetAuth)3316 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3317 ASSERT_TRUE(test_server_.Start());
3318
3319 TestDelegate d;
3320 BlockingNetworkDelegate network_delegate(
3321 BlockingNetworkDelegate::AUTO_CALLBACK);
3322 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3323 network_delegate.set_auth_retval(
3324 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3325
3326 AuthCredentials auth_credentials(kUser, kSecret);
3327 network_delegate.set_auth_credentials(auth_credentials);
3328
3329 TestURLRequestContext context(true);
3330 context.set_network_delegate(&network_delegate);
3331 context.Init();
3332
3333 {
3334 GURL url(test_server_.GetURL("auth-basic"));
3335 scoped_ptr<URLRequest> r(context.CreateRequest(
3336 url, DEFAULT_PRIORITY, &d, NULL));
3337 r->Start();
3338 base::RunLoop().Run();
3339
3340 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3341 EXPECT_EQ(0, r->status().error());
3342
3343 EXPECT_EQ(200, r->GetResponseCode());
3344 EXPECT_FALSE(d.auth_required_called());
3345 EXPECT_EQ(1, network_delegate.created_requests());
3346 EXPECT_EQ(0, network_delegate.destroyed_requests());
3347 }
3348 EXPECT_EQ(1, network_delegate.destroyed_requests());
3349 }
3350
3351 // Tests that the network delegate can asynchronously complete OnAuthRequired
3352 // by cancelling authentication.
TEST_F(URLRequestTestHTTP,NetworkDelegateOnAuthRequiredAsyncCancel)3353 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3354 ASSERT_TRUE(test_server_.Start());
3355
3356 TestDelegate d;
3357 BlockingNetworkDelegate network_delegate(
3358 BlockingNetworkDelegate::AUTO_CALLBACK);
3359 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3360 network_delegate.set_auth_retval(
3361 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3362
3363 TestURLRequestContext context(true);
3364 context.set_network_delegate(&network_delegate);
3365 context.Init();
3366
3367 {
3368 GURL url(test_server_.GetURL("auth-basic"));
3369 scoped_ptr<URLRequest> r(context.CreateRequest(
3370 url, DEFAULT_PRIORITY, &d, NULL));
3371 r->Start();
3372 base::RunLoop().Run();
3373
3374 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3375 EXPECT_EQ(OK, r->status().error());
3376 EXPECT_EQ(401, r->GetResponseCode());
3377 EXPECT_FALSE(d.auth_required_called());
3378 EXPECT_EQ(1, network_delegate.created_requests());
3379 EXPECT_EQ(0, network_delegate.destroyed_requests());
3380 }
3381 EXPECT_EQ(1, network_delegate.destroyed_requests());
3382 }
3383
3384 // Tests that we can handle when a network request was canceled while we were
3385 // waiting for the network delegate.
3386 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelWhileWaiting1)3387 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3388 ASSERT_TRUE(test_server_.Start());
3389
3390 TestDelegate d;
3391 BlockingNetworkDelegate network_delegate(
3392 BlockingNetworkDelegate::USER_CALLBACK);
3393 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3394
3395 TestURLRequestContext context(true);
3396 context.set_network_delegate(&network_delegate);
3397 context.Init();
3398
3399 {
3400 scoped_ptr<URLRequest> r(context.CreateRequest(
3401 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3402
3403 r->Start();
3404 base::RunLoop().Run();
3405 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3406 network_delegate.stage_blocked_for_callback());
3407 EXPECT_EQ(0, network_delegate.completed_requests());
3408 // Cancel before callback.
3409 r->Cancel();
3410 // Ensure that network delegate is notified.
3411 EXPECT_EQ(1, network_delegate.completed_requests());
3412 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3413 EXPECT_EQ(ERR_ABORTED, r->status().error());
3414 EXPECT_EQ(1, network_delegate.created_requests());
3415 EXPECT_EQ(0, network_delegate.destroyed_requests());
3416 }
3417 EXPECT_EQ(1, network_delegate.destroyed_requests());
3418 }
3419
3420 // Tests that we can handle when a network request was canceled while we were
3421 // waiting for the network delegate.
3422 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelWhileWaiting2)3423 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3424 ASSERT_TRUE(test_server_.Start());
3425
3426 TestDelegate d;
3427 BlockingNetworkDelegate network_delegate(
3428 BlockingNetworkDelegate::USER_CALLBACK);
3429 network_delegate.set_block_on(
3430 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
3431
3432 TestURLRequestContext context(true);
3433 context.set_network_delegate(&network_delegate);
3434 context.Init();
3435
3436 {
3437 scoped_ptr<URLRequest> r(context.CreateRequest(
3438 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3439
3440 r->Start();
3441 base::RunLoop().Run();
3442 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3443 network_delegate.stage_blocked_for_callback());
3444 EXPECT_EQ(0, network_delegate.completed_requests());
3445 // Cancel before callback.
3446 r->Cancel();
3447 // Ensure that network delegate is notified.
3448 EXPECT_EQ(1, network_delegate.completed_requests());
3449 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3450 EXPECT_EQ(ERR_ABORTED, r->status().error());
3451 EXPECT_EQ(1, network_delegate.created_requests());
3452 EXPECT_EQ(0, network_delegate.destroyed_requests());
3453 }
3454 EXPECT_EQ(1, network_delegate.destroyed_requests());
3455 }
3456
3457 // Tests that we can handle when a network request was canceled while we were
3458 // waiting for the network delegate.
3459 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelWhileWaiting3)3460 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3461 ASSERT_TRUE(test_server_.Start());
3462
3463 TestDelegate d;
3464 BlockingNetworkDelegate network_delegate(
3465 BlockingNetworkDelegate::USER_CALLBACK);
3466 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3467
3468 TestURLRequestContext context(true);
3469 context.set_network_delegate(&network_delegate);
3470 context.Init();
3471
3472 {
3473 scoped_ptr<URLRequest> r(context.CreateRequest(
3474 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3475
3476 r->Start();
3477 base::RunLoop().Run();
3478 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3479 network_delegate.stage_blocked_for_callback());
3480 EXPECT_EQ(0, network_delegate.completed_requests());
3481 // Cancel before callback.
3482 r->Cancel();
3483 // Ensure that network delegate is notified.
3484 EXPECT_EQ(1, network_delegate.completed_requests());
3485 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3486 EXPECT_EQ(ERR_ABORTED, r->status().error());
3487 EXPECT_EQ(1, network_delegate.created_requests());
3488 EXPECT_EQ(0, network_delegate.destroyed_requests());
3489 }
3490 EXPECT_EQ(1, network_delegate.destroyed_requests());
3491 }
3492
3493 // Tests that we can handle when a network request was canceled while we were
3494 // waiting for the network delegate.
3495 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
TEST_F(URLRequestTestHTTP,NetworkDelegateCancelWhileWaiting4)3496 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
3497 ASSERT_TRUE(test_server_.Start());
3498
3499 TestDelegate d;
3500 BlockingNetworkDelegate network_delegate(
3501 BlockingNetworkDelegate::USER_CALLBACK);
3502 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3503
3504 TestURLRequestContext context(true);
3505 context.set_network_delegate(&network_delegate);
3506 context.Init();
3507
3508 {
3509 scoped_ptr<URLRequest> r(context.CreateRequest(
3510 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
3511
3512 r->Start();
3513 base::RunLoop().Run();
3514 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3515 network_delegate.stage_blocked_for_callback());
3516 EXPECT_EQ(0, network_delegate.completed_requests());
3517 // Cancel before callback.
3518 r->Cancel();
3519 // Ensure that network delegate is notified.
3520 EXPECT_EQ(1, network_delegate.completed_requests());
3521 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3522 EXPECT_EQ(ERR_ABORTED, r->status().error());
3523 EXPECT_EQ(1, network_delegate.created_requests());
3524 EXPECT_EQ(0, network_delegate.destroyed_requests());
3525 }
3526 EXPECT_EQ(1, network_delegate.destroyed_requests());
3527 }
3528
3529 // In this unit test, we're using the HTTPTestServer as a proxy server and
3530 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3531 // The HTTPTestServer will return a 401 response, which we should balk at.
TEST_F(URLRequestTestHTTP,UnexpectedServerAuthTest)3532 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
3533 ASSERT_TRUE(test_server_.Start());
3534
3535 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3536 TestURLRequestContextWithProxy context(
3537 test_server_.host_port_pair().ToString(), &network_delegate);
3538
3539 TestDelegate d;
3540 {
3541 scoped_ptr<URLRequest> r(context.CreateRequest(
3542 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, NULL));
3543
3544 r->Start();
3545 EXPECT_TRUE(r->is_pending());
3546
3547 base::RunLoop().Run();
3548
3549 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3550 // The proxy server is not set before failure.
3551 EXPECT_TRUE(r->proxy_server().IsEmpty());
3552 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
3553 }
3554 }
3555
TEST_F(URLRequestTestHTTP,GetTest_NoCache)3556 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
3557 ASSERT_TRUE(test_server_.Start());
3558
3559 TestDelegate d;
3560 {
3561 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3562 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3563
3564 r->Start();
3565 EXPECT_TRUE(r->is_pending());
3566
3567 base::RunLoop().Run();
3568
3569 EXPECT_EQ(1, d.response_started_count());
3570 EXPECT_FALSE(d.received_data_before_response());
3571 EXPECT_NE(0, d.bytes_received());
3572 EXPECT_EQ(test_server_.host_port_pair().host(),
3573 r->GetSocketAddress().host());
3574 EXPECT_EQ(test_server_.host_port_pair().port(),
3575 r->GetSocketAddress().port());
3576
3577 // TODO(eroman): Add back the NetLog tests...
3578 }
3579 }
3580
3581 // This test has the server send a large number of cookies to the client.
3582 // To ensure that no number of cookies causes a crash, a galloping binary
3583 // search is used to estimate that maximum number of cookies that are accepted
3584 // by the browser. Beyond the maximum number, the request will fail with
3585 // ERR_RESPONSE_HEADERS_TOO_BIG.
3586 #if defined(OS_WIN)
3587 // http://crbug.com/177916
3588 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3589 #else
3590 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3591 #endif // defined(OS_WIN)
TEST_F(URLRequestTestHTTP,MAYBE_GetTest_ManyCookies)3592 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
3593 ASSERT_TRUE(test_server_.Start());
3594
3595 int lower_bound = 0;
3596 int upper_bound = 1;
3597
3598 // Double the number of cookies until the response header limits are
3599 // exceeded.
3600 while (DoManyCookiesRequest(upper_bound)) {
3601 lower_bound = upper_bound;
3602 upper_bound *= 2;
3603 ASSERT_LT(upper_bound, 1000000);
3604 }
3605
3606 int tolerance = upper_bound * 0.005;
3607 if (tolerance < 2)
3608 tolerance = 2;
3609
3610 // Perform a binary search to find the highest possible number of cookies,
3611 // within the desired tolerance.
3612 while (upper_bound - lower_bound >= tolerance) {
3613 int num_cookies = (lower_bound + upper_bound) / 2;
3614
3615 if (DoManyCookiesRequest(num_cookies))
3616 lower_bound = num_cookies;
3617 else
3618 upper_bound = num_cookies;
3619 }
3620 // Success: the test did not crash.
3621 }
3622
TEST_F(URLRequestTestHTTP,GetTest)3623 TEST_F(URLRequestTestHTTP, GetTest) {
3624 ASSERT_TRUE(test_server_.Start());
3625
3626 TestDelegate d;
3627 {
3628 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3629 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3630
3631 r->Start();
3632 EXPECT_TRUE(r->is_pending());
3633
3634 base::RunLoop().Run();
3635
3636 EXPECT_EQ(1, d.response_started_count());
3637 EXPECT_FALSE(d.received_data_before_response());
3638 EXPECT_NE(0, d.bytes_received());
3639 EXPECT_EQ(test_server_.host_port_pair().host(),
3640 r->GetSocketAddress().host());
3641 EXPECT_EQ(test_server_.host_port_pair().port(),
3642 r->GetSocketAddress().port());
3643 }
3644 }
3645
TEST_F(URLRequestTestHTTP,GetTest_GetFullRequestHeaders)3646 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3647 ASSERT_TRUE(test_server_.Start());
3648
3649 TestDelegate d;
3650 {
3651 GURL test_url(test_server_.GetURL(std::string()));
3652 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3653 test_url, DEFAULT_PRIORITY, &d, NULL));
3654
3655 HttpRequestHeaders headers;
3656 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
3657
3658 r->Start();
3659 EXPECT_TRUE(r->is_pending());
3660
3661 base::RunLoop().Run();
3662
3663 EXPECT_EQ(1, d.response_started_count());
3664 EXPECT_FALSE(d.received_data_before_response());
3665 EXPECT_NE(0, d.bytes_received());
3666 EXPECT_EQ(test_server_.host_port_pair().host(),
3667 r->GetSocketAddress().host());
3668 EXPECT_EQ(test_server_.host_port_pair().port(),
3669 r->GetSocketAddress().port());
3670
3671 EXPECT_TRUE(d.have_full_request_headers());
3672 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3673 }
3674 }
3675
TEST_F(URLRequestTestHTTP,GetTestLoadTiming)3676 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3677 ASSERT_TRUE(test_server_.Start());
3678
3679 TestDelegate d;
3680 {
3681 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3682 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
3683
3684 r->Start();
3685 EXPECT_TRUE(r->is_pending());
3686
3687 base::RunLoop().Run();
3688
3689 LoadTimingInfo load_timing_info;
3690 r->GetLoadTimingInfo(&load_timing_info);
3691 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3692
3693 EXPECT_EQ(1, d.response_started_count());
3694 EXPECT_FALSE(d.received_data_before_response());
3695 EXPECT_NE(0, d.bytes_received());
3696 EXPECT_EQ(test_server_.host_port_pair().host(),
3697 r->GetSocketAddress().host());
3698 EXPECT_EQ(test_server_.host_port_pair().port(),
3699 r->GetSocketAddress().port());
3700 }
3701 }
3702
TEST_F(URLRequestTestHTTP,GetZippedTest)3703 TEST_F(URLRequestTestHTTP, GetZippedTest) {
3704 ASSERT_TRUE(test_server_.Start());
3705
3706 // Parameter that specifies the Content-Length field in the response:
3707 // C - Compressed length.
3708 // U - Uncompressed length.
3709 // L - Large length (larger than both C & U).
3710 // M - Medium length (between C & U).
3711 // S - Small length (smaller than both C & U).
3712 const char test_parameters[] = "CULMS";
3713 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3714 // C & U should be OK.
3715 // L & M are larger than the data sent, and show an error.
3716 // S has too little data, but we seem to accept it.
3717 const bool test_expect_success[num_tests] =
3718 { true, true, false, false, true };
3719
3720 for (int i = 0; i < num_tests ; i++) {
3721 TestDelegate d;
3722 {
3723 std::string test_file =
3724 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3725 test_parameters[i]);
3726
3727 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3728 TestURLRequestContext context(true);
3729 context.set_network_delegate(&network_delegate);
3730 context.Init();
3731
3732 scoped_ptr<URLRequest> r(context.CreateRequest(
3733 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, NULL));
3734 r->Start();
3735 EXPECT_TRUE(r->is_pending());
3736
3737 base::RunLoop().Run();
3738
3739 EXPECT_EQ(1, d.response_started_count());
3740 EXPECT_FALSE(d.received_data_before_response());
3741 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3742 << " status = " << r->status().status()
3743 << " error = " << r->status().error();
3744 if (test_expect_success[i]) {
3745 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
3746 << " Parameter = \"" << test_file << "\"";
3747 } else {
3748 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3749 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
3750 << " Parameter = \"" << test_file << "\"";
3751 }
3752 }
3753 }
3754 }
3755
TEST_F(URLRequestTestHTTP,HTTPSToHTTPRedirectNoRefererTest)3756 TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
3757 ASSERT_TRUE(test_server_.Start());
3758
3759 SpawnedTestServer https_test_server(
3760 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
3761 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3762 ASSERT_TRUE(https_test_server.Start());
3763
3764 // An https server is sent a request with an https referer,
3765 // and responds with a redirect to an http url. The http
3766 // server should not be sent the referer.
3767 GURL http_destination = test_server_.GetURL(std::string());
3768 TestDelegate d;
3769 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3770 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3771 DEFAULT_PRIORITY, &d, NULL));
3772 req->SetReferrer("https://www.referrer.com/");
3773 req->Start();
3774 base::RunLoop().Run();
3775
3776 EXPECT_EQ(1, d.response_started_count());
3777 EXPECT_EQ(1, d.received_redirect_count());
3778 EXPECT_EQ(http_destination, req->url());
3779 EXPECT_EQ(std::string(), req->referrer());
3780 }
3781
TEST_F(URLRequestTestHTTP,RedirectLoadTiming)3782 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3783 ASSERT_TRUE(test_server_.Start());
3784
3785 GURL destination_url = test_server_.GetURL(std::string());
3786 GURL original_url =
3787 test_server_.GetURL("server-redirect?" + destination_url.spec());
3788 TestDelegate d;
3789 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3790 original_url, DEFAULT_PRIORITY, &d, NULL));
3791 req->Start();
3792 base::RunLoop().Run();
3793
3794 EXPECT_EQ(1, d.response_started_count());
3795 EXPECT_EQ(1, d.received_redirect_count());
3796 EXPECT_EQ(destination_url, req->url());
3797 EXPECT_EQ(original_url, req->original_url());
3798 ASSERT_EQ(2U, req->url_chain().size());
3799 EXPECT_EQ(original_url, req->url_chain()[0]);
3800 EXPECT_EQ(destination_url, req->url_chain()[1]);
3801
3802 LoadTimingInfo load_timing_info_before_redirect;
3803 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3804 &load_timing_info_before_redirect));
3805 TestLoadTimingNotReused(load_timing_info_before_redirect,
3806 CONNECT_TIMING_HAS_DNS_TIMES);
3807
3808 LoadTimingInfo load_timing_info;
3809 req->GetLoadTimingInfo(&load_timing_info);
3810 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3811
3812 // Check that a new socket was used on redirect, since the server does not
3813 // supposed keep-alive sockets, and that the times before the redirect are
3814 // before the ones recorded for the second request.
3815 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3816 load_timing_info.socket_log_id);
3817 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3818 load_timing_info.connect_timing.connect_start);
3819 }
3820
TEST_F(URLRequestTestHTTP,MultipleRedirectTest)3821 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3822 ASSERT_TRUE(test_server_.Start());
3823
3824 GURL destination_url = test_server_.GetURL(std::string());
3825 GURL middle_redirect_url =
3826 test_server_.GetURL("server-redirect?" + destination_url.spec());
3827 GURL original_url = test_server_.GetURL(
3828 "server-redirect?" + middle_redirect_url.spec());
3829 TestDelegate d;
3830 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3831 original_url, DEFAULT_PRIORITY, &d, NULL));
3832 req->Start();
3833 base::RunLoop().Run();
3834
3835 EXPECT_EQ(1, d.response_started_count());
3836 EXPECT_EQ(2, d.received_redirect_count());
3837 EXPECT_EQ(destination_url, req->url());
3838 EXPECT_EQ(original_url, req->original_url());
3839 ASSERT_EQ(3U, req->url_chain().size());
3840 EXPECT_EQ(original_url, req->url_chain()[0]);
3841 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
3842 EXPECT_EQ(destination_url, req->url_chain()[2]);
3843 }
3844
3845 // First and second pieces of information logged by delegates to URLRequests.
3846 const char kFirstDelegateInfo[] = "Wonderful delegate";
3847 const char kSecondDelegateInfo[] = "Exciting delegate";
3848
3849 // Logs delegate information to a URLRequest. The first string is logged
3850 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3851 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3852 // another asynchronous call is used to clear the delegate information
3853 // before calling a callback. The object then deletes itself.
3854 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3855 public:
3856 typedef base::Callback<void()> Callback;
3857
3858 // Each time delegate information is added to the URLRequest, the resulting
3859 // load state is checked. The expected load state after each request is
3860 // passed in as an argument.
Run(URLRequest * url_request,LoadState expected_first_load_state,LoadState expected_second_load_state,LoadState expected_third_load_state,const Callback & callback)3861 static void Run(URLRequest* url_request,
3862 LoadState expected_first_load_state,
3863 LoadState expected_second_load_state,
3864 LoadState expected_third_load_state,
3865 const Callback& callback) {
3866 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3867 url_request,
3868 expected_first_load_state,
3869 expected_second_load_state,
3870 expected_third_load_state,
3871 callback);
3872 logger->Start();
3873 }
3874
3875 // Checks that the log entries, starting with log_position, contain the
3876 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3877 // recorded. Returns the index of entry after the expected number of
3878 // events this logged, or entries.size() if there aren't enough entries.
CheckDelegateInfo(const CapturingNetLog::CapturedEntryList & entries,size_t log_position)3879 static size_t CheckDelegateInfo(
3880 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3881 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3882 if (log_position + 3 >= entries.size()) {
3883 ADD_FAILURE() << "Not enough log entries";
3884 return entries.size();
3885 }
3886 std::string delegate_info;
3887 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3888 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3889 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3890 &delegate_info));
3891 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3892
3893 ++log_position;
3894 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3895 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3896
3897 ++log_position;
3898 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3899 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3900 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3901 &delegate_info));
3902 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3903
3904 ++log_position;
3905 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3906 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3907
3908 return log_position + 1;
3909 }
3910
3911 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3912 // Returns the position of the end message.
ExpectBeforeNetworkEvents(const CapturingNetLog::CapturedEntryList & entries,size_t log_position)3913 static size_t ExpectBeforeNetworkEvents(
3914 const CapturingNetLog::CapturedEntryList& entries,
3915 size_t log_position) {
3916 log_position =
3917 ExpectLogContainsSomewhereAfter(entries,
3918 log_position,
3919 NetLog::TYPE_URL_REQUEST_DELEGATE,
3920 NetLog::PHASE_BEGIN);
3921 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3922 entries[log_position + 1].type);
3923 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3924 return log_position + 1;
3925 }
3926
3927 private:
3928 friend class base::RefCounted<AsyncDelegateLogger>;
3929
AsyncDelegateLogger(URLRequest * url_request,LoadState expected_first_load_state,LoadState expected_second_load_state,LoadState expected_third_load_state,const Callback & callback)3930 AsyncDelegateLogger(URLRequest* url_request,
3931 LoadState expected_first_load_state,
3932 LoadState expected_second_load_state,
3933 LoadState expected_third_load_state,
3934 const Callback& callback)
3935 : url_request_(url_request),
3936 expected_first_load_state_(expected_first_load_state),
3937 expected_second_load_state_(expected_second_load_state),
3938 expected_third_load_state_(expected_third_load_state),
3939 callback_(callback) {
3940 }
3941
~AsyncDelegateLogger()3942 ~AsyncDelegateLogger() {}
3943
Start()3944 void Start() {
3945 url_request_->LogBlockedBy(kFirstDelegateInfo);
3946 LoadStateWithParam load_state = url_request_->GetLoadState();
3947 EXPECT_EQ(expected_first_load_state_, load_state.state);
3948 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3949 base::MessageLoop::current()->PostTask(
3950 FROM_HERE,
3951 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3952 }
3953
LogSecondDelegate()3954 void LogSecondDelegate() {
3955 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
3956 LoadStateWithParam load_state = url_request_->GetLoadState();
3957 EXPECT_EQ(expected_second_load_state_, load_state.state);
3958 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3959 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3960 } else {
3961 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3962 }
3963 base::MessageLoop::current()->PostTask(
3964 FROM_HERE,
3965 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3966 }
3967
LogComplete()3968 void LogComplete() {
3969 url_request_->LogUnblocked();
3970 LoadStateWithParam load_state = url_request_->GetLoadState();
3971 EXPECT_EQ(expected_third_load_state_, load_state.state);
3972 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3973 EXPECT_EQ(base::string16(), load_state.param);
3974 callback_.Run();
3975 }
3976
3977 URLRequest* url_request_;
3978 const int expected_first_load_state_;
3979 const int expected_second_load_state_;
3980 const int expected_third_load_state_;
3981 const Callback callback_;
3982
3983 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3984 };
3985
3986 // NetworkDelegate that logs delegate information before a request is started,
3987 // before headers are sent, when headers are read, and when auth information
3988 // is requested. Uses AsyncDelegateLogger.
3989 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3990 public:
AsyncLoggingNetworkDelegate()3991 AsyncLoggingNetworkDelegate() {}
~AsyncLoggingNetworkDelegate()3992 virtual ~AsyncLoggingNetworkDelegate() {}
3993
3994 // NetworkDelegate implementation.
OnBeforeURLRequest(URLRequest * request,const CompletionCallback & callback,GURL * new_url)3995 virtual int OnBeforeURLRequest(URLRequest* request,
3996 const CompletionCallback& callback,
3997 GURL* new_url) OVERRIDE {
3998 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3999 return RunCallbackAsynchronously(request, callback);
4000 }
4001
OnBeforeSendHeaders(URLRequest * request,const CompletionCallback & callback,HttpRequestHeaders * headers)4002 virtual int OnBeforeSendHeaders(URLRequest* request,
4003 const CompletionCallback& callback,
4004 HttpRequestHeaders* headers) OVERRIDE {
4005 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4006 return RunCallbackAsynchronously(request, callback);
4007 }
4008
OnHeadersReceived(URLRequest * request,const CompletionCallback & callback,const HttpResponseHeaders * original_response_headers,scoped_refptr<HttpResponseHeaders> * override_response_headers,GURL * allowed_unsafe_redirect_url)4009 virtual int OnHeadersReceived(
4010 URLRequest* request,
4011 const CompletionCallback& callback,
4012 const HttpResponseHeaders* original_response_headers,
4013 scoped_refptr<HttpResponseHeaders>* override_response_headers,
4014 GURL* allowed_unsafe_redirect_url) OVERRIDE {
4015 TestNetworkDelegate::OnHeadersReceived(request,
4016 callback,
4017 original_response_headers,
4018 override_response_headers,
4019 allowed_unsafe_redirect_url);
4020 return RunCallbackAsynchronously(request, callback);
4021 }
4022
OnAuthRequired(URLRequest * request,const AuthChallengeInfo & auth_info,const AuthCallback & callback,AuthCredentials * credentials)4023 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
4024 URLRequest* request,
4025 const AuthChallengeInfo& auth_info,
4026 const AuthCallback& callback,
4027 AuthCredentials* credentials) OVERRIDE {
4028 AsyncDelegateLogger::Run(
4029 request,
4030 LOAD_STATE_WAITING_FOR_DELEGATE,
4031 LOAD_STATE_WAITING_FOR_DELEGATE,
4032 LOAD_STATE_WAITING_FOR_DELEGATE,
4033 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4034 callback, credentials));
4035 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4036 }
4037
4038 private:
RunCallbackAsynchronously(URLRequest * request,const CompletionCallback & callback)4039 static int RunCallbackAsynchronously(
4040 URLRequest* request,
4041 const CompletionCallback& callback) {
4042 AsyncDelegateLogger::Run(
4043 request,
4044 LOAD_STATE_WAITING_FOR_DELEGATE,
4045 LOAD_STATE_WAITING_FOR_DELEGATE,
4046 LOAD_STATE_WAITING_FOR_DELEGATE,
4047 base::Bind(callback, OK));
4048 return ERR_IO_PENDING;
4049 }
4050
SetAuthAndResume(const AuthCallback & callback,AuthCredentials * credentials)4051 static void SetAuthAndResume(const AuthCallback& callback,
4052 AuthCredentials* credentials) {
4053 *credentials = AuthCredentials(kUser, kSecret);
4054 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4055 }
4056
4057 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4058 };
4059
4060 // URLRequest::Delegate that logs delegate information when the headers
4061 // are received, when each read completes, and during redirects. Uses
4062 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4063 //
4064 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4065 // advancing to the next step in most cases, as well as cancellation.
4066 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4067 public:
4068 enum CancelStage {
4069 NO_CANCEL = 0,
4070 CANCEL_ON_RECEIVED_REDIRECT,
4071 CANCEL_ON_RESPONSE_STARTED,
4072 CANCEL_ON_READ_COMPLETED
4073 };
4074
AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)4075 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4076 : cancel_stage_(cancel_stage) {
4077 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4078 set_cancel_in_received_redirect(true);
4079 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4080 set_cancel_in_response_started(true);
4081 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4082 set_cancel_in_received_data(true);
4083 }
~AsyncLoggingUrlRequestDelegate()4084 virtual ~AsyncLoggingUrlRequestDelegate() {}
4085
4086 // URLRequest::Delegate implementation:
OnReceivedRedirect(URLRequest * request,const RedirectInfo & redirect_info,bool * defer_redirect)4087 void virtual OnReceivedRedirect(URLRequest* request,
4088 const RedirectInfo& redirect_info,
4089 bool* defer_redirect) OVERRIDE {
4090 *defer_redirect = true;
4091 AsyncDelegateLogger::Run(
4092 request,
4093 LOAD_STATE_WAITING_FOR_DELEGATE,
4094 LOAD_STATE_WAITING_FOR_DELEGATE,
4095 LOAD_STATE_WAITING_FOR_DELEGATE,
4096 base::Bind(
4097 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4098 base::Unretained(this), request, redirect_info));
4099 }
4100
OnResponseStarted(URLRequest * request)4101 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4102 AsyncDelegateLogger::Run(
4103 request,
4104 LOAD_STATE_WAITING_FOR_DELEGATE,
4105 LOAD_STATE_WAITING_FOR_DELEGATE,
4106 LOAD_STATE_WAITING_FOR_DELEGATE,
4107 base::Bind(
4108 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4109 base::Unretained(this), request));
4110 }
4111
OnReadCompleted(URLRequest * request,int bytes_read)4112 virtual void OnReadCompleted(URLRequest* request,
4113 int bytes_read) OVERRIDE {
4114 AsyncDelegateLogger::Run(
4115 request,
4116 LOAD_STATE_IDLE,
4117 LOAD_STATE_IDLE,
4118 LOAD_STATE_IDLE,
4119 base::Bind(
4120 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4121 base::Unretained(this), request, bytes_read));
4122 }
4123
4124 private:
OnReceivedRedirectLoggingComplete(URLRequest * request,const RedirectInfo & redirect_info)4125 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4126 const RedirectInfo& redirect_info) {
4127 bool defer_redirect = false;
4128 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
4129 // FollowDeferredRedirect should not be called after cancellation.
4130 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4131 return;
4132 if (!defer_redirect)
4133 request->FollowDeferredRedirect();
4134 }
4135
OnResponseStartedLoggingComplete(URLRequest * request)4136 void OnResponseStartedLoggingComplete(URLRequest* request) {
4137 // The parent class continues the request.
4138 TestDelegate::OnResponseStarted(request);
4139 }
4140
AfterReadCompletedLoggingComplete(URLRequest * request,int bytes_read)4141 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4142 // The parent class continues the request.
4143 TestDelegate::OnReadCompleted(request, bytes_read);
4144 }
4145
4146 const CancelStage cancel_stage_;
4147
4148 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4149 };
4150
4151 // Tests handling of delegate info before a request starts.
TEST_F(URLRequestTestHTTP,DelegateInfoBeforeStart)4152 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4153 ASSERT_TRUE(test_server_.Start());
4154
4155 TestDelegate request_delegate;
4156 TestURLRequestContext context(true);
4157 context.set_network_delegate(NULL);
4158 context.set_net_log(&net_log_);
4159 context.Init();
4160
4161 {
4162 scoped_ptr<URLRequest> r(context.CreateRequest(
4163 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &request_delegate,
4164 NULL));
4165 LoadStateWithParam load_state = r->GetLoadState();
4166 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4167 EXPECT_EQ(base::string16(), load_state.param);
4168
4169 AsyncDelegateLogger::Run(
4170 r.get(),
4171 LOAD_STATE_WAITING_FOR_DELEGATE,
4172 LOAD_STATE_WAITING_FOR_DELEGATE,
4173 LOAD_STATE_IDLE,
4174 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
4175
4176 base::RunLoop().Run();
4177
4178 EXPECT_EQ(200, r->GetResponseCode());
4179 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4180 }
4181
4182 CapturingNetLog::CapturedEntryList entries;
4183 net_log_.GetEntries(&entries);
4184 size_t log_position = ExpectLogContainsSomewhereAfter(
4185 entries,
4186 0,
4187 NetLog::TYPE_DELEGATE_INFO,
4188 NetLog::PHASE_BEGIN);
4189
4190 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4191
4192 // Nothing else should add any delegate info to the request.
4193 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4194 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4195 }
4196
4197 // Tests handling of delegate info from a network delegate.
TEST_F(URLRequestTestHTTP,NetworkDelegateInfo)4198 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4199 ASSERT_TRUE(test_server_.Start());
4200
4201 TestDelegate request_delegate;
4202 AsyncLoggingNetworkDelegate network_delegate;
4203 TestURLRequestContext context(true);
4204 context.set_network_delegate(&network_delegate);
4205 context.set_net_log(&net_log_);
4206 context.Init();
4207
4208 {
4209 scoped_ptr<URLRequest> r(context.CreateRequest(
4210 test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &request_delegate,
4211 NULL));
4212 LoadStateWithParam load_state = r->GetLoadState();
4213 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4214 EXPECT_EQ(base::string16(), load_state.param);
4215
4216 r->Start();
4217 base::RunLoop().Run();
4218
4219 EXPECT_EQ(200, r->GetResponseCode());
4220 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4221 EXPECT_EQ(1, network_delegate.created_requests());
4222 EXPECT_EQ(0, network_delegate.destroyed_requests());
4223 }
4224 EXPECT_EQ(1, network_delegate.destroyed_requests());
4225
4226 size_t log_position = 0;
4227 CapturingNetLog::CapturedEntryList entries;
4228 net_log_.GetEntries(&entries);
4229 for (size_t i = 0; i < 3; ++i) {
4230 log_position = ExpectLogContainsSomewhereAfter(
4231 entries,
4232 log_position + 1,
4233 NetLog::TYPE_URL_REQUEST_DELEGATE,
4234 NetLog::PHASE_BEGIN);
4235
4236 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4237 log_position + 1);
4238
4239 ASSERT_LT(log_position, entries.size());
4240 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4241 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4242
4243 if (i == 1) {
4244 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4245 entries, log_position + 1);
4246 }
4247 }
4248
4249 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4250 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4251 }
4252
4253 // Tests handling of delegate info from a network delegate in the case of an
4254 // HTTP redirect.
TEST_F(URLRequestTestHTTP,NetworkDelegateInfoRedirect)4255 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4256 ASSERT_TRUE(test_server_.Start());
4257
4258 TestDelegate request_delegate;
4259 AsyncLoggingNetworkDelegate network_delegate;
4260 TestURLRequestContext context(true);
4261 context.set_network_delegate(&network_delegate);
4262 context.set_net_log(&net_log_);
4263 context.Init();
4264
4265 {
4266 scoped_ptr<URLRequest> r(context.CreateRequest(
4267 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4268 &request_delegate, NULL));
4269 LoadStateWithParam load_state = r->GetLoadState();
4270 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4271 EXPECT_EQ(base::string16(), load_state.param);
4272
4273 r->Start();
4274 base::RunLoop().Run();
4275
4276 EXPECT_EQ(200, r->GetResponseCode());
4277 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4278 EXPECT_EQ(2, network_delegate.created_requests());
4279 EXPECT_EQ(0, network_delegate.destroyed_requests());
4280 }
4281 EXPECT_EQ(1, network_delegate.destroyed_requests());
4282
4283 size_t log_position = 0;
4284 CapturingNetLog::CapturedEntryList entries;
4285 net_log_.GetEntries(&entries);
4286 // The NetworkDelegate logged information in OnBeforeURLRequest,
4287 // OnBeforeSendHeaders, and OnHeadersReceived.
4288 for (size_t i = 0; i < 3; ++i) {
4289 log_position = ExpectLogContainsSomewhereAfter(
4290 entries,
4291 log_position + 1,
4292 NetLog::TYPE_URL_REQUEST_DELEGATE,
4293 NetLog::PHASE_BEGIN);
4294
4295 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4296 log_position + 1);
4297
4298 ASSERT_LT(log_position, entries.size());
4299 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4300 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4301
4302 if (i == 1) {
4303 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4304 entries, log_position + 1);
4305 }
4306 }
4307
4308 // The URLRequest::Delegate then gets informed about the redirect.
4309 log_position = ExpectLogContainsSomewhereAfter(
4310 entries,
4311 log_position + 1,
4312 NetLog::TYPE_URL_REQUEST_DELEGATE,
4313 NetLog::PHASE_BEGIN);
4314
4315 // The NetworkDelegate logged information in the same three events as before.
4316 for (size_t i = 0; i < 3; ++i) {
4317 log_position = ExpectLogContainsSomewhereAfter(
4318 entries,
4319 log_position + 1,
4320 NetLog::TYPE_URL_REQUEST_DELEGATE,
4321 NetLog::PHASE_BEGIN);
4322
4323 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4324 log_position + 1);
4325
4326 ASSERT_LT(log_position, entries.size());
4327 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4328 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4329 }
4330
4331 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4332 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4333 }
4334
4335 // Tests handling of delegate info from a network delegate in the case of HTTP
4336 // AUTH.
TEST_F(URLRequestTestHTTP,NetworkDelegateInfoAuth)4337 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4338 ASSERT_TRUE(test_server_.Start());
4339
4340 TestDelegate request_delegate;
4341 AsyncLoggingNetworkDelegate network_delegate;
4342 TestURLRequestContext context(true);
4343 context.set_network_delegate(&network_delegate);
4344 context.set_net_log(&net_log_);
4345 context.Init();
4346
4347 {
4348 scoped_ptr<URLRequest> r(context.CreateRequest(
4349 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &request_delegate,
4350 NULL));
4351 LoadStateWithParam load_state = r->GetLoadState();
4352 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4353 EXPECT_EQ(base::string16(), load_state.param);
4354
4355 r->Start();
4356 base::RunLoop().Run();
4357
4358 EXPECT_EQ(200, r->GetResponseCode());
4359 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4360 EXPECT_EQ(1, network_delegate.created_requests());
4361 EXPECT_EQ(0, network_delegate.destroyed_requests());
4362 }
4363 EXPECT_EQ(1, network_delegate.destroyed_requests());
4364
4365 size_t log_position = 0;
4366 CapturingNetLog::CapturedEntryList entries;
4367 net_log_.GetEntries(&entries);
4368 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4369 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4370 // OnBeforeURLRequest and OnBeforeSendHeaders.
4371 for (size_t i = 0; i < 6; ++i) {
4372 log_position = ExpectLogContainsSomewhereAfter(
4373 entries,
4374 log_position + 1,
4375 NetLog::TYPE_URL_REQUEST_DELEGATE,
4376 NetLog::PHASE_BEGIN);
4377
4378 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4379 log_position + 1);
4380
4381 ASSERT_LT(log_position, entries.size());
4382 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4383 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4384
4385 if (i == 1) {
4386 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4387 entries, log_position + 1);
4388 }
4389 }
4390
4391 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4392 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4393 }
4394
4395 // Tests handling of delegate info from a URLRequest::Delegate.
TEST_F(URLRequestTestHTTP,URLRequestDelegateInfo)4396 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4397 ASSERT_TRUE(test_server_.Start());
4398
4399 AsyncLoggingUrlRequestDelegate request_delegate(
4400 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4401 TestURLRequestContext context(true);
4402 context.set_network_delegate(NULL);
4403 context.set_net_log(&net_log_);
4404 context.Init();
4405
4406 {
4407 // A chunked response with delays between chunks is used to make sure that
4408 // attempts by the URLRequest delegate to log information while reading the
4409 // body are ignored. Since they are ignored, this test is robust against
4410 // the possibility of multiple reads being combined in the unlikely event
4411 // that it occurs.
4412 scoped_ptr<URLRequest> r(context.CreateRequest(
4413 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
4414 &request_delegate, NULL));
4415 LoadStateWithParam load_state = r->GetLoadState();
4416 r->Start();
4417 base::RunLoop().Run();
4418
4419 EXPECT_EQ(200, r->GetResponseCode());
4420 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4421 }
4422
4423 CapturingNetLog::CapturedEntryList entries;
4424 net_log_.GetEntries(&entries);
4425
4426 size_t log_position = 0;
4427
4428 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4429 entries, log_position);
4430
4431 // The delegate info should only have been logged on header complete. Other
4432 // times it should silently be ignored.
4433 log_position =
4434 ExpectLogContainsSomewhereAfter(entries,
4435 log_position + 1,
4436 NetLog::TYPE_URL_REQUEST_DELEGATE,
4437 NetLog::PHASE_BEGIN);
4438
4439 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4440 log_position + 1);
4441
4442 ASSERT_LT(log_position, entries.size());
4443 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4444 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4445
4446 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4447 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4448 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4449 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4450 }
4451
4452 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4453 // an HTTP redirect.
TEST_F(URLRequestTestHTTP,URLRequestDelegateInfoOnRedirect)4454 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4455 ASSERT_TRUE(test_server_.Start());
4456
4457 AsyncLoggingUrlRequestDelegate request_delegate(
4458 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4459 TestURLRequestContext context(true);
4460 context.set_network_delegate(NULL);
4461 context.set_net_log(&net_log_);
4462 context.Init();
4463
4464 {
4465 scoped_ptr<URLRequest> r(context.CreateRequest(
4466 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4467 &request_delegate, NULL));
4468 LoadStateWithParam load_state = r->GetLoadState();
4469 r->Start();
4470 base::RunLoop().Run();
4471
4472 EXPECT_EQ(200, r->GetResponseCode());
4473 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4474 }
4475
4476 CapturingNetLog::CapturedEntryList entries;
4477 net_log_.GetEntries(&entries);
4478
4479 // Delegate info should only have been logged in OnReceivedRedirect and
4480 // OnResponseStarted.
4481 size_t log_position = 0;
4482 for (int i = 0; i < 2; ++i) {
4483 if (i == 0) {
4484 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4485 entries, log_position) + 1;
4486 }
4487
4488 log_position = ExpectLogContainsSomewhereAfter(
4489 entries,
4490 log_position,
4491 NetLog::TYPE_URL_REQUEST_DELEGATE,
4492 NetLog::PHASE_BEGIN);
4493
4494 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4495 log_position + 1);
4496
4497 ASSERT_LT(log_position, entries.size());
4498 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4499 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4500 }
4501
4502 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4503 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4504 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4505 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4506 }
4507
4508 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4509 // an HTTP redirect, with cancellation at various points.
TEST_F(URLRequestTestHTTP,URLRequestDelegateOnRedirectCancelled)4510 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4511 ASSERT_TRUE(test_server_.Start());
4512
4513 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4514 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4515 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4516 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4517 };
4518
4519 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4520 ++test_case) {
4521 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4522 TestURLRequestContext context(true);
4523 CapturingNetLog net_log;
4524 context.set_network_delegate(NULL);
4525 context.set_net_log(&net_log);
4526 context.Init();
4527
4528 {
4529 scoped_ptr<URLRequest> r(context.CreateRequest(
4530 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4531 &request_delegate, NULL));
4532 LoadStateWithParam load_state = r->GetLoadState();
4533 r->Start();
4534 base::RunLoop().Run();
4535 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4536 }
4537
4538 CapturingNetLog::CapturedEntryList entries;
4539 net_log.GetEntries(&entries);
4540
4541 // Delegate info is always logged in both OnReceivedRedirect and
4542 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4543 // OnResponseStarted delegate call is after cancellation, but logging is
4544 // still currently supported in that call.
4545 size_t log_position = 0;
4546 for (int i = 0; i < 2; ++i) {
4547 if (i == 0) {
4548 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4549 entries, log_position) + 1;
4550 }
4551
4552 log_position = ExpectLogContainsSomewhereAfter(
4553 entries,
4554 log_position,
4555 NetLog::TYPE_URL_REQUEST_DELEGATE,
4556 NetLog::PHASE_BEGIN);
4557
4558 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4559 log_position + 1);
4560
4561 ASSERT_LT(log_position, entries.size());
4562 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4563 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4564 }
4565
4566 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4567 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4568 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4569 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4570 }
4571 }
4572
4573 namespace {
4574
4575 const char kExtraHeader[] = "Allow-Snafu";
4576 const char kExtraValue[] = "fubar";
4577
4578 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
OnReceivedRedirect(URLRequest * request,const RedirectInfo & redirect_info,bool * defer_redirect)4579 virtual void OnReceivedRedirect(URLRequest* request,
4580 const RedirectInfo& redirect_info,
4581 bool* defer_redirect) OVERRIDE {
4582 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
4583 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4584 }
4585 };
4586
4587 } // namespace
4588
TEST_F(URLRequestTestHTTP,RedirectWithAdditionalHeadersTest)4589 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4590 ASSERT_TRUE(test_server_.Start());
4591
4592 GURL destination_url = test_server_.GetURL(
4593 "echoheader?" + std::string(kExtraHeader));
4594 GURL original_url = test_server_.GetURL(
4595 "server-redirect?" + destination_url.spec());
4596 RedirectWithAdditionalHeadersDelegate d;
4597 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4598 original_url, DEFAULT_PRIORITY, &d, NULL));
4599 req->Start();
4600 base::RunLoop().Run();
4601
4602 std::string value;
4603 const HttpRequestHeaders& headers = req->extra_request_headers();
4604 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4605 EXPECT_EQ(kExtraValue, value);
4606 EXPECT_FALSE(req->is_pending());
4607 EXPECT_FALSE(req->is_redirecting());
4608 EXPECT_EQ(kExtraValue, d.data_received());
4609 }
4610
4611 namespace {
4612
4613 const char kExtraHeaderToRemove[] = "To-Be-Removed";
4614
4615 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
OnReceivedRedirect(URLRequest * request,const RedirectInfo & redirect_info,bool * defer_redirect)4616 virtual void OnReceivedRedirect(URLRequest* request,
4617 const RedirectInfo& redirect_info,
4618 bool* defer_redirect) OVERRIDE {
4619 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
4620 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4621 }
4622 };
4623
4624 } // namespace
4625
TEST_F(URLRequestTestHTTP,RedirectWithHeaderRemovalTest)4626 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4627 ASSERT_TRUE(test_server_.Start());
4628
4629 GURL destination_url = test_server_.GetURL(
4630 "echoheader?" + std::string(kExtraHeaderToRemove));
4631 GURL original_url = test_server_.GetURL(
4632 "server-redirect?" + destination_url.spec());
4633 RedirectWithHeaderRemovalDelegate d;
4634 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4635 original_url, DEFAULT_PRIORITY, &d, NULL));
4636 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4637 req->Start();
4638 base::RunLoop().Run();
4639
4640 std::string value;
4641 const HttpRequestHeaders& headers = req->extra_request_headers();
4642 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4643 EXPECT_FALSE(req->is_pending());
4644 EXPECT_FALSE(req->is_redirecting());
4645 EXPECT_EQ("None", d.data_received());
4646 }
4647
TEST_F(URLRequestTestHTTP,CancelTest)4648 TEST_F(URLRequestTestHTTP, CancelTest) {
4649 TestDelegate d;
4650 {
4651 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4652 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d, NULL));
4653
4654 r->Start();
4655 EXPECT_TRUE(r->is_pending());
4656
4657 r->Cancel();
4658
4659 base::RunLoop().Run();
4660
4661 // We expect to receive OnResponseStarted even though the request has been
4662 // cancelled.
4663 EXPECT_EQ(1, d.response_started_count());
4664 EXPECT_EQ(0, d.bytes_received());
4665 EXPECT_FALSE(d.received_data_before_response());
4666 }
4667 }
4668
TEST_F(URLRequestTestHTTP,CancelTest2)4669 TEST_F(URLRequestTestHTTP, CancelTest2) {
4670 ASSERT_TRUE(test_server_.Start());
4671
4672 TestDelegate d;
4673 {
4674 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4675 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4676
4677 d.set_cancel_in_response_started(true);
4678
4679 r->Start();
4680 EXPECT_TRUE(r->is_pending());
4681
4682 base::RunLoop().Run();
4683
4684 EXPECT_EQ(1, d.response_started_count());
4685 EXPECT_EQ(0, d.bytes_received());
4686 EXPECT_FALSE(d.received_data_before_response());
4687 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4688 }
4689 }
4690
TEST_F(URLRequestTestHTTP,CancelTest3)4691 TEST_F(URLRequestTestHTTP, CancelTest3) {
4692 ASSERT_TRUE(test_server_.Start());
4693
4694 TestDelegate d;
4695 {
4696 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4697 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4698
4699 d.set_cancel_in_received_data(true);
4700
4701 r->Start();
4702 EXPECT_TRUE(r->is_pending());
4703
4704 base::RunLoop().Run();
4705
4706 EXPECT_EQ(1, d.response_started_count());
4707 // There is no guarantee about how much data was received
4708 // before the cancel was issued. It could have been 0 bytes,
4709 // or it could have been all the bytes.
4710 // EXPECT_EQ(0, d.bytes_received());
4711 EXPECT_FALSE(d.received_data_before_response());
4712 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4713 }
4714 }
4715
TEST_F(URLRequestTestHTTP,CancelTest4)4716 TEST_F(URLRequestTestHTTP, CancelTest4) {
4717 ASSERT_TRUE(test_server_.Start());
4718
4719 TestDelegate d;
4720 {
4721 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4722 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
4723
4724 r->Start();
4725 EXPECT_TRUE(r->is_pending());
4726
4727 // The request will be implicitly canceled when it is destroyed. The
4728 // test delegate must not post a quit message when this happens because
4729 // this test doesn't actually have a message loop. The quit message would
4730 // get put on this thread's message queue and the next test would exit
4731 // early, causing problems.
4732 d.set_quit_on_complete(false);
4733 }
4734 // expect things to just cleanup properly.
4735
4736 // we won't actually get a received reponse here because we've never run the
4737 // message loop
4738 EXPECT_FALSE(d.received_data_before_response());
4739 EXPECT_EQ(0, d.bytes_received());
4740 }
4741
TEST_F(URLRequestTestHTTP,CancelTest5)4742 TEST_F(URLRequestTestHTTP, CancelTest5) {
4743 ASSERT_TRUE(test_server_.Start());
4744
4745 // populate cache
4746 {
4747 TestDelegate d;
4748 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4749 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
4750 r->Start();
4751 base::RunLoop().Run();
4752 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4753 }
4754
4755 // cancel read from cache (see bug 990242)
4756 {
4757 TestDelegate d;
4758 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4759 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
4760 r->Start();
4761 r->Cancel();
4762 base::RunLoop().Run();
4763
4764 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4765 EXPECT_EQ(1, d.response_started_count());
4766 EXPECT_EQ(0, d.bytes_received());
4767 EXPECT_FALSE(d.received_data_before_response());
4768 }
4769 }
4770
TEST_F(URLRequestTestHTTP,PostTest)4771 TEST_F(URLRequestTestHTTP, PostTest) {
4772 ASSERT_TRUE(test_server_.Start());
4773 HTTPUploadDataOperationTest("POST");
4774 }
4775
TEST_F(URLRequestTestHTTP,PutTest)4776 TEST_F(URLRequestTestHTTP, PutTest) {
4777 ASSERT_TRUE(test_server_.Start());
4778 HTTPUploadDataOperationTest("PUT");
4779 }
4780
TEST_F(URLRequestTestHTTP,PostEmptyTest)4781 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4782 ASSERT_TRUE(test_server_.Start());
4783
4784 TestDelegate d;
4785 {
4786 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4787 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4788 r->set_method("POST");
4789
4790 r->Start();
4791 EXPECT_TRUE(r->is_pending());
4792
4793 base::RunLoop().Run();
4794
4795 ASSERT_EQ(1, d.response_started_count())
4796 << "request failed: " << r->status().status()
4797 << ", error: " << r->status().error();
4798
4799 EXPECT_FALSE(d.received_data_before_response());
4800 EXPECT_TRUE(d.data_received().empty());
4801 }
4802 }
4803
TEST_F(URLRequestTestHTTP,PostFileTest)4804 TEST_F(URLRequestTestHTTP, PostFileTest) {
4805 ASSERT_TRUE(test_server_.Start());
4806
4807 TestDelegate d;
4808 {
4809 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4810 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4811 r->set_method("POST");
4812
4813 base::FilePath dir;
4814 PathService::Get(base::DIR_EXE, &dir);
4815 base::SetCurrentDirectory(dir);
4816
4817 ScopedVector<UploadElementReader> element_readers;
4818
4819 base::FilePath path;
4820 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4821 path = path.Append(FILE_PATH_LITERAL("net"));
4822 path = path.Append(FILE_PATH_LITERAL("data"));
4823 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4824 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4825 element_readers.push_back(
4826 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4827 path,
4828 0,
4829 kuint64max,
4830 base::Time()));
4831 r->set_upload(make_scoped_ptr(
4832 new UploadDataStream(element_readers.Pass(), 0)));
4833
4834 r->Start();
4835 EXPECT_TRUE(r->is_pending());
4836
4837 base::RunLoop().Run();
4838
4839 int64 size = 0;
4840 ASSERT_EQ(true, base::GetFileSize(path, &size));
4841 scoped_ptr<char[]> buf(new char[size]);
4842
4843 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
4844
4845 ASSERT_EQ(1, d.response_started_count())
4846 << "request failed: " << r->status().status()
4847 << ", error: " << r->status().error();
4848
4849 EXPECT_FALSE(d.received_data_before_response());
4850
4851 EXPECT_EQ(size, d.bytes_received());
4852 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
4853 }
4854 }
4855
TEST_F(URLRequestTestHTTP,PostUnreadableFileTest)4856 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4857 ASSERT_TRUE(test_server_.Start());
4858
4859 TestDelegate d;
4860 {
4861 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4862 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4863 r->set_method("POST");
4864
4865 ScopedVector<UploadElementReader> element_readers;
4866
4867 element_readers.push_back(new UploadFileElementReader(
4868 base::MessageLoopProxy::current().get(),
4869 base::FilePath(FILE_PATH_LITERAL(
4870 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4871 0,
4872 kuint64max,
4873 base::Time()));
4874 r->set_upload(make_scoped_ptr(
4875 new UploadDataStream(element_readers.Pass(), 0)));
4876
4877 r->Start();
4878 EXPECT_TRUE(r->is_pending());
4879
4880 base::RunLoop().Run();
4881
4882 EXPECT_TRUE(d.request_failed());
4883 EXPECT_FALSE(d.received_data_before_response());
4884 EXPECT_EQ(0, d.bytes_received());
4885 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4886 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
4887 }
4888 }
4889
TEST_F(URLRequestTestHTTP,TestPostChunkedDataBeforeStart)4890 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4891 ASSERT_TRUE(test_server_.Start());
4892
4893 TestDelegate d;
4894 {
4895 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4896 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4897 r->EnableChunkedUpload();
4898 r->set_method("POST");
4899 AddChunksToUpload(r.get());
4900 r->Start();
4901 EXPECT_TRUE(r->is_pending());
4902
4903 base::RunLoop().Run();
4904
4905 VerifyReceivedDataMatchesChunks(r.get(), &d);
4906 }
4907 }
4908
TEST_F(URLRequestTestHTTP,TestPostChunkedDataJustAfterStart)4909 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4910 ASSERT_TRUE(test_server_.Start());
4911
4912 TestDelegate d;
4913 {
4914 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4915 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4916 r->EnableChunkedUpload();
4917 r->set_method("POST");
4918 r->Start();
4919 EXPECT_TRUE(r->is_pending());
4920 AddChunksToUpload(r.get());
4921 base::RunLoop().Run();
4922
4923 VerifyReceivedDataMatchesChunks(r.get(), &d);
4924 }
4925 }
4926
TEST_F(URLRequestTestHTTP,TestPostChunkedDataAfterStart)4927 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4928 ASSERT_TRUE(test_server_.Start());
4929
4930 TestDelegate d;
4931 {
4932 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4933 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4934 r->EnableChunkedUpload();
4935 r->set_method("POST");
4936 r->Start();
4937 EXPECT_TRUE(r->is_pending());
4938
4939 base::RunLoop().RunUntilIdle();
4940 AddChunksToUpload(r.get());
4941 base::RunLoop().Run();
4942
4943 VerifyReceivedDataMatchesChunks(r.get(), &d);
4944 }
4945 }
4946
TEST_F(URLRequestTestHTTP,ResponseHeadersTest)4947 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4948 ASSERT_TRUE(test_server_.Start());
4949
4950 TestDelegate d;
4951 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4952 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d,
4953 NULL));
4954 req->Start();
4955 base::RunLoop().Run();
4956
4957 const HttpResponseHeaders* headers = req->response_headers();
4958
4959 // Simple sanity check that response_info() accesses the same data.
4960 EXPECT_EQ(headers, req->response_info().headers.get());
4961
4962 std::string header;
4963 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4964 EXPECT_EQ("private", header);
4965
4966 header.clear();
4967 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4968 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4969
4970 // The response has two "X-Multiple-Entries" headers.
4971 // This verfies our output has them concatenated together.
4972 header.clear();
4973 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4974 EXPECT_EQ("a, b", header);
4975 }
4976
TEST_F(URLRequestTestHTTP,ProcessSTS)4977 TEST_F(URLRequestTestHTTP, ProcessSTS) {
4978 SpawnedTestServer::SSLOptions ssl_options;
4979 SpawnedTestServer https_test_server(
4980 SpawnedTestServer::TYPE_HTTPS,
4981 ssl_options,
4982 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4983 ASSERT_TRUE(https_test_server.Start());
4984
4985 TestDelegate d;
4986 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
4987 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY, &d,
4988 NULL));
4989 request->Start();
4990 base::RunLoop().Run();
4991
4992 TransportSecurityState* security_state =
4993 default_context_.transport_security_state();
4994 TransportSecurityState::DomainState domain_state;
4995 EXPECT_TRUE(security_state->GetDynamicDomainState(
4996 SpawnedTestServer::kLocalhost, &domain_state));
4997 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4998 domain_state.sts.upgrade_mode);
4999 EXPECT_TRUE(domain_state.sts.include_subdomains);
5000 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5001 #if defined(OS_ANDROID)
5002 // Android's CertVerifyProc does not (yet) handle pins.
5003 #else
5004 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5005 #endif
5006 }
5007
5008 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5009 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5010 // DomainState present because header rejected).
5011 #if defined(OS_ANDROID)
5012 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5013 #else
5014 #define MAYBE_ProcessPKP ProcessPKP
5015 #endif
5016
5017 // Tests that enabling HPKP on a domain does not affect the HSTS
5018 // validity/expiration.
TEST_F(URLRequestTestHTTP,MAYBE_ProcessPKP)5019 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5020 SpawnedTestServer::SSLOptions ssl_options;
5021 SpawnedTestServer https_test_server(
5022 SpawnedTestServer::TYPE_HTTPS,
5023 ssl_options,
5024 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5025 ASSERT_TRUE(https_test_server.Start());
5026
5027 TestDelegate d;
5028 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5029 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
5030 NULL));
5031 request->Start();
5032 base::RunLoop().Run();
5033
5034 TransportSecurityState* security_state =
5035 default_context_.transport_security_state();
5036 TransportSecurityState::DomainState domain_state;
5037 EXPECT_TRUE(security_state->GetDynamicDomainState(
5038 SpawnedTestServer::kLocalhost, &domain_state));
5039 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5040 domain_state.sts.upgrade_mode);
5041 EXPECT_FALSE(domain_state.sts.include_subdomains);
5042 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5043 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5044 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5045 }
5046
TEST_F(URLRequestTestHTTP,ProcessSTSOnce)5047 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5048 SpawnedTestServer::SSLOptions ssl_options;
5049 SpawnedTestServer https_test_server(
5050 SpawnedTestServer::TYPE_HTTPS,
5051 ssl_options,
5052 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5053 ASSERT_TRUE(https_test_server.Start());
5054
5055 TestDelegate d;
5056 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5057 https_test_server.GetURL("files/hsts-multiple-headers.html"),
5058 DEFAULT_PRIORITY, &d, NULL));
5059 request->Start();
5060 base::RunLoop().Run();
5061
5062 // We should have set parameters from the first header, not the second.
5063 TransportSecurityState* security_state =
5064 default_context_.transport_security_state();
5065 TransportSecurityState::DomainState domain_state;
5066 EXPECT_TRUE(security_state->GetDynamicDomainState(
5067 SpawnedTestServer::kLocalhost, &domain_state));
5068 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5069 domain_state.sts.upgrade_mode);
5070 EXPECT_FALSE(domain_state.sts.include_subdomains);
5071 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5072 }
5073
TEST_F(URLRequestTestHTTP,ProcessSTSAndPKP)5074 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5075 SpawnedTestServer::SSLOptions ssl_options;
5076 SpawnedTestServer https_test_server(
5077 SpawnedTestServer::TYPE_HTTPS,
5078 ssl_options,
5079 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5080 ASSERT_TRUE(https_test_server.Start());
5081
5082 TestDelegate d;
5083 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5084 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5085 DEFAULT_PRIORITY, &d, NULL));
5086 request->Start();
5087 base::RunLoop().Run();
5088
5089 // We should have set parameters from the first header, not the second.
5090 TransportSecurityState* security_state =
5091 default_context_.transport_security_state();
5092 TransportSecurityState::DomainState domain_state;
5093 EXPECT_TRUE(security_state->GetDynamicDomainState(
5094 SpawnedTestServer::kLocalhost, &domain_state));
5095 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5096 domain_state.sts.upgrade_mode);
5097 #if defined(OS_ANDROID)
5098 // Android's CertVerifyProc does not (yet) handle pins.
5099 #else
5100 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5101 #endif
5102 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5103
5104 // Even though there is an HSTS header asserting includeSubdomains, it is
5105 // the *second* such header, and we MUST process only the first.
5106 EXPECT_FALSE(domain_state.sts.include_subdomains);
5107 // includeSubdomains does not occur in the test HPKP header.
5108 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5109 }
5110
5111 // Tests that when multiple HPKP headers are present, asserting different
5112 // policies, that only the first such policy is processed.
TEST_F(URLRequestTestHTTP,ProcessSTSAndPKP2)5113 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5114 SpawnedTestServer::SSLOptions ssl_options;
5115 SpawnedTestServer https_test_server(
5116 SpawnedTestServer::TYPE_HTTPS,
5117 ssl_options,
5118 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5119 ASSERT_TRUE(https_test_server.Start());
5120
5121 TestDelegate d;
5122 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5123 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5124 DEFAULT_PRIORITY, &d, NULL));
5125 request->Start();
5126 base::RunLoop().Run();
5127
5128 TransportSecurityState* security_state =
5129 default_context_.transport_security_state();
5130 TransportSecurityState::DomainState domain_state;
5131 EXPECT_TRUE(security_state->GetDynamicDomainState(
5132 SpawnedTestServer::kLocalhost, &domain_state));
5133 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5134 domain_state.sts.upgrade_mode);
5135 #if defined(OS_ANDROID)
5136 // Android's CertVerifyProc does not (yet) handle pins.
5137 #else
5138 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5139 #endif
5140 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5141
5142 EXPECT_TRUE(domain_state.sts.include_subdomains);
5143 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5144 }
5145
TEST_F(URLRequestTestHTTP,ContentTypeNormalizationTest)5146 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5147 ASSERT_TRUE(test_server_.Start());
5148
5149 TestDelegate d;
5150 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5151 test_server_.GetURL("files/content-type-normalization.html"),
5152 DEFAULT_PRIORITY, &d, NULL));
5153 req->Start();
5154 base::RunLoop().Run();
5155
5156 std::string mime_type;
5157 req->GetMimeType(&mime_type);
5158 EXPECT_EQ("text/html", mime_type);
5159
5160 std::string charset;
5161 req->GetCharset(&charset);
5162 EXPECT_EQ("utf-8", charset);
5163 req->Cancel();
5164 }
5165
TEST_F(URLRequestTestHTTP,ProtocolHandlerAndFactoryRestrictDataRedirects)5166 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
5167 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5168 GURL data_url("data:,foo");
5169 DataProtocolHandler data_protocol_handler;
5170 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5171
5172 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5173 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
5174 }
5175
5176 #if !defined(DISABLE_FILE_SUPPORT)
TEST_F(URLRequestTestHTTP,ProtocolHandlerAndFactoryRestrictFileRedirects)5177 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5178 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5179 GURL file_url("file:///foo.txt");
5180 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5181 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5182
5183 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5184 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
5185 }
5186
TEST_F(URLRequestTestHTTP,RestrictFileRedirects)5187 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5188 ASSERT_TRUE(test_server_.Start());
5189
5190 TestDelegate d;
5191 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5192 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY, &d,
5193 NULL));
5194 req->Start();
5195 base::RunLoop().Run();
5196
5197 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5198 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5199 }
5200 #endif // !defined(DISABLE_FILE_SUPPORT)
5201
TEST_F(URLRequestTestHTTP,RestrictDataRedirects)5202 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5203 ASSERT_TRUE(test_server_.Start());
5204
5205 TestDelegate d;
5206 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5207 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY, &d,
5208 NULL));
5209 req->Start();
5210 base::MessageLoop::current()->Run();
5211
5212 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5213 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
5214 }
5215
TEST_F(URLRequestTestHTTP,RedirectToInvalidURL)5216 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5217 ASSERT_TRUE(test_server_.Start());
5218
5219 TestDelegate d;
5220 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5221 test_server_.GetURL("files/redirect-to-invalid-url.html"),
5222 DEFAULT_PRIORITY, &d, NULL));
5223 req->Start();
5224 base::RunLoop().Run();
5225
5226 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5227 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
5228 }
5229
5230 // Make sure redirects are cached, despite not reading their bodies.
TEST_F(URLRequestTestHTTP,CacheRedirect)5231 TEST_F(URLRequestTestHTTP, CacheRedirect) {
5232 ASSERT_TRUE(test_server_.Start());
5233 GURL redirect_url =
5234 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5235
5236 {
5237 TestDelegate d;
5238 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5239 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5240 req->Start();
5241 base::RunLoop().Run();
5242 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5243 EXPECT_EQ(1, d.received_redirect_count());
5244 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5245 }
5246
5247 {
5248 TestDelegate d;
5249 d.set_quit_on_redirect(true);
5250 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5251 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5252 req->Start();
5253 base::RunLoop().Run();
5254
5255 EXPECT_EQ(1, d.received_redirect_count());
5256 EXPECT_EQ(0, d.response_started_count());
5257 EXPECT_TRUE(req->was_cached());
5258
5259 req->FollowDeferredRedirect();
5260 base::RunLoop().Run();
5261 EXPECT_EQ(1, d.received_redirect_count());
5262 EXPECT_EQ(1, d.response_started_count());
5263 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5264 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
5265 }
5266 }
5267
5268 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5269 // when the headers are read, since the body won't have been read.
TEST_F(URLRequestTestHTTP,NoCacheOnNetworkDelegateRedirect)5270 TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5271 ASSERT_TRUE(test_server_.Start());
5272 // URL that is normally cached.
5273 GURL initial_url = test_server_.GetURL("cachetime");
5274
5275 {
5276 // Set up the TestNetworkDelegate tp force a redirect.
5277 GURL redirect_to_url = test_server_.GetURL("echo");
5278 default_network_delegate_.set_redirect_on_headers_received_url(
5279 redirect_to_url);
5280
5281 TestDelegate d;
5282 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5283 initial_url, DEFAULT_PRIORITY, &d, NULL));
5284 req->Start();
5285 base::RunLoop().Run();
5286 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5287 EXPECT_EQ(1, d.received_redirect_count());
5288 EXPECT_EQ(redirect_to_url, req->url());
5289 }
5290
5291 {
5292 TestDelegate d;
5293 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5294 initial_url, DEFAULT_PRIORITY, &d, NULL));
5295 req->Start();
5296 base::RunLoop().Run();
5297
5298 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5299 EXPECT_FALSE(req->was_cached());
5300 EXPECT_EQ(0, d.received_redirect_count());
5301 EXPECT_EQ(initial_url, req->url());
5302 }
5303 }
5304
5305 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5306 // safe.
TEST_F(URLRequestTestHTTP,UnsafeRedirectToWhitelistedUnsafeURL)5307 TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5308 ASSERT_TRUE(test_server_.Start());
5309
5310 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5311 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5312 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5313
5314 TestDelegate d;
5315 {
5316 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5317 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
5318
5319 r->Start();
5320 base::RunLoop().Run();
5321
5322 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5323
5324 EXPECT_EQ(2U, r->url_chain().size());
5325 EXPECT_EQ(OK, r->status().error());
5326 EXPECT_EQ(unsafe_url, r->url());
5327 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5328 }
5329 }
5330
5331 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5332 // some other URL to the whitelist.
TEST_F(URLRequestTestHTTP,UnsafeRedirectToDifferentUnsafeURL)5333 TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5334 ASSERT_TRUE(test_server_.Start());
5335
5336 GURL unsafe_url("data:text/html,something");
5337 GURL different_unsafe_url("data:text/html,something-else");
5338 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5339 default_network_delegate_.set_allowed_unsafe_redirect_url(
5340 different_unsafe_url);
5341
5342 TestDelegate d;
5343 {
5344 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5345 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
5346
5347 r->Start();
5348 base::RunLoop().Run();
5349
5350 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5351 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
5352 }
5353 }
5354
5355 // Redirects from an URL with fragment to an unsafe URL with fragment should
5356 // be allowed, and the reference fragment of the target URL should be preserved.
TEST_F(URLRequestTestHTTP,UnsafeRedirectWithDifferentReferenceFragment)5357 TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5358 ASSERT_TRUE(test_server_.Start());
5359
5360 GURL original_url(test_server_.GetURL("original#fragment1"));
5361 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5362 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5363
5364 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5365 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5366
5367 TestDelegate d;
5368 {
5369 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5370 original_url, DEFAULT_PRIORITY, &d, NULL));
5371
5372 r->Start();
5373 base::RunLoop().Run();
5374
5375 EXPECT_EQ(2U, r->url_chain().size());
5376 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5377 EXPECT_EQ(OK, r->status().error());
5378 EXPECT_EQ(original_url, r->original_url());
5379 EXPECT_EQ(expected_url, r->url());
5380 }
5381 }
5382
5383 // When a delegate has specified a safe redirect URL, but it does not match the
5384 // redirect target, then do not prevent the reference fragment from being added.
TEST_F(URLRequestTestHTTP,RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl)5385 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
5386 ASSERT_TRUE(test_server_.Start());
5387
5388 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5389 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5390 GURL redirect_url(test_server_.GetURL("target"));
5391 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5392
5393 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5394 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5395
5396 TestDelegate d;
5397 {
5398 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5399 original_url, DEFAULT_PRIORITY, &d, NULL));
5400
5401 r->Start();
5402 base::RunLoop().Run();
5403
5404 EXPECT_EQ(2U, r->url_chain().size());
5405 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5406 EXPECT_EQ(OK, r->status().error());
5407 EXPECT_EQ(original_url, r->original_url());
5408 EXPECT_EQ(expected_redirect_url, r->url());
5409 }
5410 }
5411
5412 // When a delegate has specified a safe redirect URL, assume that the redirect
5413 // URL should not be changed. In particular, the reference fragment should not
5414 // be modified.
TEST_F(URLRequestTestHTTP,RedirectWithReferenceFragment)5415 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5416 ASSERT_TRUE(test_server_.Start());
5417
5418 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5419 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5420
5421 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5422 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5423
5424 TestDelegate d;
5425 {
5426 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5427 original_url, DEFAULT_PRIORITY, &d, NULL));
5428
5429 r->Start();
5430 base::RunLoop().Run();
5431
5432 EXPECT_EQ(2U, r->url_chain().size());
5433 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5434 EXPECT_EQ(OK, r->status().error());
5435 EXPECT_EQ(original_url, r->original_url());
5436 EXPECT_EQ(redirect_url, r->url());
5437 }
5438 }
5439
5440 // When a URLRequestRedirectJob is created, the redirection must be followed and
5441 // the reference fragment of the target URL must not be modified.
TEST_F(URLRequestTestHTTP,RedirectJobWithReferenceFragment)5442 TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5443 ASSERT_TRUE(test_server_.Start());
5444
5445 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5446 GURL redirect_url(test_server_.GetURL("echo"));
5447
5448 TestDelegate d;
5449 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5450 original_url, DEFAULT_PRIORITY, &d, NULL));
5451
5452 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5453 r.get(), &default_network_delegate_, redirect_url,
5454 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5455 AddTestInterceptor()->set_main_intercept_job(job);
5456
5457 r->Start();
5458 base::RunLoop().Run();
5459
5460 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5461 EXPECT_EQ(OK, r->status().error());
5462 EXPECT_EQ(original_url, r->original_url());
5463 EXPECT_EQ(redirect_url, r->url());
5464 }
5465
TEST_F(URLRequestTestHTTP,NoUserPassInReferrer)5466 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5467 ASSERT_TRUE(test_server_.Start());
5468
5469 TestDelegate d;
5470 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5471 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
5472 req->SetReferrer("http://user:pass@foo.com/");
5473 req->Start();
5474 base::RunLoop().Run();
5475
5476 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5477 }
5478
TEST_F(URLRequestTestHTTP,NoFragmentInReferrer)5479 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5480 ASSERT_TRUE(test_server_.Start());
5481
5482 TestDelegate d;
5483 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5484 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
5485 req->SetReferrer("http://foo.com/test#fragment");
5486 req->Start();
5487 base::RunLoop().Run();
5488
5489 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5490 }
5491
TEST_F(URLRequestTestHTTP,EmptyReferrerAfterValidReferrer)5492 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5493 ASSERT_TRUE(test_server_.Start());
5494
5495 TestDelegate d;
5496 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5497 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
5498 req->SetReferrer("http://foo.com/test#fragment");
5499 req->SetReferrer("");
5500 req->Start();
5501 base::RunLoop().Run();
5502
5503 EXPECT_EQ(std::string("None"), d.data_received());
5504 }
5505
5506 // Defer network start and then resume, checking that the request was a success
5507 // and bytes were received.
TEST_F(URLRequestTestHTTP,DeferredBeforeNetworkStart)5508 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5509 ASSERT_TRUE(test_server_.Start());
5510
5511 TestDelegate d;
5512 {
5513 d.set_quit_on_network_start(true);
5514 GURL test_url(test_server_.GetURL("echo"));
5515 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5516 test_url, DEFAULT_PRIORITY, &d, NULL));
5517
5518 req->Start();
5519 base::RunLoop().Run();
5520
5521 EXPECT_EQ(1, d.received_before_network_start_count());
5522 EXPECT_EQ(0, d.response_started_count());
5523
5524 req->ResumeNetworkStart();
5525 base::RunLoop().Run();
5526
5527 EXPECT_EQ(1, d.response_started_count());
5528 EXPECT_NE(0, d.bytes_received());
5529 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5530 }
5531 }
5532
5533 // Check that OnBeforeNetworkStart is only called once even if there is a
5534 // redirect.
TEST_F(URLRequestTestHTTP,BeforeNetworkStartCalledOnce)5535 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5536 ASSERT_TRUE(test_server_.Start());
5537
5538 TestDelegate d;
5539 {
5540 d.set_quit_on_redirect(true);
5541 d.set_quit_on_network_start(true);
5542 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5543 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d,
5544 NULL));
5545
5546 req->Start();
5547 base::RunLoop().Run();
5548
5549 EXPECT_EQ(1, d.received_before_network_start_count());
5550 EXPECT_EQ(0, d.response_started_count());
5551 EXPECT_EQ(0, d.received_redirect_count());
5552
5553 req->ResumeNetworkStart();
5554 base::RunLoop().Run();
5555
5556 EXPECT_EQ(1, d.received_redirect_count());
5557 req->FollowDeferredRedirect();
5558 base::RunLoop().Run();
5559
5560 // Check that the redirect's new network transaction does not get propagated
5561 // to a second OnBeforeNetworkStart() notification.
5562 EXPECT_EQ(1, d.received_before_network_start_count());
5563
5564 EXPECT_EQ(1, d.response_started_count());
5565 EXPECT_NE(0, d.bytes_received());
5566 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5567 }
5568 }
5569
5570 // Cancel the request after learning that the request would use the network.
TEST_F(URLRequestTestHTTP,CancelOnBeforeNetworkStart)5571 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5572 ASSERT_TRUE(test_server_.Start());
5573
5574 TestDelegate d;
5575 {
5576 d.set_quit_on_network_start(true);
5577 GURL test_url(test_server_.GetURL("echo"));
5578 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5579 test_url, DEFAULT_PRIORITY, &d, NULL));
5580
5581 req->Start();
5582 base::RunLoop().Run();
5583
5584 EXPECT_EQ(1, d.received_before_network_start_count());
5585 EXPECT_EQ(0, d.response_started_count());
5586
5587 req->Cancel();
5588 base::RunLoop().Run();
5589
5590 EXPECT_EQ(1, d.response_started_count());
5591 EXPECT_EQ(0, d.bytes_received());
5592 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
5593 }
5594 }
5595
TEST_F(URLRequestTestHTTP,CancelRedirect)5596 TEST_F(URLRequestTestHTTP, CancelRedirect) {
5597 ASSERT_TRUE(test_server_.Start());
5598
5599 TestDelegate d;
5600 {
5601 d.set_cancel_in_received_redirect(true);
5602 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5603 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
5604 NULL));
5605 req->Start();
5606 base::RunLoop().Run();
5607
5608 EXPECT_EQ(1, d.response_started_count());
5609 EXPECT_EQ(0, d.bytes_received());
5610 EXPECT_FALSE(d.received_data_before_response());
5611 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
5612 }
5613 }
5614
TEST_F(URLRequestTestHTTP,DeferredRedirect)5615 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5616 ASSERT_TRUE(test_server_.Start());
5617
5618 TestDelegate d;
5619 {
5620 d.set_quit_on_redirect(true);
5621 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5622 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5623 test_url, DEFAULT_PRIORITY, &d, NULL));
5624
5625 req->Start();
5626 base::RunLoop().Run();
5627
5628 EXPECT_EQ(1, d.received_redirect_count());
5629
5630 req->FollowDeferredRedirect();
5631 base::RunLoop().Run();
5632
5633 EXPECT_EQ(1, d.response_started_count());
5634 EXPECT_FALSE(d.received_data_before_response());
5635 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5636
5637 base::FilePath path;
5638 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5639 path = path.Append(FILE_PATH_LITERAL("net"));
5640 path = path.Append(FILE_PATH_LITERAL("data"));
5641 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5642 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5643
5644 std::string contents;
5645 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5646 EXPECT_EQ(contents, d.data_received());
5647 }
5648 }
5649
TEST_F(URLRequestTestHTTP,DeferredRedirect_GetFullRequestHeaders)5650 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5651 ASSERT_TRUE(test_server_.Start());
5652
5653 TestDelegate d;
5654 {
5655 d.set_quit_on_redirect(true);
5656 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5657 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5658 test_url, DEFAULT_PRIORITY, &d, NULL));
5659
5660 EXPECT_FALSE(d.have_full_request_headers());
5661
5662 req->Start();
5663 base::RunLoop().Run();
5664
5665 EXPECT_EQ(1, d.received_redirect_count());
5666 EXPECT_TRUE(d.have_full_request_headers());
5667 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5668 d.ClearFullRequestHeaders();
5669
5670 req->FollowDeferredRedirect();
5671 base::RunLoop().Run();
5672
5673 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5674 EXPECT_EQ(1, d.response_started_count());
5675 EXPECT_TRUE(d.have_full_request_headers());
5676 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5677 EXPECT_FALSE(d.received_data_before_response());
5678 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5679
5680 base::FilePath path;
5681 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5682 path = path.Append(FILE_PATH_LITERAL("net"));
5683 path = path.Append(FILE_PATH_LITERAL("data"));
5684 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5685 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5686
5687 std::string contents;
5688 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5689 EXPECT_EQ(contents, d.data_received());
5690 }
5691 }
5692
TEST_F(URLRequestTestHTTP,CancelDeferredRedirect)5693 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5694 ASSERT_TRUE(test_server_.Start());
5695
5696 TestDelegate d;
5697 {
5698 d.set_quit_on_redirect(true);
5699 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5700 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
5701 NULL));
5702 req->Start();
5703 base::RunLoop().Run();
5704
5705 EXPECT_EQ(1, d.received_redirect_count());
5706
5707 req->Cancel();
5708 base::RunLoop().Run();
5709
5710 EXPECT_EQ(1, d.response_started_count());
5711 EXPECT_EQ(0, d.bytes_received());
5712 EXPECT_FALSE(d.received_data_before_response());
5713 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
5714 }
5715 }
5716
TEST_F(URLRequestTestHTTP,VaryHeader)5717 TEST_F(URLRequestTestHTTP, VaryHeader) {
5718 ASSERT_TRUE(test_server_.Start());
5719
5720 // Populate the cache.
5721 {
5722 TestDelegate d;
5723 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5724 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
5725 NULL));
5726 HttpRequestHeaders headers;
5727 headers.SetHeader("foo", "1");
5728 req->SetExtraRequestHeaders(headers);
5729 req->Start();
5730 base::RunLoop().Run();
5731
5732 LoadTimingInfo load_timing_info;
5733 req->GetLoadTimingInfo(&load_timing_info);
5734 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5735 }
5736
5737 // Expect a cache hit.
5738 {
5739 TestDelegate d;
5740 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5741 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
5742 NULL));
5743 HttpRequestHeaders headers;
5744 headers.SetHeader("foo", "1");
5745 req->SetExtraRequestHeaders(headers);
5746 req->Start();
5747 base::RunLoop().Run();
5748
5749 EXPECT_TRUE(req->was_cached());
5750
5751 LoadTimingInfo load_timing_info;
5752 req->GetLoadTimingInfo(&load_timing_info);
5753 TestLoadTimingCacheHitNoNetwork(load_timing_info);
5754 }
5755
5756 // Expect a cache miss.
5757 {
5758 TestDelegate d;
5759 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5760 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
5761 NULL));
5762 HttpRequestHeaders headers;
5763 headers.SetHeader("foo", "2");
5764 req->SetExtraRequestHeaders(headers);
5765 req->Start();
5766 base::RunLoop().Run();
5767
5768 EXPECT_FALSE(req->was_cached());
5769
5770 LoadTimingInfo load_timing_info;
5771 req->GetLoadTimingInfo(&load_timing_info);
5772 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5773 }
5774 }
5775
TEST_F(URLRequestTestHTTP,BasicAuth)5776 TEST_F(URLRequestTestHTTP, BasicAuth) {
5777 ASSERT_TRUE(test_server_.Start());
5778
5779 // populate the cache
5780 {
5781 TestDelegate d;
5782 d.set_credentials(AuthCredentials(kUser, kSecret));
5783
5784 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5785 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
5786 r->Start();
5787
5788 base::RunLoop().Run();
5789
5790 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5791 }
5792
5793 // repeat request with end-to-end validation. since auth-basic results in a
5794 // cachable page, we expect this test to result in a 304. in which case, the
5795 // response should be fetched from the cache.
5796 {
5797 TestDelegate d;
5798 d.set_credentials(AuthCredentials(kUser, kSecret));
5799
5800 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5801 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
5802 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
5803 r->Start();
5804
5805 base::RunLoop().Run();
5806
5807 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5808
5809 // Should be the same cached document.
5810 EXPECT_TRUE(r->was_cached());
5811 }
5812 }
5813
5814 // Check that Set-Cookie headers in 401 responses are respected.
5815 // http://crbug.com/6450
TEST_F(URLRequestTestHTTP,BasicAuthWithCookies)5816 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5817 ASSERT_TRUE(test_server_.Start());
5818
5819 GURL url_requiring_auth =
5820 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5821
5822 // Request a page that will give a 401 containing a Set-Cookie header.
5823 // Verify that when the transaction is restarted, it includes the new cookie.
5824 {
5825 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5826 TestURLRequestContext context(true);
5827 context.set_network_delegate(&network_delegate);
5828 context.Init();
5829
5830 TestDelegate d;
5831 d.set_credentials(AuthCredentials(kUser, kSecret));
5832
5833 scoped_ptr<URLRequest> r(context.CreateRequest(
5834 url_requiring_auth, DEFAULT_PRIORITY, &d, NULL));
5835 r->Start();
5836
5837 base::RunLoop().Run();
5838
5839 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5840
5841 // Make sure we sent the cookie in the restarted transaction.
5842 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5843 != std::string::npos);
5844 }
5845
5846 // Same test as above, except this time the restart is initiated earlier
5847 // (without user intervention since identity is embedded in the URL).
5848 {
5849 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5850 TestURLRequestContext context(true);
5851 context.set_network_delegate(&network_delegate);
5852 context.Init();
5853
5854 TestDelegate d;
5855
5856 GURL::Replacements replacements;
5857 std::string username("user2");
5858 std::string password("secret");
5859 replacements.SetUsernameStr(username);
5860 replacements.SetPasswordStr(password);
5861 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5862
5863 scoped_ptr<URLRequest> r(context.CreateRequest(
5864 url_with_identity, DEFAULT_PRIORITY, &d, NULL));
5865 r->Start();
5866
5867 base::RunLoop().Run();
5868
5869 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5870
5871 // Make sure we sent the cookie in the restarted transaction.
5872 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5873 != std::string::npos);
5874 }
5875 }
5876
5877 // Tests that load timing works as expected with auth and the cache.
TEST_F(URLRequestTestHTTP,BasicAuthLoadTiming)5878 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5879 ASSERT_TRUE(test_server_.Start());
5880
5881 // populate the cache
5882 {
5883 TestDelegate d;
5884 d.set_credentials(AuthCredentials(kUser, kSecret));
5885
5886 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5887 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
5888 r->Start();
5889
5890 base::RunLoop().Run();
5891
5892 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5893
5894 LoadTimingInfo load_timing_info_before_auth;
5895 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5896 &load_timing_info_before_auth));
5897 TestLoadTimingNotReused(load_timing_info_before_auth,
5898 CONNECT_TIMING_HAS_DNS_TIMES);
5899
5900 LoadTimingInfo load_timing_info;
5901 r->GetLoadTimingInfo(&load_timing_info);
5902 // The test server does not support keep alive sockets, so the second
5903 // request with auth should use a new socket.
5904 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5905 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5906 load_timing_info.socket_log_id);
5907 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5908 load_timing_info.connect_timing.connect_start);
5909 }
5910
5911 // Repeat request with end-to-end validation. Since auth-basic results in a
5912 // cachable page, we expect this test to result in a 304. In which case, the
5913 // response should be fetched from the cache.
5914 {
5915 TestDelegate d;
5916 d.set_credentials(AuthCredentials(kUser, kSecret));
5917
5918 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5919 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
5920 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
5921 r->Start();
5922
5923 base::RunLoop().Run();
5924
5925 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5926
5927 // Should be the same cached document.
5928 EXPECT_TRUE(r->was_cached());
5929
5930 // Since there was a request that went over the wire, the load timing
5931 // information should include connection times.
5932 LoadTimingInfo load_timing_info;
5933 r->GetLoadTimingInfo(&load_timing_info);
5934 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5935 }
5936 }
5937
5938 // In this test, we do a POST which the server will 302 redirect.
5939 // The subsequent transaction should use GET, and should not send the
5940 // Content-Type header.
5941 // http://code.google.com/p/chromium/issues/detail?id=843
TEST_F(URLRequestTestHTTP,Post302RedirectGet)5942 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5943 ASSERT_TRUE(test_server_.Start());
5944
5945 const char kData[] = "hello world";
5946
5947 TestDelegate d;
5948 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5949 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
5950 NULL));
5951 req->set_method("POST");
5952 req->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
5953
5954 // Set headers (some of which are specific to the POST).
5955 HttpRequestHeaders headers;
5956 headers.AddHeadersFromString(
5957 "Content-Type: multipart/form-data; "
5958 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5959 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5960 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5961 "Accept-Language: en-US,en\r\n"
5962 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5963 "Content-Length: 11\r\n"
5964 "Origin: http://localhost:1337/");
5965 req->SetExtraRequestHeaders(headers);
5966 req->Start();
5967 base::RunLoop().Run();
5968
5969 std::string mime_type;
5970 req->GetMimeType(&mime_type);
5971 EXPECT_EQ("text/html", mime_type);
5972
5973 const std::string& data = d.data_received();
5974
5975 // Check that the post-specific headers were stripped:
5976 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
5977 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
5978 EXPECT_FALSE(ContainsString(data, "Origin:"));
5979
5980 // These extra request headers should not have been stripped.
5981 EXPECT_TRUE(ContainsString(data, "Accept:"));
5982 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
5983 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
5984 }
5985
5986 // The following tests check that we handle mutating the request method for
5987 // HTTP redirects as expected.
5988 // See http://crbug.com/56373 and http://crbug.com/102130.
5989
TEST_F(URLRequestTestHTTP,Redirect301Tests)5990 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
5991 ASSERT_TRUE(test_server_.Start());
5992
5993 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
5994
5995 HTTPRedirectMethodTest(url, "POST", "GET", true);
5996 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5997 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5998 }
5999
TEST_F(URLRequestTestHTTP,Redirect302Tests)6000 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6001 ASSERT_TRUE(test_server_.Start());
6002
6003 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6004
6005 HTTPRedirectMethodTest(url, "POST", "GET", true);
6006 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6007 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6008 }
6009
TEST_F(URLRequestTestHTTP,Redirect303Tests)6010 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6011 ASSERT_TRUE(test_server_.Start());
6012
6013 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6014
6015 HTTPRedirectMethodTest(url, "POST", "GET", true);
6016 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6017 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6018 }
6019
TEST_F(URLRequestTestHTTP,Redirect307Tests)6020 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6021 ASSERT_TRUE(test_server_.Start());
6022
6023 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6024
6025 HTTPRedirectMethodTest(url, "POST", "POST", true);
6026 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6027 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6028 }
6029
TEST_F(URLRequestTestHTTP,Redirect308Tests)6030 TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6031 ASSERT_TRUE(test_server_.Start());
6032
6033 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6034
6035 HTTPRedirectMethodTest(url, "POST", "POST", true);
6036 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6037 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6038 }
6039
6040 // Make sure that 308 responses without bodies are not treated as redirects.
6041 // Certain legacy apis that pre-date the response code expect this behavior
6042 // (Like Google Drive).
TEST_F(URLRequestTestHTTP,NoRedirectOn308WithoutLocationHeader)6043 TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6044 ASSERT_TRUE(test_server_.Start());
6045
6046 TestDelegate d;
6047 const GURL url = test_server_.GetURL("files/308-without-location-header");
6048
6049 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
6050 url, DEFAULT_PRIORITY, &d, NULL));
6051
6052 request->Start();
6053 base::RunLoop().Run();
6054 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6055 EXPECT_EQ(OK, request->status().error());
6056 EXPECT_EQ(0, d.received_redirect_count());
6057 EXPECT_EQ(308, request->response_headers()->response_code());
6058 EXPECT_EQ("This is not a redirect.", d.data_received());
6059 }
6060
TEST_F(URLRequestTestHTTP,Redirect302PreserveReferenceFragment)6061 TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6062 ASSERT_TRUE(test_server_.Start());
6063
6064 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6065 GURL expected_url(test_server_.GetURL("echo#fragment"));
6066
6067 TestDelegate d;
6068 {
6069 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6070 original_url, DEFAULT_PRIORITY, &d, NULL));
6071
6072 r->Start();
6073 base::RunLoop().Run();
6074
6075 EXPECT_EQ(2U, r->url_chain().size());
6076 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6077 EXPECT_EQ(OK, r->status().error());
6078 EXPECT_EQ(original_url, r->original_url());
6079 EXPECT_EQ(expected_url, r->url());
6080 }
6081 }
6082
TEST_F(URLRequestTestHTTP,RedirectPreserveFirstPartyURL)6083 TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6084 ASSERT_TRUE(test_server_.Start());
6085
6086 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6087 GURL first_party_url("http://example.com");
6088
6089 TestDelegate d;
6090 {
6091 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6092 url, DEFAULT_PRIORITY, &d, NULL));
6093 r->set_first_party_for_cookies(first_party_url);
6094
6095 r->Start();
6096 base::RunLoop().Run();
6097
6098 EXPECT_EQ(2U, r->url_chain().size());
6099 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6100 EXPECT_EQ(OK, r->status().error());
6101 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
6102 }
6103 }
6104
TEST_F(URLRequestTestHTTP,RedirectUpdateFirstPartyURL)6105 TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6106 ASSERT_TRUE(test_server_.Start());
6107
6108 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6109 GURL original_first_party_url("http://example.com");
6110 GURL expected_first_party_url(test_server_.GetURL("echo"));
6111
6112 TestDelegate d;
6113 {
6114 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6115 url, DEFAULT_PRIORITY, &d, NULL));
6116 r->set_first_party_for_cookies(original_first_party_url);
6117 r->set_first_party_url_policy(
6118 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6119
6120 r->Start();
6121 base::RunLoop().Run();
6122
6123 EXPECT_EQ(2U, r->url_chain().size());
6124 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6125 EXPECT_EQ(OK, r->status().error());
6126 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
6127 }
6128 }
6129
TEST_F(URLRequestTestHTTP,InterceptPost302RedirectGet)6130 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6131 ASSERT_TRUE(test_server_.Start());
6132
6133 const char kData[] = "hello world";
6134
6135 TestDelegate d;
6136 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6137 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6138 req->set_method("POST");
6139 req->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6140 HttpRequestHeaders headers;
6141 headers.SetHeader(HttpRequestHeaders::kContentLength,
6142 base::UintToString(arraysize(kData) - 1));
6143 req->SetExtraRequestHeaders(headers);
6144
6145 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6146 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6147 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6148 AddTestInterceptor()->set_main_intercept_job(job);
6149
6150 req->Start();
6151 base::RunLoop().Run();
6152 EXPECT_EQ("GET", req->method());
6153 }
6154
TEST_F(URLRequestTestHTTP,InterceptPost307RedirectPost)6155 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6156 ASSERT_TRUE(test_server_.Start());
6157
6158 const char kData[] = "hello world";
6159
6160 TestDelegate d;
6161 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6162 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6163 req->set_method("POST");
6164 req->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6165 HttpRequestHeaders headers;
6166 headers.SetHeader(HttpRequestHeaders::kContentLength,
6167 base::UintToString(arraysize(kData) - 1));
6168 req->SetExtraRequestHeaders(headers);
6169
6170 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6171 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6172 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6173 "Very Good Reason");
6174 AddTestInterceptor()->set_main_intercept_job(job);
6175
6176 req->Start();
6177 base::RunLoop().Run();
6178 EXPECT_EQ("POST", req->method());
6179 EXPECT_EQ(kData, d.data_received());
6180 }
6181
6182 // Check that default A-L header is sent.
TEST_F(URLRequestTestHTTP,DefaultAcceptLanguage)6183 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6184 ASSERT_TRUE(test_server_.Start());
6185
6186 StaticHttpUserAgentSettings settings("en", std::string());
6187 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6188 TestURLRequestContext context(true);
6189 context.set_network_delegate(&network_delegate);
6190 context.set_http_user_agent_settings(&settings);
6191 context.Init();
6192
6193 TestDelegate d;
6194 scoped_ptr<URLRequest> req(context.CreateRequest(
6195 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6196 NULL));
6197 req->Start();
6198 base::RunLoop().Run();
6199 EXPECT_EQ("en", d.data_received());
6200 }
6201
6202 // Check that an empty A-L header is not sent. http://crbug.com/77365.
TEST_F(URLRequestTestHTTP,EmptyAcceptLanguage)6203 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6204 ASSERT_TRUE(test_server_.Start());
6205
6206 std::string empty_string; // Avoid most vexing parse on line below.
6207 StaticHttpUserAgentSettings settings(empty_string, empty_string);
6208 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6209 TestURLRequestContext context(true);
6210 context.set_network_delegate(&network_delegate);
6211 context.Init();
6212 // We override the language after initialization because empty entries
6213 // get overridden by Init().
6214 context.set_http_user_agent_settings(&settings);
6215
6216 TestDelegate d;
6217 scoped_ptr<URLRequest> req(context.CreateRequest(
6218 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6219 NULL));
6220 req->Start();
6221 base::RunLoop().Run();
6222 EXPECT_EQ("None", d.data_received());
6223 }
6224
6225 // Check that if request overrides the A-L header, the default is not appended.
6226 // See http://crbug.com/20894
TEST_F(URLRequestTestHTTP,OverrideAcceptLanguage)6227 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6228 ASSERT_TRUE(test_server_.Start());
6229
6230 TestDelegate d;
6231 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6232 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6233 NULL));
6234 HttpRequestHeaders headers;
6235 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6236 req->SetExtraRequestHeaders(headers);
6237 req->Start();
6238 base::RunLoop().Run();
6239 EXPECT_EQ(std::string("ru"), d.data_received());
6240 }
6241
6242 // Check that default A-E header is sent.
TEST_F(URLRequestTestHTTP,DefaultAcceptEncoding)6243 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6244 ASSERT_TRUE(test_server_.Start());
6245
6246 TestDelegate d;
6247 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6248 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6249 NULL));
6250 HttpRequestHeaders headers;
6251 req->SetExtraRequestHeaders(headers);
6252 req->Start();
6253 base::RunLoop().Run();
6254 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6255 }
6256
6257 // Check that if request overrides the A-E header, the default is not appended.
6258 // See http://crbug.com/47381
TEST_F(URLRequestTestHTTP,OverrideAcceptEncoding)6259 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6260 ASSERT_TRUE(test_server_.Start());
6261
6262 TestDelegate d;
6263 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6264 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6265 NULL));
6266 HttpRequestHeaders headers;
6267 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6268 req->SetExtraRequestHeaders(headers);
6269 req->Start();
6270 base::RunLoop().Run();
6271 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6272 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6273 }
6274
6275 // Check that setting the A-C header sends the proper header.
TEST_F(URLRequestTestHTTP,SetAcceptCharset)6276 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
6277 ASSERT_TRUE(test_server_.Start());
6278
6279 TestDelegate d;
6280 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6281 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d,
6282 NULL));
6283 HttpRequestHeaders headers;
6284 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6285 req->SetExtraRequestHeaders(headers);
6286 req->Start();
6287 base::RunLoop().Run();
6288 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6289 }
6290
6291 // Check that default User-Agent header is sent.
TEST_F(URLRequestTestHTTP,DefaultUserAgent)6292 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6293 ASSERT_TRUE(test_server_.Start());
6294
6295 TestDelegate d;
6296 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6297 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6298 NULL));
6299 req->Start();
6300 base::RunLoop().Run();
6301 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
6302 d.data_received());
6303 }
6304
6305 // Check that if request overrides the User-Agent header,
6306 // the default is not appended.
TEST_F(URLRequestTestHTTP,OverrideUserAgent)6307 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6308 ASSERT_TRUE(test_server_.Start());
6309
6310 TestDelegate d;
6311 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6312 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6313 NULL));
6314 HttpRequestHeaders headers;
6315 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6316 req->SetExtraRequestHeaders(headers);
6317 req->Start();
6318 base::RunLoop().Run();
6319 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
6320 }
6321
6322 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6323 // User-Agent header to be sent but does not send the Accept-Language and
6324 // Accept-Charset headers.
TEST_F(URLRequestTestHTTP,EmptyHttpUserAgentSettings)6325 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6326 ASSERT_TRUE(test_server_.Start());
6327
6328 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6329 TestURLRequestContext context(true);
6330 context.set_network_delegate(&network_delegate);
6331 context.Init();
6332 // We override the HttpUserAgentSettings after initialization because empty
6333 // entries get overridden by Init().
6334 context.set_http_user_agent_settings(NULL);
6335
6336 struct {
6337 const char* request;
6338 const char* expected_response;
6339 } tests[] = { { "echoheader?Accept-Language", "None" },
6340 { "echoheader?Accept-Charset", "None" },
6341 { "echoheader?User-Agent", "" } };
6342
6343 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
6344 TestDelegate d;
6345 scoped_ptr<URLRequest> req(context.CreateRequest(
6346 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, NULL));
6347 req->Start();
6348 base::RunLoop().Run();
6349 EXPECT_EQ(tests[i].expected_response, d.data_received())
6350 << " Request = \"" << tests[i].request << "\"";
6351 }
6352 }
6353
6354 // Make sure that URLRequest passes on its priority updates to
6355 // newly-created jobs after the first one.
TEST_F(URLRequestTestHTTP,SetSubsequentJobPriority)6356 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6357 ASSERT_TRUE(test_server_.Start());
6358
6359 TestDelegate d;
6360 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6361 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6362 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
6363
6364 scoped_refptr<URLRequestRedirectJob> redirect_job =
6365 new URLRequestRedirectJob(
6366 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
6367 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6368 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
6369
6370 req->SetPriority(LOW);
6371 req->Start();
6372 EXPECT_TRUE(req->is_pending());
6373
6374 scoped_refptr<URLRequestTestJob> job =
6375 new URLRequestTestJob(req.get(), &default_network_delegate_);
6376 AddTestInterceptor()->set_main_intercept_job(job.get());
6377
6378 // Should trigger |job| to be started.
6379 base::RunLoop().Run();
6380 EXPECT_EQ(LOW, job->priority());
6381 }
6382
6383 // Check that creating a network request while entering/exiting suspend mode
6384 // fails as it should. This is the only case where an HttpTransactionFactory
6385 // does not return an HttpTransaction.
TEST_F(URLRequestTestHTTP,NetworkSuspendTest)6386 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6387 // Create a new HttpNetworkLayer that thinks it's suspended.
6388 HttpNetworkSession::Params params;
6389 params.host_resolver = default_context_.host_resolver();
6390 params.cert_verifier = default_context_.cert_verifier();
6391 params.transport_security_state = default_context_.transport_security_state();
6392 params.proxy_service = default_context_.proxy_service();
6393 params.ssl_config_service = default_context_.ssl_config_service();
6394 params.http_auth_handler_factory =
6395 default_context_.http_auth_handler_factory();
6396 params.network_delegate = &default_network_delegate_;
6397 params.http_server_properties = default_context_.http_server_properties();
6398 scoped_ptr<HttpNetworkLayer> network_layer(
6399 new HttpNetworkLayer(new HttpNetworkSession(params)));
6400 network_layer->OnSuspend();
6401
6402 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6403 HttpCache::DefaultBackend::InMemory(0));
6404
6405 TestURLRequestContext context(true);
6406 context.set_http_transaction_factory(&http_cache);
6407 context.Init();
6408
6409 TestDelegate d;
6410 scoped_ptr<URLRequest> req(context.CreateRequest(
6411 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
6412 req->Start();
6413 base::RunLoop().Run();
6414
6415 EXPECT_TRUE(d.request_failed());
6416 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6417 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
6418 }
6419
6420 // Check that creating a network request while entering/exiting suspend mode
6421 // fails as it should in the case there is no cache. This is the only case
6422 // where an HttpTransactionFactory does not return an HttpTransaction.
TEST_F(URLRequestTestHTTP,NetworkSuspendTestNoCache)6423 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6424 // Create a new HttpNetworkLayer that thinks it's suspended.
6425 HttpNetworkSession::Params params;
6426 params.host_resolver = default_context_.host_resolver();
6427 params.cert_verifier = default_context_.cert_verifier();
6428 params.transport_security_state = default_context_.transport_security_state();
6429 params.proxy_service = default_context_.proxy_service();
6430 params.ssl_config_service = default_context_.ssl_config_service();
6431 params.http_auth_handler_factory =
6432 default_context_.http_auth_handler_factory();
6433 params.network_delegate = &default_network_delegate_;
6434 params.http_server_properties = default_context_.http_server_properties();
6435 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6436 network_layer.OnSuspend();
6437
6438 TestURLRequestContext context(true);
6439 context.set_http_transaction_factory(&network_layer);
6440 context.Init();
6441
6442 TestDelegate d;
6443 scoped_ptr<URLRequest> req(context.CreateRequest(
6444 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
6445 req->Start();
6446 base::RunLoop().Run();
6447
6448 EXPECT_TRUE(d.request_failed());
6449 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6450 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
6451 }
6452
6453 class HTTPSRequestTest : public testing::Test {
6454 public:
HTTPSRequestTest()6455 HTTPSRequestTest() : default_context_(true) {
6456 default_context_.set_network_delegate(&default_network_delegate_);
6457 default_context_.Init();
6458 }
~HTTPSRequestTest()6459 virtual ~HTTPSRequestTest() {}
6460
6461 protected:
6462 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
6463 TestURLRequestContext default_context_;
6464 };
6465
TEST_F(HTTPSRequestTest,HTTPSGetTest)6466 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
6467 SpawnedTestServer test_server(
6468 SpawnedTestServer::TYPE_HTTPS,
6469 SpawnedTestServer::kLocalhost,
6470 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6471 ASSERT_TRUE(test_server.Start());
6472
6473 TestDelegate d;
6474 {
6475 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6476 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
6477 r->Start();
6478 EXPECT_TRUE(r->is_pending());
6479
6480 base::RunLoop().Run();
6481
6482 EXPECT_EQ(1, d.response_started_count());
6483 EXPECT_FALSE(d.received_data_before_response());
6484 EXPECT_NE(0, d.bytes_received());
6485 CheckSSLInfo(r->ssl_info());
6486 EXPECT_EQ(test_server.host_port_pair().host(),
6487 r->GetSocketAddress().host());
6488 EXPECT_EQ(test_server.host_port_pair().port(),
6489 r->GetSocketAddress().port());
6490 }
6491 }
6492
TEST_F(HTTPSRequestTest,HTTPSMismatchedTest)6493 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
6494 SpawnedTestServer::SSLOptions ssl_options(
6495 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6496 SpawnedTestServer test_server(
6497 SpawnedTestServer::TYPE_HTTPS,
6498 ssl_options,
6499 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6500 ASSERT_TRUE(test_server.Start());
6501
6502 bool err_allowed = true;
6503 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6504 TestDelegate d;
6505 {
6506 d.set_allow_certificate_errors(err_allowed);
6507 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6508 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
6509
6510 r->Start();
6511 EXPECT_TRUE(r->is_pending());
6512
6513 base::RunLoop().Run();
6514
6515 EXPECT_EQ(1, d.response_started_count());
6516 EXPECT_FALSE(d.received_data_before_response());
6517 EXPECT_TRUE(d.have_certificate_errors());
6518 if (err_allowed) {
6519 EXPECT_NE(0, d.bytes_received());
6520 CheckSSLInfo(r->ssl_info());
6521 } else {
6522 EXPECT_EQ(0, d.bytes_received());
6523 }
6524 }
6525 }
6526 }
6527
TEST_F(HTTPSRequestTest,HTTPSExpiredTest)6528 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
6529 SpawnedTestServer::SSLOptions ssl_options(
6530 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6531 SpawnedTestServer test_server(
6532 SpawnedTestServer::TYPE_HTTPS,
6533 ssl_options,
6534 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6535 ASSERT_TRUE(test_server.Start());
6536
6537 // Iterate from false to true, just so that we do the opposite of the
6538 // previous test in order to increase test coverage.
6539 bool err_allowed = false;
6540 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6541 TestDelegate d;
6542 {
6543 d.set_allow_certificate_errors(err_allowed);
6544 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6545 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
6546
6547 r->Start();
6548 EXPECT_TRUE(r->is_pending());
6549
6550 base::RunLoop().Run();
6551
6552 EXPECT_EQ(1, d.response_started_count());
6553 EXPECT_FALSE(d.received_data_before_response());
6554 EXPECT_TRUE(d.have_certificate_errors());
6555 if (err_allowed) {
6556 EXPECT_NE(0, d.bytes_received());
6557 CheckSSLInfo(r->ssl_info());
6558 } else {
6559 EXPECT_EQ(0, d.bytes_received());
6560 }
6561 }
6562 }
6563 }
6564
6565 // This tests that a load of www.google.com with a certificate error sets
6566 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
6567 // the interstitial to be fatal.
TEST_F(HTTPSRequestTest,HTTPSPreloadedHSTSTest)6568 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
6569 SpawnedTestServer::SSLOptions ssl_options(
6570 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6571 SpawnedTestServer test_server(
6572 SpawnedTestServer::TYPE_HTTPS,
6573 ssl_options,
6574 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6575 ASSERT_TRUE(test_server.Start());
6576
6577 // We require that the URL be www.google.com in order to pick up the
6578 // preloaded HSTS entries in the TransportSecurityState. This means that we
6579 // have to use a MockHostResolver in order to direct www.google.com to the
6580 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6581
6582 MockHostResolver host_resolver;
6583 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6584 TestURLRequestContext context(true);
6585 context.set_network_delegate(&network_delegate);
6586 context.set_host_resolver(&host_resolver);
6587 TransportSecurityState transport_security_state;
6588 context.set_transport_security_state(&transport_security_state);
6589 context.Init();
6590
6591 TestDelegate d;
6592 scoped_ptr<URLRequest> r(context.CreateRequest(
6593 GURL(base::StringPrintf("https://www.google.com:%d",
6594 test_server.host_port_pair().port())),
6595 DEFAULT_PRIORITY, &d, NULL));
6596
6597 r->Start();
6598 EXPECT_TRUE(r->is_pending());
6599
6600 base::RunLoop().Run();
6601
6602 EXPECT_EQ(1, d.response_started_count());
6603 EXPECT_FALSE(d.received_data_before_response());
6604 EXPECT_TRUE(d.have_certificate_errors());
6605 EXPECT_TRUE(d.certificate_errors_are_fatal());
6606 }
6607
6608 // This tests that cached HTTPS page loads do not cause any updates to the
6609 // TransportSecurityState.
TEST_F(HTTPSRequestTest,HTTPSErrorsNoClobberTSSTest)6610 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6611 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6612 // matter. It just has to be any error.
6613 SpawnedTestServer::SSLOptions ssl_options(
6614 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6615 SpawnedTestServer test_server(
6616 SpawnedTestServer::TYPE_HTTPS,
6617 ssl_options,
6618 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6619 ASSERT_TRUE(test_server.Start());
6620
6621 // We require that the URL be www.google.com in order to pick up the static
6622 // and dynamic STS and PKP entries in the TransportSecurityState. This means
6623 // that we have to use a MockHostResolver in order to direct www.google.com to
6624 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6625
6626 MockHostResolver host_resolver;
6627 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6628 TestURLRequestContext context(true);
6629 context.set_network_delegate(&network_delegate);
6630 context.set_host_resolver(&host_resolver);
6631 TransportSecurityState transport_security_state;
6632
6633 TransportSecurityState::DomainState static_domain_state;
6634 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6635 "www.google.com", &static_domain_state));
6636 context.set_transport_security_state(&transport_security_state);
6637 context.Init();
6638
6639 TransportSecurityState::DomainState dynamic_domain_state;
6640 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6641 "www.google.com", &dynamic_domain_state));
6642
6643 TestDelegate d;
6644 scoped_ptr<URLRequest> r(context.CreateRequest(
6645 GURL(base::StringPrintf("https://www.google.com:%d",
6646 test_server.host_port_pair().port())),
6647 DEFAULT_PRIORITY, &d, NULL));
6648
6649 r->Start();
6650 EXPECT_TRUE(r->is_pending());
6651
6652 base::RunLoop().Run();
6653
6654 EXPECT_EQ(1, d.response_started_count());
6655 EXPECT_FALSE(d.received_data_before_response());
6656 EXPECT_TRUE(d.have_certificate_errors());
6657 EXPECT_TRUE(d.certificate_errors_are_fatal());
6658
6659 // Get a fresh copy of the states, and check that they haven't changed.
6660 TransportSecurityState::DomainState new_static_domain_state;
6661 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6662 "www.google.com", &new_static_domain_state));
6663 TransportSecurityState::DomainState new_dynamic_domain_state;
6664 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6665 "www.google.com", &new_dynamic_domain_state));
6666
6667 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
6668 static_domain_state.sts.upgrade_mode);
6669 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
6670 static_domain_state.sts.include_subdomains);
6671 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
6672 static_domain_state.pkp.include_subdomains);
6673 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
6674 static_domain_state.pkp.spki_hashes));
6675 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
6676 static_domain_state.pkp.bad_spki_hashes));
6677 }
6678
6679 // Make sure HSTS preserves a POST request's method and body.
TEST_F(HTTPSRequestTest,HSTSPreservesPosts)6680 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6681 static const char kData[] = "hello world";
6682
6683 SpawnedTestServer::SSLOptions ssl_options(
6684 SpawnedTestServer::SSLOptions::CERT_OK);
6685 SpawnedTestServer test_server(
6686 SpawnedTestServer::TYPE_HTTPS,
6687 ssl_options,
6688 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6689 ASSERT_TRUE(test_server.Start());
6690
6691
6692 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6693 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
6694 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6695 // to 127.0.0.1.
6696 MockHostResolver host_resolver;
6697
6698 // Force https for www.somewhere.com.
6699 TransportSecurityState transport_security_state;
6700 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6701 bool include_subdomains = false;
6702 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6703 include_subdomains);
6704
6705 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6706
6707 TestURLRequestContext context(true);
6708 context.set_host_resolver(&host_resolver);
6709 context.set_transport_security_state(&transport_security_state);
6710 context.set_network_delegate(&network_delegate);
6711 context.Init();
6712
6713 TestDelegate d;
6714 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6715 // cause a certificate error. Ignore the error.
6716 d.set_allow_certificate_errors(true);
6717
6718 scoped_ptr<URLRequest> req(context.CreateRequest(
6719 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6720 test_server.host_port_pair().port())),
6721 DEFAULT_PRIORITY, &d, NULL));
6722 req->set_method("POST");
6723 req->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6724
6725 req->Start();
6726 base::RunLoop().Run();
6727
6728 EXPECT_EQ("https", req->url().scheme());
6729 EXPECT_EQ("POST", req->method());
6730 EXPECT_EQ(kData, d.data_received());
6731
6732 LoadTimingInfo load_timing_info;
6733 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6734 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6735 TestLoadTimingCacheHitNoNetwork(load_timing_info);
6736 }
6737
6738 // Make sure that the CORS headers are added to cross-origin HSTS redirects.
TEST_F(HTTPSRequestTest,HSTSCrossOriginAddHeaders)6739 TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
6740 static const char kOriginHeaderValue[] = "http://www.example.com";
6741
6742 SpawnedTestServer::SSLOptions ssl_options(
6743 SpawnedTestServer::SSLOptions::CERT_OK);
6744 SpawnedTestServer test_server(
6745 SpawnedTestServer::TYPE_HTTPS,
6746 ssl_options,
6747 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6748 ASSERT_TRUE(test_server.Start());
6749
6750 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6751 // address, so a MockHostResolver is needed to redirect example.net to the
6752 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
6753 MockHostResolver host_resolver;
6754
6755 TransportSecurityState transport_security_state;
6756 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
6757 bool include_subdomains = false;
6758 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
6759
6760 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6761
6762 MockCertVerifier cert_verifier;
6763 cert_verifier.set_default_result(OK);
6764
6765 TestURLRequestContext context(true);
6766 context.set_host_resolver(&host_resolver);
6767 context.set_transport_security_state(&transport_security_state);
6768 context.set_network_delegate(&network_delegate);
6769 context.set_cert_verifier(&cert_verifier);
6770 context.Init();
6771
6772 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
6773 test_server.host_port_pair().port()));
6774 url::Replacements<char> replacements;
6775 const char kNewScheme[] = "https";
6776 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
6777 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
6778
6779 TestDelegate d;
6780 // Quit on redirect to allow response header inspection upon redirect.
6781 d.set_quit_on_redirect(true);
6782
6783 scoped_ptr<URLRequest> req(context.CreateRequest(hsts_http_url,
6784 DEFAULT_PRIORITY, &d, NULL));
6785 // Set Origin header to simulate a cross-origin request.
6786 HttpRequestHeaders request_headers;
6787 request_headers.SetHeader("Origin", kOriginHeaderValue);
6788 req->SetExtraRequestHeaders(request_headers);
6789
6790 req->Start();
6791 base::RunLoop().Run();
6792
6793 EXPECT_EQ(1, d.received_redirect_count());
6794
6795 const HttpResponseHeaders* headers = req->response_headers();
6796 std::string redirect_location;
6797 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
6798 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
6799
6800 std::string received_cors_header;
6801 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
6802 &received_cors_header));
6803 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
6804 }
6805
6806 namespace {
6807
6808 class SSLClientAuthTestDelegate : public TestDelegate {
6809 public:
SSLClientAuthTestDelegate()6810 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6811 }
OnCertificateRequested(URLRequest * request,SSLCertRequestInfo * cert_request_info)6812 virtual void OnCertificateRequested(
6813 URLRequest* request,
6814 SSLCertRequestInfo* cert_request_info) OVERRIDE {
6815 on_certificate_requested_count_++;
6816 base::MessageLoop::current()->Quit();
6817 }
on_certificate_requested_count()6818 int on_certificate_requested_count() {
6819 return on_certificate_requested_count_;
6820 }
6821 private:
6822 int on_certificate_requested_count_;
6823 };
6824
6825 } // namespace
6826
6827 // TODO(davidben): Test the rest of the code. Specifically,
6828 // - Filtering which certificates to select.
6829 // - Sending a certificate back.
6830 // - Getting a certificate request in an SSL renegotiation sending the
6831 // HTTP request.
TEST_F(HTTPSRequestTest,ClientAuthTest)6832 TEST_F(HTTPSRequestTest, ClientAuthTest) {
6833 SpawnedTestServer::SSLOptions ssl_options;
6834 ssl_options.request_client_certificate = true;
6835 SpawnedTestServer test_server(
6836 SpawnedTestServer::TYPE_HTTPS,
6837 ssl_options,
6838 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6839 ASSERT_TRUE(test_server.Start());
6840
6841 SSLClientAuthTestDelegate d;
6842 {
6843 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6844 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
6845
6846 r->Start();
6847 EXPECT_TRUE(r->is_pending());
6848
6849 base::RunLoop().Run();
6850
6851 EXPECT_EQ(1, d.on_certificate_requested_count());
6852 EXPECT_FALSE(d.received_data_before_response());
6853 EXPECT_EQ(0, d.bytes_received());
6854
6855 // Send no certificate.
6856 // TODO(davidben): Get temporary client cert import (with keys) working on
6857 // all platforms so we can test sending a cert as well.
6858 r->ContinueWithCertificate(NULL);
6859
6860 base::RunLoop().Run();
6861
6862 EXPECT_EQ(1, d.response_started_count());
6863 EXPECT_FALSE(d.received_data_before_response());
6864 EXPECT_NE(0, d.bytes_received());
6865 }
6866 }
6867
TEST_F(HTTPSRequestTest,ResumeTest)6868 TEST_F(HTTPSRequestTest, ResumeTest) {
6869 // Test that we attempt a session resume when making two connections to the
6870 // same host.
6871 SpawnedTestServer::SSLOptions ssl_options;
6872 ssl_options.record_resume = true;
6873 SpawnedTestServer test_server(
6874 SpawnedTestServer::TYPE_HTTPS,
6875 ssl_options,
6876 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6877 ASSERT_TRUE(test_server.Start());
6878
6879 SSLClientSocket::ClearSessionCache();
6880
6881 {
6882 TestDelegate d;
6883 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6884 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
6885
6886 r->Start();
6887 EXPECT_TRUE(r->is_pending());
6888
6889 base::RunLoop().Run();
6890
6891 EXPECT_EQ(1, d.response_started_count());
6892 }
6893
6894 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6895 CloseAllConnections();
6896
6897 {
6898 TestDelegate d;
6899 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6900 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
6901
6902 r->Start();
6903 EXPECT_TRUE(r->is_pending());
6904
6905 base::RunLoop().Run();
6906
6907 // The response will look like;
6908 // insert abc
6909 // lookup abc
6910 // insert xyz
6911 //
6912 // With a newline at the end which makes the split think that there are
6913 // four lines.
6914
6915 EXPECT_EQ(1, d.response_started_count());
6916 std::vector<std::string> lines;
6917 base::SplitString(d.data_received(), '\n', &lines);
6918 ASSERT_EQ(4u, lines.size()) << d.data_received();
6919
6920 std::string session_id;
6921
6922 for (size_t i = 0; i < 2; i++) {
6923 std::vector<std::string> parts;
6924 base::SplitString(lines[i], '\t', &parts);
6925 ASSERT_EQ(2u, parts.size());
6926 if (i == 0) {
6927 EXPECT_EQ("insert", parts[0]);
6928 session_id = parts[1];
6929 } else {
6930 EXPECT_EQ("lookup", parts[0]);
6931 EXPECT_EQ(session_id, parts[1]);
6932 }
6933 }
6934 }
6935 }
6936
6937 // AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
6938 // the result of fetching "ssl-session-cache" from the test server, indicates
6939 // that exactly two different sessions were inserted, with no lookups etc.
AssertTwoDistinctSessionsInserted(const string & session_info)6940 static void AssertTwoDistinctSessionsInserted(const string& session_info) {
6941 std::vector<std::string> lines;
6942 base::SplitString(session_info, '\n', &lines);
6943 ASSERT_EQ(3u, lines.size()) << session_info;
6944
6945 std::string session_id;
6946 for (size_t i = 0; i < 2; i++) {
6947 std::vector<std::string> parts;
6948 base::SplitString(lines[i], '\t', &parts);
6949 ASSERT_EQ(2u, parts.size());
6950 EXPECT_EQ("insert", parts[0]);
6951 if (i == 0) {
6952 session_id = parts[1];
6953 } else {
6954 EXPECT_NE(session_id, parts[1]);
6955 }
6956 }
6957 }
6958
TEST_F(HTTPSRequestTest,SSLSessionCacheShardTest)6959 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6960 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6961 // differs.
6962 SpawnedTestServer::SSLOptions ssl_options;
6963 ssl_options.record_resume = true;
6964 SpawnedTestServer test_server(
6965 SpawnedTestServer::TYPE_HTTPS,
6966 ssl_options,
6967 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6968 ASSERT_TRUE(test_server.Start());
6969
6970 SSLClientSocket::ClearSessionCache();
6971
6972 {
6973 TestDelegate d;
6974 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6975 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
6976
6977 r->Start();
6978 EXPECT_TRUE(r->is_pending());
6979
6980 base::RunLoop().Run();
6981
6982 EXPECT_EQ(1, d.response_started_count());
6983 }
6984
6985 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6986 HttpNetworkSession::Params params;
6987 params.host_resolver = default_context_.host_resolver();
6988 params.cert_verifier = default_context_.cert_verifier();
6989 params.transport_security_state = default_context_.transport_security_state();
6990 params.proxy_service = default_context_.proxy_service();
6991 params.ssl_config_service = default_context_.ssl_config_service();
6992 params.http_auth_handler_factory =
6993 default_context_.http_auth_handler_factory();
6994 params.network_delegate = &default_network_delegate_;
6995 params.http_server_properties = default_context_.http_server_properties();
6996 params.ssl_session_cache_shard = "alternate";
6997
6998 scoped_ptr<HttpCache> cache(new HttpCache(
6999 new HttpNetworkSession(params),
7000 HttpCache::DefaultBackend::InMemory(0)));
7001
7002 default_context_.set_http_transaction_factory(cache.get());
7003
7004 {
7005 TestDelegate d;
7006 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7007 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7008
7009 r->Start();
7010 EXPECT_TRUE(r->is_pending());
7011
7012 base::RunLoop().Run();
7013
7014 // The response will look like;
7015 // insert abc
7016 // insert xyz
7017 //
7018 // With a newline at the end which makes the split think that there are
7019 // three lines.
7020
7021 EXPECT_EQ(1, d.response_started_count());
7022 AssertTwoDistinctSessionsInserted(d.data_received());
7023 }
7024 }
7025
7026 #if defined(OS_WIN)
7027
7028 namespace {
7029
IsECDSACipherSuite(uint16_t cipher_suite)7030 bool IsECDSACipherSuite(uint16_t cipher_suite) {
7031 const char* key_exchange;
7032 const char* cipher;
7033 const char* mac;
7034 bool is_aead;
7035 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7036 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7037 }
7038
7039 } // namespace
7040
7041 // Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7042 // verified.
7043 // Test seems flaky, see http://crbug.com/411827.
TEST_F(HTTPSRequestTest,DISABLED_DisableECDSAOnXP)7044 TEST_F(HTTPSRequestTest, DISABLED_DisableECDSAOnXP) {
7045 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7046 LOG(INFO) << "Skipping test on this version.";
7047 return;
7048 }
7049
7050 SpawnedTestServer test_server(
7051 SpawnedTestServer::TYPE_HTTPS,
7052 SpawnedTestServer::kLocalhost,
7053 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7054 ASSERT_TRUE(test_server.Start());
7055
7056 TestDelegate d;
7057 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7058 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d, NULL));
7059 r->Start();
7060 EXPECT_TRUE(r->is_pending());
7061
7062 base::RunLoop().Run();
7063
7064 EXPECT_EQ(1, d.response_started_count());
7065 std::vector<std::string> lines;
7066 base::SplitString(d.data_received(), '\n', &lines);
7067
7068 for (size_t i = 0; i < lines.size(); i++) {
7069 int cipher_suite;
7070 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7071 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7072 << "ClientHello advertised " << cipher_suite;
7073 }
7074 }
7075
7076 #endif // OS_WIN
7077
7078 class TestSSLConfigService : public SSLConfigService {
7079 public:
TestSSLConfigService(bool ev_enabled,bool online_rev_checking,bool rev_checking_required_local_anchors)7080 TestSSLConfigService(bool ev_enabled,
7081 bool online_rev_checking,
7082 bool rev_checking_required_local_anchors)
7083 : ev_enabled_(ev_enabled),
7084 online_rev_checking_(online_rev_checking),
7085 rev_checking_required_local_anchors_(
7086 rev_checking_required_local_anchors),
7087 fallback_min_version_(0) {}
7088
set_fallback_min_version(uint16 version)7089 void set_fallback_min_version(uint16 version) {
7090 fallback_min_version_ = version;
7091 }
7092
7093 // SSLConfigService:
GetSSLConfig(SSLConfig * config)7094 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
7095 *config = SSLConfig();
7096 config->rev_checking_enabled = online_rev_checking_;
7097 config->verify_ev_cert = ev_enabled_;
7098 config->rev_checking_required_local_anchors =
7099 rev_checking_required_local_anchors_;
7100 if (fallback_min_version_) {
7101 config->version_fallback_min = fallback_min_version_;
7102 }
7103 }
7104
7105 protected:
~TestSSLConfigService()7106 virtual ~TestSSLConfigService() {}
7107
7108 private:
7109 const bool ev_enabled_;
7110 const bool online_rev_checking_;
7111 const bool rev_checking_required_local_anchors_;
7112 uint16 fallback_min_version_;
7113 };
7114
7115 class FallbackTestURLRequestContext : public TestURLRequestContext {
7116 public:
FallbackTestURLRequestContext(bool delay_initialization)7117 explicit FallbackTestURLRequestContext(bool delay_initialization)
7118 : TestURLRequestContext(delay_initialization) {}
7119
set_fallback_min_version(uint16 version)7120 void set_fallback_min_version(uint16 version) {
7121 TestSSLConfigService *ssl_config_service =
7122 new TestSSLConfigService(true /* check for EV */,
7123 false /* online revocation checking */,
7124 false /* require rev. checking for local
7125 anchors */);
7126 ssl_config_service->set_fallback_min_version(version);
7127 set_ssl_config_service(ssl_config_service);
7128 }
7129 };
7130
7131 class HTTPSFallbackTest : public testing::Test {
7132 public:
HTTPSFallbackTest()7133 HTTPSFallbackTest() : context_(true) {}
~HTTPSFallbackTest()7134 virtual ~HTTPSFallbackTest() {}
7135
7136 protected:
DoFallbackTest(const SpawnedTestServer::SSLOptions & ssl_options)7137 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7138 DCHECK(!request_);
7139 context_.Init();
7140 delegate_.set_allow_certificate_errors(true);
7141
7142 SpawnedTestServer test_server(
7143 SpawnedTestServer::TYPE_HTTPS,
7144 ssl_options,
7145 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7146 ASSERT_TRUE(test_server.Start());
7147
7148 request_ = context_.CreateRequest(
7149 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate_, NULL);
7150 request_->Start();
7151
7152 base::RunLoop().Run();
7153 }
7154
set_fallback_min_version(uint16 version)7155 void set_fallback_min_version(uint16 version) {
7156 context_.set_fallback_min_version(version);
7157 }
7158
ExpectConnection(int version)7159 void ExpectConnection(int version) {
7160 EXPECT_EQ(1, delegate_.response_started_count());
7161 EXPECT_NE(0, delegate_.bytes_received());
7162 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7163 request_->ssl_info().connection_status));
7164 EXPECT_TRUE(request_->ssl_info().connection_status &
7165 SSL_CONNECTION_VERSION_FALLBACK);
7166 }
7167
ExpectFailure(int error)7168 void ExpectFailure(int error) {
7169 EXPECT_EQ(1, delegate_.response_started_count());
7170 EXPECT_FALSE(request_->status().is_success());
7171 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7172 EXPECT_EQ(error, request_->status().error());
7173 }
7174
7175 private:
7176 TestDelegate delegate_;
7177 FallbackTestURLRequestContext context_;
7178 scoped_ptr<URLRequest> request_;
7179 };
7180
7181 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7182 // than necessary.
TEST_F(HTTPSFallbackTest,TLSv1Fallback)7183 TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7184 SpawnedTestServer::SSLOptions ssl_options(
7185 SpawnedTestServer::SSLOptions::CERT_OK);
7186 ssl_options.tls_intolerant =
7187 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7188
7189 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7190 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7191 }
7192
7193 // This test is disabled on Android because the remote test server doesn't cause
7194 // a TCP reset.
7195 #if !defined(OS_ANDROID)
7196 // Tests fallback to TLS 1.0 on connection reset.
TEST_F(HTTPSFallbackTest,TLSv1FallbackReset)7197 TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7198 SpawnedTestServer::SSLOptions ssl_options(
7199 SpawnedTestServer::SSLOptions::CERT_OK);
7200 ssl_options.tls_intolerant =
7201 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7202 ssl_options.tls_intolerance_type =
7203 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7204
7205 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7206 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7207 }
7208 #endif // !OS_ANDROID
7209
7210 // Tests that we don't fallback on handshake failure with servers that implement
7211 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
TEST_F(HTTPSFallbackTest,FallbackSCSV)7212 TEST_F(HTTPSFallbackTest, FallbackSCSV) {
7213 SpawnedTestServer::SSLOptions ssl_options(
7214 SpawnedTestServer::SSLOptions::CERT_OK);
7215 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7216 // a version fallback.
7217 ssl_options.tls_intolerant =
7218 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7219 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7220 // connections are rejected.
7221 ssl_options.fallback_scsv_enabled = true;
7222
7223 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7224
7225 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7226 // intolerance. If the fallback SCSV is processed when the original error
7227 // that caused the fallback should be returned, which should be
7228 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7229 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7230 }
7231
7232 // Tests that we don't fallback on connection closed with servers that implement
7233 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
TEST_F(HTTPSFallbackTest,FallbackSCSVClosed)7234 TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
7235 SpawnedTestServer::SSLOptions ssl_options(
7236 SpawnedTestServer::SSLOptions::CERT_OK);
7237 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7238 // a version fallback.
7239 ssl_options.tls_intolerant =
7240 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7241 ssl_options.tls_intolerance_type =
7242 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7243 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7244 // connections are rejected.
7245 ssl_options.fallback_scsv_enabled = true;
7246
7247 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7248
7249 // The original error should be replayed on rejected fallback.
7250 ExpectFailure(ERR_CONNECTION_CLOSED);
7251 }
7252
7253 // Tests that the SSLv3 fallback doesn't happen by default.
TEST_F(HTTPSFallbackTest,SSLv3Fallback)7254 TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7255 SpawnedTestServer::SSLOptions ssl_options(
7256 SpawnedTestServer::SSLOptions::CERT_OK);
7257 ssl_options.tls_intolerant =
7258 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7259
7260 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7261 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
7262 }
7263
7264 // Tests that the SSLv3 fallback works when explicitly enabled.
TEST_F(HTTPSFallbackTest,SSLv3FallbackEnabled)7265 TEST_F(HTTPSFallbackTest, SSLv3FallbackEnabled) {
7266 SpawnedTestServer::SSLOptions ssl_options(
7267 SpawnedTestServer::SSLOptions::CERT_OK);
7268 ssl_options.tls_intolerant =
7269 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7270 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7271
7272 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7273 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7274 }
7275
7276 // Tests that the SSLv3 fallback triggers on closed connections when explicitly
7277 // enabled.
TEST_F(HTTPSFallbackTest,SSLv3FallbackClosed)7278 TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
7279 SpawnedTestServer::SSLOptions ssl_options(
7280 SpawnedTestServer::SSLOptions::CERT_OK);
7281 ssl_options.tls_intolerant =
7282 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7283 ssl_options.tls_intolerance_type =
7284 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7285 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7286
7287 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7288 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7289 }
7290
7291 // Test that SSLv3 fallback probe connections don't cause sessions to be cached.
TEST_F(HTTPSRequestTest,SSLv3FallbackNoCache)7292 TEST_F(HTTPSRequestTest, SSLv3FallbackNoCache) {
7293 SpawnedTestServer::SSLOptions ssl_options(
7294 SpawnedTestServer::SSLOptions::CERT_OK);
7295 ssl_options.tls_intolerant =
7296 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7297 ssl_options.tls_intolerance_type =
7298 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7299 ssl_options.record_resume = true;
7300
7301 SpawnedTestServer test_server(
7302 SpawnedTestServer::TYPE_HTTPS,
7303 ssl_options,
7304 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7305 ASSERT_TRUE(test_server.Start());
7306
7307 SSLClientSocket::ClearSessionCache();
7308
7309 // Make a connection that does a probe fallback to SSLv3 but fails because
7310 // SSLv3 fallback is disabled. We don't wish a session for this connection to
7311 // be inserted locally.
7312 {
7313 TestDelegate delegate;
7314 FallbackTestURLRequestContext context(true);
7315
7316 context.Init();
7317 scoped_ptr<URLRequest> request(context.CreateRequest(
7318 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate, NULL));
7319 request->Start();
7320
7321 base::RunLoop().Run();
7322
7323 EXPECT_EQ(1, delegate.response_started_count());
7324 EXPECT_FALSE(request->status().is_success());
7325 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
7326 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
7327 request->status().error());
7328 }
7329
7330 // Now allow SSLv3 connections and request the session cache log.
7331 {
7332 TestDelegate delegate;
7333 FallbackTestURLRequestContext context(true);
7334 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7335
7336 context.Init();
7337 scoped_ptr<URLRequest> request(
7338 context.CreateRequest(test_server.GetURL("ssl-session-cache"),
7339 DEFAULT_PRIORITY,
7340 &delegate,
7341 NULL));
7342 request->Start();
7343
7344 base::RunLoop().Run();
7345
7346 EXPECT_EQ(1, delegate.response_started_count());
7347 EXPECT_NE(0, delegate.bytes_received());
7348 EXPECT_EQ(SSL_CONNECTION_VERSION_SSL3, SSLConnectionStatusToVersion(
7349 request->ssl_info().connection_status));
7350 EXPECT_TRUE(request->ssl_info().connection_status &
7351 SSL_CONNECTION_VERSION_FALLBACK);
7352
7353 std::vector<std::string> lines;
7354 // If no sessions were cached then the server should have seen two sessions
7355 // inserted with no lookups.
7356 AssertTwoDistinctSessionsInserted(delegate.data_received());
7357 }
7358 }
7359
7360 // This test is disabled on Android because the remote test server doesn't cause
7361 // a TCP reset.
7362 #if !defined(OS_ANDROID)
7363 // Tests that a reset connection does not fallback down to SSL3.
TEST_F(HTTPSFallbackTest,SSLv3NoFallbackReset)7364 TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
7365 SpawnedTestServer::SSLOptions ssl_options(
7366 SpawnedTestServer::SSLOptions::CERT_OK);
7367 ssl_options.tls_intolerant =
7368 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7369 ssl_options.tls_intolerance_type =
7370 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7371
7372 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7373 ExpectFailure(ERR_CONNECTION_RESET);
7374 }
7375 #endif // !OS_ANDROID
7376
7377 class HTTPSSessionTest : public testing::Test {
7378 public:
HTTPSSessionTest()7379 HTTPSSessionTest() : default_context_(true) {
7380 cert_verifier_.set_default_result(OK);
7381
7382 default_context_.set_network_delegate(&default_network_delegate_);
7383 default_context_.set_cert_verifier(&cert_verifier_);
7384 default_context_.Init();
7385 }
~HTTPSSessionTest()7386 virtual ~HTTPSSessionTest() {}
7387
7388 protected:
7389 MockCertVerifier cert_verifier_;
7390 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7391 TestURLRequestContext default_context_;
7392 };
7393
7394 // Tests that session resumption is not attempted if an invalid certificate
7395 // is presented.
TEST_F(HTTPSSessionTest,DontResumeSessionsForInvalidCertificates)7396 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7397 SpawnedTestServer::SSLOptions ssl_options;
7398 ssl_options.record_resume = true;
7399 SpawnedTestServer test_server(
7400 SpawnedTestServer::TYPE_HTTPS,
7401 ssl_options,
7402 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7403 ASSERT_TRUE(test_server.Start());
7404
7405 SSLClientSocket::ClearSessionCache();
7406
7407 // Simulate the certificate being expired and attempt a connection.
7408 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
7409 {
7410 TestDelegate d;
7411 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7412 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7413
7414 r->Start();
7415 EXPECT_TRUE(r->is_pending());
7416
7417 base::RunLoop().Run();
7418
7419 EXPECT_EQ(1, d.response_started_count());
7420 }
7421
7422 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7423 CloseAllConnections();
7424
7425 // Now change the certificate to be acceptable (so that the response is
7426 // loaded), and ensure that no session id is presented to the peer.
7427 cert_verifier_.set_default_result(OK);
7428 {
7429 TestDelegate d;
7430 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7431 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
7432
7433 r->Start();
7434 EXPECT_TRUE(r->is_pending());
7435
7436 base::RunLoop().Run();
7437
7438 // The response will look like;
7439 // insert abc
7440 // insert xyz
7441 //
7442 // With a newline at the end which makes the split think that there are
7443 // three lines.
7444 //
7445 // If a session was presented (eg: a bug), then the response would look
7446 // like;
7447 // insert abc
7448 // lookup abc
7449 // insert xyz
7450
7451 EXPECT_EQ(1, d.response_started_count());
7452 AssertTwoDistinctSessionsInserted(d.data_received());
7453 }
7454 }
7455
7456 // This the fingerprint of the "Testing CA" certificate used by the testserver.
7457 // See net/data/ssl/certificates/ocsp-test-root.pem.
7458 static const SHA1HashValue kOCSPTestCertFingerprint =
7459 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7460 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7461
7462 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7463 // testserver.
7464 static const SHA256HashValue kOCSPTestCertSPKI = { {
7465 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7466 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7467 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7468 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7469 } };
7470
7471 // This is the policy OID contained in the certificates that testserver
7472 // generates.
7473 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
7474
7475 class HTTPSOCSPTest : public HTTPSRequestTest {
7476 public:
HTTPSOCSPTest()7477 HTTPSOCSPTest()
7478 : context_(true),
7479 ev_test_policy_(
7480 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7481 kOCSPTestCertFingerprint,
7482 kOCSPTestCertPolicy)) {
7483 }
7484
SetUp()7485 virtual void SetUp() OVERRIDE {
7486 SetupContext(&context_);
7487 context_.Init();
7488
7489 scoped_refptr<X509Certificate> root_cert =
7490 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
7491 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
7492 test_root_.reset(new ScopedTestRoot(root_cert.get()));
7493
7494 #if defined(USE_NSS) || defined(OS_IOS)
7495 SetURLRequestContextForNSSHttpIO(&context_);
7496 EnsureNSSHttpIOInit();
7497 #endif
7498 }
7499
DoConnection(const SpawnedTestServer::SSLOptions & ssl_options,CertStatus * out_cert_status)7500 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
7501 CertStatus* out_cert_status) {
7502 // We always overwrite out_cert_status.
7503 *out_cert_status = 0;
7504 SpawnedTestServer test_server(
7505 SpawnedTestServer::TYPE_HTTPS,
7506 ssl_options,
7507 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7508 ASSERT_TRUE(test_server.Start());
7509
7510 TestDelegate d;
7511 d.set_allow_certificate_errors(true);
7512 scoped_ptr<URLRequest> r(context_.CreateRequest(
7513 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7514 r->Start();
7515
7516 base::RunLoop().Run();
7517
7518 EXPECT_EQ(1, d.response_started_count());
7519 *out_cert_status = r->ssl_info().cert_status;
7520 }
7521
~HTTPSOCSPTest()7522 virtual ~HTTPSOCSPTest() {
7523 #if defined(USE_NSS) || defined(OS_IOS)
7524 ShutdownNSSHttpIO();
7525 #endif
7526 }
7527
7528 protected:
7529 // SetupContext configures the URLRequestContext that will be used for making
7530 // connetions to testserver. This can be overridden in test subclasses for
7531 // different behaviour.
SetupContext(URLRequestContext * context)7532 virtual void SetupContext(URLRequestContext* context) {
7533 context->set_ssl_config_service(
7534 new TestSSLConfigService(true /* check for EV */,
7535 true /* online revocation checking */,
7536 false /* require rev. checking for local
7537 anchors */));
7538 }
7539
7540 scoped_ptr<ScopedTestRoot> test_root_;
7541 TestURLRequestContext context_;
7542 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
7543 };
7544
ExpectedCertStatusForFailedOnlineRevocationCheck()7545 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
7546 #if defined(OS_WIN)
7547 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7548 // have that ability on other platforms.
7549 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
7550 #else
7551 return 0;
7552 #endif
7553 }
7554
7555 // SystemSupportsHardFailRevocationChecking returns true iff the current
7556 // operating system supports revocation checking and can distinguish between
7557 // situations where a given certificate lacks any revocation information (eg:
7558 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7559 // revocation information cannot be obtained (eg: the CRL was unreachable).
7560 // If it does not, then tests which rely on 'hard fail' behaviour should be
7561 // skipped.
SystemSupportsHardFailRevocationChecking()7562 static bool SystemSupportsHardFailRevocationChecking() {
7563 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7564 return true;
7565 #else
7566 return false;
7567 #endif
7568 }
7569
7570 // SystemUsesChromiumEVMetadata returns true iff the current operating system
7571 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7572 // several tests are effected because our testing EV certificate won't be
7573 // recognised as EV.
SystemUsesChromiumEVMetadata()7574 static bool SystemUsesChromiumEVMetadata() {
7575 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
7576 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7577 return false;
7578 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7579 // On OS X and Android, we use the system to tell us whether a certificate is
7580 // EV or not and the system won't recognise our testing root.
7581 return false;
7582 #else
7583 return true;
7584 #endif
7585 }
7586
SystemSupportsOCSP()7587 static bool SystemSupportsOCSP() {
7588 #if defined(USE_OPENSSL)
7589 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7590 return false;
7591 #elif defined(OS_WIN)
7592 return base::win::GetVersion() >= base::win::VERSION_VISTA;
7593 #elif defined(OS_ANDROID)
7594 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7595 return false;
7596 #else
7597 return true;
7598 #endif
7599 }
7600
TEST_F(HTTPSOCSPTest,Valid)7601 TEST_F(HTTPSOCSPTest, Valid) {
7602 if (!SystemSupportsOCSP()) {
7603 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7604 return;
7605 }
7606
7607 SpawnedTestServer::SSLOptions ssl_options(
7608 SpawnedTestServer::SSLOptions::CERT_AUTO);
7609 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7610
7611 CertStatus cert_status;
7612 DoConnection(ssl_options, &cert_status);
7613
7614 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7615
7616 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7617 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7618
7619 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7620 }
7621
TEST_F(HTTPSOCSPTest,Revoked)7622 TEST_F(HTTPSOCSPTest, Revoked) {
7623 if (!SystemSupportsOCSP()) {
7624 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7625 return;
7626 }
7627
7628 SpawnedTestServer::SSLOptions ssl_options(
7629 SpawnedTestServer::SSLOptions::CERT_AUTO);
7630 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7631
7632 CertStatus cert_status;
7633 DoConnection(ssl_options, &cert_status);
7634
7635 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
7636 // Doesn't pass on OS X yet for reasons that need to be investigated.
7637 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7638 #endif
7639 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7640 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7641 }
7642
TEST_F(HTTPSOCSPTest,Invalid)7643 TEST_F(HTTPSOCSPTest, Invalid) {
7644 if (!SystemSupportsOCSP()) {
7645 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7646 return;
7647 }
7648
7649 SpawnedTestServer::SSLOptions ssl_options(
7650 SpawnedTestServer::SSLOptions::CERT_AUTO);
7651 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7652
7653 CertStatus cert_status;
7654 DoConnection(ssl_options, &cert_status);
7655
7656 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7657 cert_status & CERT_STATUS_ALL_ERRORS);
7658
7659 // Without a positive OCSP response, we shouldn't show the EV status.
7660 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7661 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7662 }
7663
7664 class HTTPSHardFailTest : public HTTPSOCSPTest {
7665 protected:
SetupContext(URLRequestContext * context)7666 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7667 context->set_ssl_config_service(
7668 new TestSSLConfigService(false /* check for EV */,
7669 false /* online revocation checking */,
7670 true /* require rev. checking for local
7671 anchors */));
7672 }
7673 };
7674
7675
TEST_F(HTTPSHardFailTest,FailsOnOCSPInvalid)7676 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
7677 if (!SystemSupportsOCSP()) {
7678 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7679 return;
7680 }
7681
7682 if (!SystemSupportsHardFailRevocationChecking()) {
7683 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
7684 << "revocation checking";
7685 return;
7686 }
7687
7688 SpawnedTestServer::SSLOptions ssl_options(
7689 SpawnedTestServer::SSLOptions::CERT_AUTO);
7690 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7691
7692 CertStatus cert_status;
7693 DoConnection(ssl_options, &cert_status);
7694
7695 EXPECT_EQ(CERT_STATUS_REVOKED,
7696 cert_status & CERT_STATUS_REVOKED);
7697
7698 // Without a positive OCSP response, we shouldn't show the EV status.
7699 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7700 }
7701
7702 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
7703 protected:
SetupContext(URLRequestContext * context)7704 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7705 context->set_ssl_config_service(
7706 new TestSSLConfigService(true /* check for EV */,
7707 false /* online revocation checking */,
7708 false /* require rev. checking for local
7709 anchors */));
7710 }
7711 };
7712
TEST_F(HTTPSEVCRLSetTest,MissingCRLSetAndInvalidOCSP)7713 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
7714 if (!SystemSupportsOCSP()) {
7715 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7716 return;
7717 }
7718
7719 SpawnedTestServer::SSLOptions ssl_options(
7720 SpawnedTestServer::SSLOptions::CERT_AUTO);
7721 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7722 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7723
7724 CertStatus cert_status;
7725 DoConnection(ssl_options, &cert_status);
7726
7727 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7728 cert_status & CERT_STATUS_ALL_ERRORS);
7729
7730 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7731 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7732 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7733 }
7734
TEST_F(HTTPSEVCRLSetTest,MissingCRLSetAndRevokedOCSP)7735 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
7736 if (!SystemSupportsOCSP()) {
7737 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7738 return;
7739 }
7740
7741 SpawnedTestServer::SSLOptions ssl_options(
7742 SpawnedTestServer::SSLOptions::CERT_AUTO);
7743 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7744 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7745
7746 CertStatus cert_status;
7747 DoConnection(ssl_options, &cert_status);
7748
7749 // Currently only works for Windows. When using NSS or OS X, it's not
7750 // possible to determine whether the check failed because of actual
7751 // revocation or because there was an OCSP failure.
7752 #if defined(OS_WIN)
7753 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7754 #else
7755 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7756 #endif
7757
7758 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7759 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7760 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7761 }
7762
TEST_F(HTTPSEVCRLSetTest,MissingCRLSetAndGoodOCSP)7763 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
7764 if (!SystemSupportsOCSP()) {
7765 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7766 return;
7767 }
7768
7769 SpawnedTestServer::SSLOptions ssl_options(
7770 SpawnedTestServer::SSLOptions::CERT_AUTO);
7771 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7772 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7773
7774 CertStatus cert_status;
7775 DoConnection(ssl_options, &cert_status);
7776
7777 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7778
7779 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7780 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7781 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7782 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7783 }
7784
TEST_F(HTTPSEVCRLSetTest,ExpiredCRLSet)7785 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
7786 if (!SystemSupportsOCSP()) {
7787 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7788 return;
7789 }
7790
7791 SpawnedTestServer::SSLOptions ssl_options(
7792 SpawnedTestServer::SSLOptions::CERT_AUTO);
7793 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7794 SSLConfigService::SetCRLSet(
7795 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7796
7797 CertStatus cert_status;
7798 DoConnection(ssl_options, &cert_status);
7799
7800 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7801 cert_status & CERT_STATUS_ALL_ERRORS);
7802
7803 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7804 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7805 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7806 }
7807
TEST_F(HTTPSEVCRLSetTest,FreshCRLSetCovered)7808 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
7809 if (!SystemSupportsOCSP()) {
7810 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7811 return;
7812 }
7813
7814 SpawnedTestServer::SSLOptions ssl_options(
7815 SpawnedTestServer::SSLOptions::CERT_AUTO);
7816 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7817 SSLConfigService::SetCRLSet(
7818 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7819 false, &kOCSPTestCertSPKI, "")));
7820
7821 CertStatus cert_status;
7822 DoConnection(ssl_options, &cert_status);
7823
7824 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7825 // revocation check for EV.
7826 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7827 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7828 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7829 EXPECT_FALSE(
7830 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7831 }
7832
TEST_F(HTTPSEVCRLSetTest,FreshCRLSetNotCovered)7833 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
7834 if (!SystemSupportsOCSP()) {
7835 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7836 return;
7837 }
7838
7839 SpawnedTestServer::SSLOptions ssl_options(
7840 SpawnedTestServer::SSLOptions::CERT_AUTO);
7841 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7842 SSLConfigService::SetCRLSet(
7843 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
7844
7845 CertStatus cert_status = 0;
7846 DoConnection(ssl_options, &cert_status);
7847
7848 // Even with a fresh CRLSet, we should still do online revocation checks when
7849 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7850 // test.
7851 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7852 cert_status & CERT_STATUS_ALL_ERRORS);
7853
7854 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7855 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7856 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7857 }
7858
TEST_F(HTTPSEVCRLSetTest,ExpiredCRLSetAndRevokedNonEVCert)7859 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
7860 // Test that when EV verification is requested, but online revocation
7861 // checking is disabled, and the leaf certificate is not in fact EV, that
7862 // no revocation checking actually happens.
7863 if (!SystemSupportsOCSP()) {
7864 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7865 return;
7866 }
7867
7868 // Unmark the certificate's OID as EV, which should disable revocation
7869 // checking (as per the user preference)
7870 ev_test_policy_.reset();
7871
7872 SpawnedTestServer::SSLOptions ssl_options(
7873 SpawnedTestServer::SSLOptions::CERT_AUTO);
7874 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7875 SSLConfigService::SetCRLSet(
7876 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7877
7878 CertStatus cert_status;
7879 DoConnection(ssl_options, &cert_status);
7880
7881 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7882
7883 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7884 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7885 }
7886
7887 class HTTPSCRLSetTest : public HTTPSOCSPTest {
7888 protected:
SetupContext(URLRequestContext * context)7889 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7890 context->set_ssl_config_service(
7891 new TestSSLConfigService(false /* check for EV */,
7892 false /* online revocation checking */,
7893 false /* require rev. checking for local
7894 anchors */));
7895 }
7896 };
7897
TEST_F(HTTPSCRLSetTest,ExpiredCRLSet)7898 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
7899 SpawnedTestServer::SSLOptions ssl_options(
7900 SpawnedTestServer::SSLOptions::CERT_AUTO);
7901 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7902 SSLConfigService::SetCRLSet(
7903 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7904
7905 CertStatus cert_status;
7906 DoConnection(ssl_options, &cert_status);
7907
7908 // If we're not trying EV verification then, even if the CRLSet has expired,
7909 // we don't fall back to online revocation checks.
7910 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7911 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7912 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7913 }
7914
TEST_F(HTTPSCRLSetTest,CRLSetRevoked)7915 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
7916 #if defined(OS_ANDROID)
7917 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
7918 return;
7919 #endif
7920
7921 SpawnedTestServer::SSLOptions ssl_options(
7922 SpawnedTestServer::SSLOptions::CERT_AUTO);
7923 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7924 ssl_options.cert_serial = 10;
7925 SSLConfigService::SetCRLSet(
7926 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7927 false, &kOCSPTestCertSPKI, "\x0a")));
7928
7929 CertStatus cert_status = 0;
7930 DoConnection(ssl_options, &cert_status);
7931
7932 // If the certificate is recorded as revoked in the CRLSet, that should be
7933 // reflected without online revocation checking.
7934 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7935 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7936 EXPECT_FALSE(
7937 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7938 }
7939 #endif // !defined(OS_IOS)
7940
7941 #if !defined(DISABLE_FTP_SUPPORT)
7942 class URLRequestTestFTP : public URLRequestTest {
7943 public:
URLRequestTestFTP()7944 URLRequestTestFTP()
7945 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
7946 base::FilePath()) {
7947 }
7948
7949 protected:
7950 SpawnedTestServer test_server_;
7951 };
7952
7953 // Make sure an FTP request using an unsafe ports fails.
TEST_F(URLRequestTestFTP,UnsafePort)7954 TEST_F(URLRequestTestFTP, UnsafePort) {
7955 ASSERT_TRUE(test_server_.Start());
7956
7957 URLRequestJobFactoryImpl job_factory;
7958 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
7959
7960 GURL url("ftp://127.0.0.1:7");
7961 job_factory.SetProtocolHandler(
7962 "ftp",
7963 new FtpProtocolHandler(&ftp_transaction_factory));
7964 default_context_.set_job_factory(&job_factory);
7965
7966 TestDelegate d;
7967 {
7968 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7969 url, DEFAULT_PRIORITY, &d, NULL));
7970 r->Start();
7971 EXPECT_TRUE(r->is_pending());
7972
7973 base::RunLoop().Run();
7974
7975 EXPECT_FALSE(r->is_pending());
7976 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
7977 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
7978 }
7979 }
7980
7981 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPDirectoryListing)7982 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
7983 ASSERT_TRUE(test_server_.Start());
7984
7985 TestDelegate d;
7986 {
7987 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7988 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, NULL));
7989 r->Start();
7990 EXPECT_TRUE(r->is_pending());
7991
7992 base::RunLoop().Run();
7993
7994 EXPECT_FALSE(r->is_pending());
7995 EXPECT_EQ(1, d.response_started_count());
7996 EXPECT_FALSE(d.received_data_before_response());
7997 EXPECT_LT(0, d.bytes_received());
7998 EXPECT_EQ(test_server_.host_port_pair().host(),
7999 r->GetSocketAddress().host());
8000 EXPECT_EQ(test_server_.host_port_pair().port(),
8001 r->GetSocketAddress().port());
8002 }
8003 }
8004
8005 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPGetTestAnonymous)8006 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
8007 ASSERT_TRUE(test_server_.Start());
8008
8009 base::FilePath app_path;
8010 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8011 app_path = app_path.AppendASCII("LICENSE");
8012 TestDelegate d;
8013 {
8014 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8015 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d, NULL));
8016 r->Start();
8017 EXPECT_TRUE(r->is_pending());
8018
8019 base::RunLoop().Run();
8020
8021 int64 file_size = 0;
8022 base::GetFileSize(app_path, &file_size);
8023
8024 EXPECT_FALSE(r->is_pending());
8025 EXPECT_EQ(1, d.response_started_count());
8026 EXPECT_FALSE(d.received_data_before_response());
8027 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8028 EXPECT_EQ(test_server_.host_port_pair().host(),
8029 r->GetSocketAddress().host());
8030 EXPECT_EQ(test_server_.host_port_pair().port(),
8031 r->GetSocketAddress().port());
8032 }
8033 }
8034
8035 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPGetTest)8036 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
8037 ASSERT_TRUE(test_server_.Start());
8038
8039 base::FilePath app_path;
8040 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8041 app_path = app_path.AppendASCII("LICENSE");
8042 TestDelegate d;
8043 {
8044 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8045 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8046 DEFAULT_PRIORITY, &d, NULL));
8047 r->Start();
8048 EXPECT_TRUE(r->is_pending());
8049
8050 base::RunLoop().Run();
8051
8052 int64 file_size = 0;
8053 base::GetFileSize(app_path, &file_size);
8054
8055 EXPECT_FALSE(r->is_pending());
8056 EXPECT_EQ(test_server_.host_port_pair().host(),
8057 r->GetSocketAddress().host());
8058 EXPECT_EQ(test_server_.host_port_pair().port(),
8059 r->GetSocketAddress().port());
8060 EXPECT_EQ(1, d.response_started_count());
8061 EXPECT_FALSE(d.received_data_before_response());
8062 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8063
8064 LoadTimingInfo load_timing_info;
8065 r->GetLoadTimingInfo(&load_timing_info);
8066 TestLoadTimingNoHttpResponse(load_timing_info);
8067 }
8068 }
8069
8070 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPCheckWrongPassword)8071 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
8072 ASSERT_TRUE(test_server_.Start());
8073
8074 base::FilePath app_path;
8075 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8076 app_path = app_path.AppendASCII("LICENSE");
8077 TestDelegate d;
8078 {
8079 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8080 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8081 "wrong_password"),
8082 DEFAULT_PRIORITY, &d, NULL));
8083 r->Start();
8084 EXPECT_TRUE(r->is_pending());
8085
8086 base::RunLoop().Run();
8087
8088 int64 file_size = 0;
8089 base::GetFileSize(app_path, &file_size);
8090
8091 EXPECT_FALSE(r->is_pending());
8092 EXPECT_EQ(1, d.response_started_count());
8093 EXPECT_FALSE(d.received_data_before_response());
8094 EXPECT_EQ(d.bytes_received(), 0);
8095 }
8096 }
8097
8098 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPCheckWrongPasswordRestart)8099 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
8100 ASSERT_TRUE(test_server_.Start());
8101
8102 base::FilePath app_path;
8103 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8104 app_path = app_path.AppendASCII("LICENSE");
8105 TestDelegate d;
8106 // Set correct login credentials. The delegate will be asked for them when
8107 // the initial login with wrong credentials will fail.
8108 d.set_credentials(AuthCredentials(kChrome, kChrome));
8109 {
8110 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8111 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8112 "wrong_password"),
8113 DEFAULT_PRIORITY, &d, NULL));
8114 r->Start();
8115 EXPECT_TRUE(r->is_pending());
8116
8117 base::RunLoop().Run();
8118
8119 int64 file_size = 0;
8120 base::GetFileSize(app_path, &file_size);
8121
8122 EXPECT_FALSE(r->is_pending());
8123 EXPECT_EQ(1, d.response_started_count());
8124 EXPECT_FALSE(d.received_data_before_response());
8125 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8126 }
8127 }
8128
8129 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPCheckWrongUser)8130 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
8131 ASSERT_TRUE(test_server_.Start());
8132
8133 base::FilePath app_path;
8134 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8135 app_path = app_path.AppendASCII("LICENSE");
8136 TestDelegate d;
8137 {
8138 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8139 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8140 "chrome"),
8141 DEFAULT_PRIORITY, &d, NULL));
8142 r->Start();
8143 EXPECT_TRUE(r->is_pending());
8144
8145 base::RunLoop().Run();
8146
8147 int64 file_size = 0;
8148 base::GetFileSize(app_path, &file_size);
8149
8150 EXPECT_FALSE(r->is_pending());
8151 EXPECT_EQ(1, d.response_started_count());
8152 EXPECT_FALSE(d.received_data_before_response());
8153 EXPECT_EQ(d.bytes_received(), 0);
8154 }
8155 }
8156
8157 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPCheckWrongUserRestart)8158 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
8159 ASSERT_TRUE(test_server_.Start());
8160
8161 base::FilePath app_path;
8162 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8163 app_path = app_path.AppendASCII("LICENSE");
8164 TestDelegate d;
8165 // Set correct login credentials. The delegate will be asked for them when
8166 // the initial login with wrong credentials will fail.
8167 d.set_credentials(AuthCredentials(kChrome, kChrome));
8168 {
8169 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8170 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8171 "chrome"),
8172 DEFAULT_PRIORITY, &d, NULL));
8173 r->Start();
8174 EXPECT_TRUE(r->is_pending());
8175
8176 base::RunLoop().Run();
8177
8178 int64 file_size = 0;
8179 base::GetFileSize(app_path, &file_size);
8180
8181 EXPECT_FALSE(r->is_pending());
8182 EXPECT_EQ(1, d.response_started_count());
8183 EXPECT_FALSE(d.received_data_before_response());
8184 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8185 }
8186 }
8187
8188 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPCacheURLCredentials)8189 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
8190 ASSERT_TRUE(test_server_.Start());
8191
8192 base::FilePath app_path;
8193 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8194 app_path = app_path.AppendASCII("LICENSE");
8195
8196 scoped_ptr<TestDelegate> d(new TestDelegate);
8197 {
8198 // Pass correct login identity in the URL.
8199 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8200 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8201 DEFAULT_PRIORITY, d.get(), NULL));
8202 r->Start();
8203 EXPECT_TRUE(r->is_pending());
8204
8205 base::RunLoop().Run();
8206
8207 int64 file_size = 0;
8208 base::GetFileSize(app_path, &file_size);
8209
8210 EXPECT_FALSE(r->is_pending());
8211 EXPECT_EQ(1, d->response_started_count());
8212 EXPECT_FALSE(d->received_data_before_response());
8213 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8214 }
8215
8216 d.reset(new TestDelegate);
8217 {
8218 // This request should use cached identity from previous request.
8219 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8220 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
8221 r->Start();
8222 EXPECT_TRUE(r->is_pending());
8223
8224 base::RunLoop().Run();
8225
8226 int64 file_size = 0;
8227 base::GetFileSize(app_path, &file_size);
8228
8229 EXPECT_FALSE(r->is_pending());
8230 EXPECT_EQ(1, d->response_started_count());
8231 EXPECT_FALSE(d->received_data_before_response());
8232 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8233 }
8234 }
8235
8236 // Flaky, see http://crbug.com/25045.
TEST_F(URLRequestTestFTP,DISABLED_FTPCacheLoginBoxCredentials)8237 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
8238 ASSERT_TRUE(test_server_.Start());
8239
8240 base::FilePath app_path;
8241 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8242 app_path = app_path.AppendASCII("LICENSE");
8243
8244 scoped_ptr<TestDelegate> d(new TestDelegate);
8245 // Set correct login credentials. The delegate will be asked for them when
8246 // the initial login with wrong credentials will fail.
8247 d->set_credentials(AuthCredentials(kChrome, kChrome));
8248 {
8249 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8250 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8251 "wrong_password"),
8252 DEFAULT_PRIORITY, d.get(), NULL));
8253 r->Start();
8254 EXPECT_TRUE(r->is_pending());
8255
8256 base::RunLoop().Run();
8257
8258 int64 file_size = 0;
8259 base::GetFileSize(app_path, &file_size);
8260
8261 EXPECT_FALSE(r->is_pending());
8262 EXPECT_EQ(1, d->response_started_count());
8263 EXPECT_FALSE(d->received_data_before_response());
8264 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8265 }
8266
8267 // Use a new delegate without explicit credentials. The cached ones should be
8268 // used.
8269 d.reset(new TestDelegate);
8270 {
8271 // Don't pass wrong credentials in the URL, they would override valid cached
8272 // ones.
8273 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8274 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
8275 r->Start();
8276 EXPECT_TRUE(r->is_pending());
8277
8278 base::RunLoop().Run();
8279
8280 int64 file_size = 0;
8281 base::GetFileSize(app_path, &file_size);
8282
8283 EXPECT_FALSE(r->is_pending());
8284 EXPECT_EQ(1, d->response_started_count());
8285 EXPECT_FALSE(d->received_data_before_response());
8286 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8287 }
8288 }
8289 #endif // !defined(DISABLE_FTP_SUPPORT)
8290
8291 } // namespace net
8292