url_request_unittest.cc revision 3551c9c881056c480085172ff9840cab31610854
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/file_util.h" 19#include "base/format_macros.h" 20#include "base/memory/weak_ptr.h" 21#include "base/message_loop/message_loop.h" 22#include "base/message_loop/message_loop_proxy.h" 23#include "base/path_service.h" 24#include "base/run_loop.h" 25#include "base/strings/string_number_conversions.h" 26#include "base/strings/string_piece.h" 27#include "base/strings/string_split.h" 28#include "base/strings/string_util.h" 29#include "base/strings/stringprintf.h" 30#include "base/strings/utf_string_conversions.h" 31#include "net/base/capturing_net_log.h" 32#include "net/base/load_flags.h" 33#include "net/base/load_timing_info.h" 34#include "net/base/load_timing_info_test_util.h" 35#include "net/base/net_errors.h" 36#include "net/base/net_log.h" 37#include "net/base/net_log_unittest.h" 38#include "net/base/net_module.h" 39#include "net/base/net_util.h" 40#include "net/base/test_data_directory.h" 41#include "net/base/upload_bytes_element_reader.h" 42#include "net/base/upload_data_stream.h" 43#include "net/base/upload_file_element_reader.h" 44#include "net/cert/ev_root_ca_metadata.h" 45#include "net/cert/test_root_certs.h" 46#include "net/cookies/cookie_monster.h" 47#include "net/cookies/cookie_store_test_helpers.h" 48#include "net/disk_cache/disk_cache.h" 49#include "net/dns/mock_host_resolver.h" 50#include "net/ftp/ftp_network_layer.h" 51#include "net/http/http_cache.h" 52#include "net/http/http_network_layer.h" 53#include "net/http/http_network_session.h" 54#include "net/http/http_request_headers.h" 55#include "net/http/http_response_headers.h" 56#include "net/ocsp/nss_ocsp.h" 57#include "net/proxy/proxy_service.h" 58#include "net/socket/ssl_client_socket.h" 59#include "net/ssl/ssl_connection_status_flags.h" 60#include "net/test/cert_test_util.h" 61#include "net/test/spawned_test_server/spawned_test_server.h" 62#include "net/url_request/data_protocol_handler.h" 63#include "net/url_request/file_protocol_handler.h" 64#include "net/url_request/ftp_protocol_handler.h" 65#include "net/url_request/static_http_user_agent_settings.h" 66#include "net/url_request/url_request.h" 67#include "net/url_request/url_request_file_dir_job.h" 68#include "net/url_request/url_request_http_job.h" 69#include "net/url_request/url_request_job_factory_impl.h" 70#include "net/url_request/url_request_redirect_job.h" 71#include "net/url_request/url_request_test_job.h" 72#include "net/url_request/url_request_test_util.h" 73#include "testing/gtest/include/gtest/gtest.h" 74#include "testing/platform_test.h" 75 76#if defined(OS_WIN) 77#include "base/win/scoped_com_initializer.h" 78#include "base/win/scoped_comptr.h" 79#include "base/win/windows_version.h" 80#endif 81 82using base::Time; 83 84namespace net { 85 86namespace { 87 88const base::string16 kChrome(ASCIIToUTF16("chrome")); 89const base::string16 kSecret(ASCIIToUTF16("secret")); 90const base::string16 kUser(ASCIIToUTF16("user")); 91 92// Tests load timing information in the case a fresh connection was used, with 93// no proxy. 94void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info, 95 int connect_timing_flags) { 96 EXPECT_FALSE(load_timing_info.socket_reused); 97 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id); 98 99 EXPECT_FALSE(load_timing_info.request_start_time.is_null()); 100 EXPECT_FALSE(load_timing_info.request_start.is_null()); 101 102 EXPECT_LE(load_timing_info.request_start, 103 load_timing_info.connect_timing.connect_start); 104 ExpectConnectTimingHasTimes(load_timing_info.connect_timing, 105 connect_timing_flags); 106 EXPECT_LE(load_timing_info.connect_timing.connect_end, 107 load_timing_info.send_start); 108 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end); 109 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end); 110 111 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null()); 112 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null()); 113} 114 115// Same as above, but with proxy times. 116void TestLoadTimingNotReusedWithProxy( 117 const net::LoadTimingInfo& load_timing_info, 118 int connect_timing_flags) { 119 EXPECT_FALSE(load_timing_info.socket_reused); 120 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id); 121 122 EXPECT_FALSE(load_timing_info.request_start_time.is_null()); 123 EXPECT_FALSE(load_timing_info.request_start.is_null()); 124 125 EXPECT_LE(load_timing_info.request_start, 126 load_timing_info.proxy_resolve_start); 127 EXPECT_LE(load_timing_info.proxy_resolve_start, 128 load_timing_info.proxy_resolve_end); 129 EXPECT_LE(load_timing_info.proxy_resolve_end, 130 load_timing_info.connect_timing.connect_start); 131 ExpectConnectTimingHasTimes(load_timing_info.connect_timing, 132 connect_timing_flags); 133 EXPECT_LE(load_timing_info.connect_timing.connect_end, 134 load_timing_info.send_start); 135 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end); 136 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end); 137} 138 139// Same as above, but with a reused socket and proxy times. 140void TestLoadTimingReusedWithProxy( 141 const net::LoadTimingInfo& load_timing_info) { 142 EXPECT_TRUE(load_timing_info.socket_reused); 143 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id); 144 145 EXPECT_FALSE(load_timing_info.request_start_time.is_null()); 146 EXPECT_FALSE(load_timing_info.request_start.is_null()); 147 148 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing); 149 150 EXPECT_LE(load_timing_info.request_start, 151 load_timing_info.proxy_resolve_start); 152 EXPECT_LE(load_timing_info.proxy_resolve_start, 153 load_timing_info.proxy_resolve_end); 154 EXPECT_LE(load_timing_info.proxy_resolve_end, 155 load_timing_info.send_start); 156 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end); 157 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end); 158} 159 160// Tests load timing information in the case of a cache hit, when no cache 161// validation request was sent over the wire. 162void TestLoadTimingCacheHitNoNetwork( 163 const net::LoadTimingInfo& load_timing_info) { 164 EXPECT_FALSE(load_timing_info.socket_reused); 165 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id); 166 167 EXPECT_FALSE(load_timing_info.request_start_time.is_null()); 168 EXPECT_FALSE(load_timing_info.request_start.is_null()); 169 170 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing); 171 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start); 172 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end); 173 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end); 174 175 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null()); 176 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null()); 177} 178 179// Tests load timing in the case that there is no HTTP response. This can be 180// used to test in the case of errors or non-HTTP requests. 181void TestLoadTimingNoHttpResponse( 182 const net::LoadTimingInfo& load_timing_info) { 183 EXPECT_FALSE(load_timing_info.socket_reused); 184 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id); 185 186 // Only the request times should be non-null. 187 EXPECT_FALSE(load_timing_info.request_start_time.is_null()); 188 EXPECT_FALSE(load_timing_info.request_start.is_null()); 189 190 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing); 191 192 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null()); 193 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null()); 194 EXPECT_TRUE(load_timing_info.send_start.is_null()); 195 EXPECT_TRUE(load_timing_info.send_end.is_null()); 196 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null()); 197} 198 199base::StringPiece TestNetResourceProvider(int key) { 200 return "header"; 201} 202 203// Do a case-insensitive search through |haystack| for |needle|. 204bool ContainsString(const std::string& haystack, const char* needle) { 205 std::string::const_iterator it = 206 std::search(haystack.begin(), 207 haystack.end(), 208 needle, 209 needle + strlen(needle), 210 base::CaseInsensitiveCompare<char>()); 211 return it != haystack.end(); 212} 213 214void FillBuffer(char* buffer, size_t len) { 215 static bool called = false; 216 if (!called) { 217 called = true; 218 int seed = static_cast<int>(Time::Now().ToInternalValue()); 219 srand(seed); 220 } 221 222 for (size_t i = 0; i < len; i++) { 223 buffer[i] = static_cast<char>(rand()); 224 if (!buffer[i]) 225 buffer[i] = 'g'; 226 } 227} 228 229UploadDataStream* CreateSimpleUploadData(const char* data) { 230 scoped_ptr<UploadElementReader> reader( 231 new UploadBytesElementReader(data, strlen(data))); 232 return UploadDataStream::CreateWithReader(reader.Pass(), 0); 233} 234 235// Verify that the SSLInfo of a successful SSL connection has valid values. 236void CheckSSLInfo(const SSLInfo& ssl_info) { 237 // Allow ChromeFrame fake SSLInfo to get through. 238 if (ssl_info.cert.get() && 239 ssl_info.cert.get()->issuer().GetDisplayName() == "Chrome Internal") { 240 // -1 means unknown. 241 EXPECT_EQ(ssl_info.security_bits, -1); 242 return; 243 } 244 245 // -1 means unknown. 0 means no encryption. 246 EXPECT_GT(ssl_info.security_bits, 0); 247 248 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated. 249 int cipher_suite = SSLConnectionStatusToCipherSuite( 250 ssl_info.connection_status); 251 EXPECT_NE(0, cipher_suite); 252} 253 254void CheckFullRequestHeaders(const HttpRequestHeaders& headers, 255 const GURL& host_url) { 256 std::string sent_value; 257 258 EXPECT_TRUE(headers.GetHeader("Host", &sent_value)); 259 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value); 260 261 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value)); 262 EXPECT_EQ("keep-alive", sent_value); 263} 264 265bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) { 266 size_t size = a.size(); 267 268 if (size != b.size()) 269 return false; 270 271 for (size_t i = 0; i < size; ++i) { 272 if (!a[i].Equals(b[i])) 273 return false; 274 } 275 276 return true; 277} 278 279// A network delegate that allows the user to choose a subset of request stages 280// to block in. When blocking, the delegate can do one of the following: 281// * synchronously return a pre-specified error code, or 282// * asynchronously return that value via an automatically called callback, 283// or 284// * block and wait for the user to do a callback. 285// Additionally, the user may also specify a redirect URL -- then each request 286// with the current URL different from the redirect target will be redirected 287// to that target, in the on-before-URL-request stage, independent of whether 288// the delegate blocks in ON_BEFORE_URL_REQUEST or not. 289class BlockingNetworkDelegate : public TestNetworkDelegate { 290 public: 291 // Stages in which the delegate can block. 292 enum Stage { 293 NOT_BLOCKED = 0, 294 ON_BEFORE_URL_REQUEST = 1 << 0, 295 ON_BEFORE_SEND_HEADERS = 1 << 1, 296 ON_HEADERS_RECEIVED = 1 << 2, 297 ON_AUTH_REQUIRED = 1 << 3 298 }; 299 300 // Behavior during blocked stages. During other stages, just 301 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION. 302 enum BlockMode { 303 SYNCHRONOUS, // No callback, returns specified return values. 304 AUTO_CALLBACK, // |this| posts a task to run the callback using the 305 // specified return codes. 306 USER_CALLBACK, // User takes care of doing a callback. |retval_| and 307 // |auth_retval_| are ignored. In every blocking stage the 308 // message loop is quit. 309 }; 310 311 // Creates a delegate which does not block at all. 312 explicit BlockingNetworkDelegate(BlockMode block_mode); 313 314 // For users to trigger a callback returning |response|. 315 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks. 316 // Only call if |block_mode_| == USER_CALLBACK. 317 void DoCallback(int response); 318 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response); 319 320 // Setters. 321 void set_retval(int retval) { 322 ASSERT_NE(USER_CALLBACK, block_mode_); 323 ASSERT_NE(ERR_IO_PENDING, retval); 324 ASSERT_NE(OK, retval); 325 retval_ = retval; 326 } 327 328 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then 329 // |auth_credentials_| will be passed with the response. 330 void set_auth_retval(AuthRequiredResponse auth_retval) { 331 ASSERT_NE(USER_CALLBACK, block_mode_); 332 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval); 333 auth_retval_ = auth_retval; 334 } 335 void set_auth_credentials(const AuthCredentials& auth_credentials) { 336 auth_credentials_ = auth_credentials; 337 } 338 339 void set_redirect_url(const GURL& url) { 340 redirect_url_ = url; 341 } 342 343 void set_block_on(int block_on) { 344 block_on_ = block_on; 345 } 346 347 // Allows the user to check in which state did we block. 348 Stage stage_blocked_for_callback() const { 349 EXPECT_EQ(USER_CALLBACK, block_mode_); 350 return stage_blocked_for_callback_; 351 } 352 353 private: 354 void RunCallback(int response, const CompletionCallback& callback); 355 void RunAuthCallback(AuthRequiredResponse response, 356 const AuthCallback& callback); 357 358 // TestNetworkDelegate implementation. 359 virtual int OnBeforeURLRequest(URLRequest* request, 360 const CompletionCallback& callback, 361 GURL* new_url) OVERRIDE; 362 363 virtual int OnBeforeSendHeaders(URLRequest* request, 364 const CompletionCallback& callback, 365 HttpRequestHeaders* headers) OVERRIDE; 366 367 virtual int OnHeadersReceived( 368 URLRequest* request, 369 const CompletionCallback& callback, 370 const HttpResponseHeaders* original_response_headers, 371 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE; 372 373 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired( 374 URLRequest* request, 375 const AuthChallengeInfo& auth_info, 376 const AuthCallback& callback, 377 AuthCredentials* credentials) OVERRIDE; 378 379 // Resets the callbacks and |stage_blocked_for_callback_|. 380 void Reset(); 381 382 // Checks whether we should block in |stage|. If yes, returns an error code 383 // and optionally sets up callback based on |block_mode_|. If no, returns OK. 384 int MaybeBlockStage(Stage stage, const CompletionCallback& callback); 385 386 // Configuration parameters, can be adjusted by public methods: 387 const BlockMode block_mode_; 388 389 // Values returned on blocking stages when mode is SYNCHRONOUS or 390 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING. 391 int retval_; // To be returned in non-auth stages. 392 AuthRequiredResponse auth_retval_; 393 394 GURL redirect_url_; // Used if non-empty. 395 int block_on_; // Bit mask: in which stages to block. 396 397 // |auth_credentials_| will be copied to |*target_auth_credential_| on 398 // callback. 399 AuthCredentials auth_credentials_; 400 AuthCredentials* target_auth_credentials_; 401 402 // Internal variables, not set by not the user: 403 // Last blocked stage waiting for user callback (unused if |block_mode_| != 404 // USER_CALLBACK). 405 Stage stage_blocked_for_callback_; 406 407 // Callback objects stored during blocking stages. 408 CompletionCallback callback_; 409 AuthCallback auth_callback_; 410 411 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_; 412 413 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate); 414}; 415 416BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode) 417 : block_mode_(block_mode), 418 retval_(OK), 419 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION), 420 block_on_(0), 421 target_auth_credentials_(NULL), 422 stage_blocked_for_callback_(NOT_BLOCKED), 423 weak_factory_(this) { 424} 425 426void BlockingNetworkDelegate::DoCallback(int response) { 427 ASSERT_EQ(USER_CALLBACK, block_mode_); 428 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_); 429 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_); 430 CompletionCallback callback = callback_; 431 Reset(); 432 RunCallback(response, callback); 433} 434 435void BlockingNetworkDelegate::DoAuthCallback( 436 NetworkDelegate::AuthRequiredResponse response) { 437 ASSERT_EQ(USER_CALLBACK, block_mode_); 438 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_); 439 AuthCallback auth_callback = auth_callback_; 440 Reset(); 441 RunAuthCallback(response, auth_callback); 442} 443 444void BlockingNetworkDelegate::RunCallback(int response, 445 const CompletionCallback& callback) { 446 callback.Run(response); 447} 448 449void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response, 450 const AuthCallback& callback) { 451 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) { 452 ASSERT_TRUE(target_auth_credentials_ != NULL); 453 *target_auth_credentials_ = auth_credentials_; 454 } 455 callback.Run(response); 456} 457 458int BlockingNetworkDelegate::OnBeforeURLRequest( 459 URLRequest* request, 460 const CompletionCallback& callback, 461 GURL* new_url) { 462 if (redirect_url_ == request->url()) 463 return OK; // We've already seen this request and redirected elsewhere. 464 465 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url); 466 467 if (!redirect_url_.is_empty()) 468 *new_url = redirect_url_; 469 470 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback); 471} 472 473int BlockingNetworkDelegate::OnBeforeSendHeaders( 474 URLRequest* request, 475 const CompletionCallback& callback, 476 HttpRequestHeaders* headers) { 477 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers); 478 479 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback); 480} 481 482int BlockingNetworkDelegate::OnHeadersReceived( 483 URLRequest* request, 484 const CompletionCallback& callback, 485 const HttpResponseHeaders* original_response_headers, 486 scoped_refptr<HttpResponseHeaders>* override_response_headers) { 487 TestNetworkDelegate::OnHeadersReceived( 488 request, callback, original_response_headers, 489 override_response_headers); 490 491 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback); 492} 493 494NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired( 495 URLRequest* request, 496 const AuthChallengeInfo& auth_info, 497 const AuthCallback& callback, 498 AuthCredentials* credentials) { 499 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback, 500 credentials); 501 // Check that the user has provided callback for the previous blocked stage. 502 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_); 503 504 if ((block_on_ & ON_AUTH_REQUIRED) == 0) { 505 return AUTH_REQUIRED_RESPONSE_NO_ACTION; 506 } 507 508 target_auth_credentials_ = credentials; 509 510 switch (block_mode_) { 511 case SYNCHRONOUS: 512 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) 513 *target_auth_credentials_ = auth_credentials_; 514 return auth_retval_; 515 516 case AUTO_CALLBACK: 517 base::MessageLoop::current()->PostTask( 518 FROM_HERE, 519 base::Bind(&BlockingNetworkDelegate::RunAuthCallback, 520 weak_factory_.GetWeakPtr(), auth_retval_, callback)); 521 return AUTH_REQUIRED_RESPONSE_IO_PENDING; 522 523 case USER_CALLBACK: 524 auth_callback_ = callback; 525 stage_blocked_for_callback_ = ON_AUTH_REQUIRED; 526 base::MessageLoop::current()->PostTask(FROM_HERE, 527 base::MessageLoop::QuitClosure()); 528 return AUTH_REQUIRED_RESPONSE_IO_PENDING; 529 } 530 NOTREACHED(); 531 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value. 532} 533 534void BlockingNetworkDelegate::Reset() { 535 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_); 536 stage_blocked_for_callback_ = NOT_BLOCKED; 537 callback_.Reset(); 538 auth_callback_.Reset(); 539} 540 541int BlockingNetworkDelegate::MaybeBlockStage( 542 BlockingNetworkDelegate::Stage stage, 543 const CompletionCallback& callback) { 544 // Check that the user has provided callback for the previous blocked stage. 545 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_); 546 547 if ((block_on_ & stage) == 0) { 548 return OK; 549 } 550 551 switch (block_mode_) { 552 case SYNCHRONOUS: 553 EXPECT_NE(OK, retval_); 554 return retval_; 555 556 case AUTO_CALLBACK: 557 base::MessageLoop::current()->PostTask( 558 FROM_HERE, 559 base::Bind(&BlockingNetworkDelegate::RunCallback, 560 weak_factory_.GetWeakPtr(), retval_, callback)); 561 return ERR_IO_PENDING; 562 563 case USER_CALLBACK: 564 callback_ = callback; 565 stage_blocked_for_callback_ = stage; 566 base::MessageLoop::current()->PostTask(FROM_HERE, 567 base::MessageLoop::QuitClosure()); 568 return ERR_IO_PENDING; 569 } 570 NOTREACHED(); 571 return 0; 572} 573 574class TestURLRequestContextWithProxy : public TestURLRequestContext { 575 public: 576 // Does not own |delegate|. 577 TestURLRequestContextWithProxy(const std::string& proxy, 578 NetworkDelegate* delegate) 579 : TestURLRequestContext(true) { 580 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy)); 581 set_network_delegate(delegate); 582 Init(); 583 } 584 virtual ~TestURLRequestContextWithProxy() {} 585}; 586 587} // namespace 588 589// Inherit PlatformTest since we require the autorelease pool on Mac OS X. 590class URLRequestTest : public PlatformTest { 591 public: 592 URLRequestTest() : default_context_(true) { 593 default_context_.set_network_delegate(&default_network_delegate_); 594 default_context_.set_net_log(&net_log_); 595 job_factory_.SetProtocolHandler("data", new DataProtocolHandler); 596 job_factory_.SetProtocolHandler( 597 "file", new FileProtocolHandler(base::MessageLoopProxy::current())); 598 default_context_.set_job_factory(&job_factory_); 599 default_context_.Init(); 600 } 601 virtual ~URLRequestTest() {} 602 603 // Adds the TestJobInterceptor to the default context. 604 TestJobInterceptor* AddTestInterceptor() { 605 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor(); 606 job_factory_.SetProtocolHandler("http", NULL); 607 job_factory_.SetProtocolHandler("http", protocol_handler_); 608 return protocol_handler_; 609 } 610 611 protected: 612 CapturingNetLog net_log_; 613 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest. 614 URLRequestJobFactoryImpl job_factory_; 615 TestURLRequestContext default_context_; 616}; 617 618TEST_F(URLRequestTest, AboutBlankTest) { 619 TestDelegate d; 620 { 621 URLRequest r(GURL("about:blank"), &d, &default_context_); 622 623 r.Start(); 624 EXPECT_TRUE(r.is_pending()); 625 626 base::RunLoop().Run(); 627 628 EXPECT_TRUE(!r.is_pending()); 629 EXPECT_FALSE(d.received_data_before_response()); 630 EXPECT_EQ(d.bytes_received(), 0); 631 EXPECT_EQ("", r.GetSocketAddress().host()); 632 EXPECT_EQ(0, r.GetSocketAddress().port()); 633 634 HttpRequestHeaders headers; 635 EXPECT_FALSE(r.GetFullRequestHeaders(&headers)); 636 } 637} 638 639TEST_F(URLRequestTest, DataURLImageTest) { 640 TestDelegate d; 641 { 642 // Use our nice little Chrome logo. 643 URLRequest r(GURL( 644 "data:image/png;base64," 645 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3" 646 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD" 647 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t" 648 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9" 649 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1" 650 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z" 651 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW" 652 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW" 653 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb" 654 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5" 655 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV" 656 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq" 657 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F" 658 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB" 659 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM" 660 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm" 661 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En" 662 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="), 663 &d, 664 &default_context_); 665 666 r.Start(); 667 EXPECT_TRUE(r.is_pending()); 668 669 base::RunLoop().Run(); 670 671 EXPECT_TRUE(!r.is_pending()); 672 EXPECT_FALSE(d.received_data_before_response()); 673 EXPECT_EQ(d.bytes_received(), 911); 674 EXPECT_EQ("", r.GetSocketAddress().host()); 675 EXPECT_EQ(0, r.GetSocketAddress().port()); 676 677 HttpRequestHeaders headers; 678 EXPECT_FALSE(r.GetFullRequestHeaders(&headers)); 679 } 680} 681 682TEST_F(URLRequestTest, FileTest) { 683 base::FilePath app_path; 684 PathService::Get(base::FILE_EXE, &app_path); 685 GURL app_url = FilePathToFileURL(app_path); 686 687 TestDelegate d; 688 { 689 URLRequest r(app_url, &d, &default_context_); 690 691 r.Start(); 692 EXPECT_TRUE(r.is_pending()); 693 694 base::RunLoop().Run(); 695 696 int64 file_size = -1; 697 EXPECT_TRUE(file_util::GetFileSize(app_path, &file_size)); 698 699 EXPECT_TRUE(!r.is_pending()); 700 EXPECT_EQ(1, d.response_started_count()); 701 EXPECT_FALSE(d.received_data_before_response()); 702 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size)); 703 EXPECT_EQ("", r.GetSocketAddress().host()); 704 EXPECT_EQ(0, r.GetSocketAddress().port()); 705 706 HttpRequestHeaders headers; 707 EXPECT_FALSE(r.GetFullRequestHeaders(&headers)); 708 } 709} 710 711TEST_F(URLRequestTest, FileTestCancel) { 712 base::FilePath app_path; 713 PathService::Get(base::FILE_EXE, &app_path); 714 GURL app_url = FilePathToFileURL(app_path); 715 716 TestDelegate d; 717 { 718 URLRequest r(app_url, &d, &default_context_); 719 720 r.Start(); 721 EXPECT_TRUE(r.is_pending()); 722 r.Cancel(); 723 } 724 // Async cancellation should be safe even when URLRequest has been already 725 // destroyed. 726 base::RunLoop().RunUntilIdle(); 727} 728 729TEST_F(URLRequestTest, FileTestFullSpecifiedRange) { 730 const size_t buffer_size = 4000; 731 scoped_ptr<char[]> buffer(new char[buffer_size]); 732 FillBuffer(buffer.get(), buffer_size); 733 734 base::FilePath temp_path; 735 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path)); 736 GURL temp_url = FilePathToFileURL(temp_path); 737 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size)); 738 739 int64 file_size; 740 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size)); 741 742 const size_t first_byte_position = 500; 743 const size_t last_byte_position = buffer_size - first_byte_position; 744 const size_t content_length = last_byte_position - first_byte_position + 1; 745 std::string partial_buffer_string(buffer.get() + first_byte_position, 746 buffer.get() + last_byte_position + 1); 747 748 TestDelegate d; 749 { 750 URLRequest r(temp_url, &d, &default_context_); 751 752 HttpRequestHeaders headers; 753 headers.SetHeader(HttpRequestHeaders::kRange, 754 base::StringPrintf( 755 "bytes=%" PRIuS "-%" PRIuS, 756 first_byte_position, last_byte_position)); 757 r.SetExtraRequestHeaders(headers); 758 r.Start(); 759 EXPECT_TRUE(r.is_pending()); 760 761 base::RunLoop().Run(); 762 EXPECT_TRUE(!r.is_pending()); 763 EXPECT_EQ(1, d.response_started_count()); 764 EXPECT_FALSE(d.received_data_before_response()); 765 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received()); 766 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed. 767 EXPECT_TRUE(partial_buffer_string == d.data_received()); 768 } 769 770 EXPECT_TRUE(base::DeleteFile(temp_path, false)); 771} 772 773TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) { 774 const size_t buffer_size = 4000; 775 scoped_ptr<char[]> buffer(new char[buffer_size]); 776 FillBuffer(buffer.get(), buffer_size); 777 778 base::FilePath temp_path; 779 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path)); 780 GURL temp_url = FilePathToFileURL(temp_path); 781 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size)); 782 783 int64 file_size; 784 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size)); 785 786 const size_t first_byte_position = 500; 787 const size_t last_byte_position = buffer_size - 1; 788 const size_t content_length = last_byte_position - first_byte_position + 1; 789 std::string partial_buffer_string(buffer.get() + first_byte_position, 790 buffer.get() + last_byte_position + 1); 791 792 TestDelegate d; 793 { 794 URLRequest r(temp_url, &d, &default_context_); 795 796 HttpRequestHeaders headers; 797 headers.SetHeader(HttpRequestHeaders::kRange, 798 base::StringPrintf("bytes=%" PRIuS "-", 799 first_byte_position)); 800 r.SetExtraRequestHeaders(headers); 801 r.Start(); 802 EXPECT_TRUE(r.is_pending()); 803 804 base::RunLoop().Run(); 805 EXPECT_TRUE(!r.is_pending()); 806 EXPECT_EQ(1, d.response_started_count()); 807 EXPECT_FALSE(d.received_data_before_response()); 808 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received()); 809 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed. 810 EXPECT_TRUE(partial_buffer_string == d.data_received()); 811 } 812 813 EXPECT_TRUE(base::DeleteFile(temp_path, false)); 814} 815 816TEST_F(URLRequestTest, FileTestMultipleRanges) { 817 const size_t buffer_size = 400000; 818 scoped_ptr<char[]> buffer(new char[buffer_size]); 819 FillBuffer(buffer.get(), buffer_size); 820 821 base::FilePath temp_path; 822 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path)); 823 GURL temp_url = FilePathToFileURL(temp_path); 824 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size)); 825 826 int64 file_size; 827 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size)); 828 829 TestDelegate d; 830 { 831 URLRequest r(temp_url, &d, &default_context_); 832 833 HttpRequestHeaders headers; 834 headers.SetHeader(HttpRequestHeaders::kRange, 835 "bytes=0-0,10-200,200-300"); 836 r.SetExtraRequestHeaders(headers); 837 r.Start(); 838 EXPECT_TRUE(r.is_pending()); 839 840 base::RunLoop().Run(); 841 EXPECT_TRUE(d.request_failed()); 842 } 843 844 EXPECT_TRUE(base::DeleteFile(temp_path, false)); 845} 846 847TEST_F(URLRequestTest, InvalidUrlTest) { 848 TestDelegate d; 849 { 850 URLRequest r(GURL("invalid url"), &d, &default_context_); 851 852 r.Start(); 853 EXPECT_TRUE(r.is_pending()); 854 855 base::RunLoop().Run(); 856 EXPECT_TRUE(d.request_failed()); 857 } 858} 859 860#if defined(OS_WIN) 861TEST_F(URLRequestTest, ResolveShortcutTest) { 862 base::FilePath app_path; 863 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 864 app_path = app_path.AppendASCII("net"); 865 app_path = app_path.AppendASCII("data"); 866 app_path = app_path.AppendASCII("url_request_unittest"); 867 app_path = app_path.AppendASCII("with-headers.html"); 868 869 std::wstring lnk_path = app_path.value() + L".lnk"; 870 871 base::win::ScopedCOMInitializer com_initializer; 872 873 // Temporarily create a shortcut for test 874 { 875 base::win::ScopedComPtr<IShellLink> shell; 876 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL, 877 CLSCTX_INPROC_SERVER))); 878 base::win::ScopedComPtr<IPersistFile> persist; 879 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive()))); 880 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str()))); 881 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest"))); 882 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE))); 883 } 884 885 TestDelegate d; 886 { 887 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)), &d, 888 &default_context_); 889 890 r.Start(); 891 EXPECT_TRUE(r.is_pending()); 892 893 base::RunLoop().Run(); 894 895 WIN32_FILE_ATTRIBUTE_DATA data; 896 GetFileAttributesEx(app_path.value().c_str(), 897 GetFileExInfoStandard, &data); 898 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ, 899 FILE_SHARE_READ, NULL, OPEN_EXISTING, 900 FILE_ATTRIBUTE_NORMAL, NULL); 901 EXPECT_NE(INVALID_HANDLE_VALUE, file); 902 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]); 903 DWORD read_size; 904 BOOL result; 905 result = ReadFile(file, buffer.get(), data.nFileSizeLow, 906 &read_size, NULL); 907 std::string content(buffer.get(), read_size); 908 CloseHandle(file); 909 910 EXPECT_TRUE(!r.is_pending()); 911 EXPECT_EQ(1, d.received_redirect_count()); 912 EXPECT_EQ(content, d.data_received()); 913 } 914 915 // Clean the shortcut 916 DeleteFile(lnk_path.c_str()); 917} 918#endif // defined(OS_WIN) 919 920TEST_F(URLRequestTest, FileDirCancelTest) { 921 // Put in mock resource provider. 922 NetModule::SetResourceProvider(TestNetResourceProvider); 923 924 TestDelegate d; 925 { 926 base::FilePath file_path; 927 PathService::Get(base::DIR_SOURCE_ROOT, &file_path); 928 file_path = file_path.Append(FILE_PATH_LITERAL("net")); 929 file_path = file_path.Append(FILE_PATH_LITERAL("data")); 930 931 URLRequest req(FilePathToFileURL(file_path), &d, &default_context_); 932 req.Start(); 933 EXPECT_TRUE(req.is_pending()); 934 935 d.set_cancel_in_received_data_pending(true); 936 937 base::RunLoop().Run(); 938 } 939 940 // Take out mock resource provider. 941 NetModule::SetResourceProvider(NULL); 942} 943 944TEST_F(URLRequestTest, FileDirRedirectNoCrash) { 945 // There is an implicit redirect when loading a file path that matches a 946 // directory and does not end with a slash. Ensure that following such 947 // redirects does not crash. See http://crbug.com/18686. 948 949 base::FilePath path; 950 PathService::Get(base::DIR_SOURCE_ROOT, &path); 951 path = path.Append(FILE_PATH_LITERAL("net")); 952 path = path.Append(FILE_PATH_LITERAL("data")); 953 path = path.Append(FILE_PATH_LITERAL("url_request_unittest")); 954 955 TestDelegate d; 956 URLRequest req(FilePathToFileURL(path), &d, &default_context_); 957 req.Start(); 958 base::RunLoop().Run(); 959 960 ASSERT_EQ(1, d.received_redirect_count()); 961 ASSERT_LT(0, d.bytes_received()); 962 ASSERT_FALSE(d.request_failed()); 963 ASSERT_TRUE(req.status().is_success()); 964} 965 966#if defined(OS_WIN) 967// Don't accept the url "file:///" on windows. See http://crbug.com/1474. 968TEST_F(URLRequestTest, FileDirRedirectSingleSlash) { 969 TestDelegate d; 970 URLRequest req(GURL("file:///"), &d, &default_context_); 971 req.Start(); 972 base::RunLoop().Run(); 973 974 ASSERT_EQ(1, d.received_redirect_count()); 975 ASSERT_FALSE(req.status().is_success()); 976} 977#endif 978 979// Custom URLRequestJobs for use with interceptor tests 980class RestartTestJob : public URLRequestTestJob { 981 public: 982 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate) 983 : URLRequestTestJob(request, network_delegate, true) {} 984 protected: 985 virtual void StartAsync() OVERRIDE { 986 this->NotifyRestartRequired(); 987 } 988 private: 989 virtual ~RestartTestJob() {} 990}; 991 992class CancelTestJob : public URLRequestTestJob { 993 public: 994 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate) 995 : URLRequestTestJob(request, network_delegate, true) {} 996 protected: 997 virtual void StartAsync() OVERRIDE { 998 request_->Cancel(); 999 } 1000 private: 1001 virtual ~CancelTestJob() {} 1002}; 1003 1004class CancelThenRestartTestJob : public URLRequestTestJob { 1005 public: 1006 explicit CancelThenRestartTestJob(URLRequest* request, 1007 NetworkDelegate* network_delegate) 1008 : URLRequestTestJob(request, network_delegate, true) { 1009 } 1010 protected: 1011 virtual void StartAsync() OVERRIDE { 1012 request_->Cancel(); 1013 this->NotifyRestartRequired(); 1014 } 1015 private: 1016 virtual ~CancelThenRestartTestJob() {} 1017}; 1018 1019// An Interceptor for use with interceptor tests 1020class TestInterceptor : URLRequest::Interceptor { 1021 public: 1022 TestInterceptor() 1023 : intercept_main_request_(false), restart_main_request_(false), 1024 cancel_main_request_(false), cancel_then_restart_main_request_(false), 1025 simulate_main_network_error_(false), 1026 intercept_redirect_(false), cancel_redirect_request_(false), 1027 intercept_final_response_(false), cancel_final_request_(false), 1028 did_intercept_main_(false), did_restart_main_(false), 1029 did_cancel_main_(false), did_cancel_then_restart_main_(false), 1030 did_simulate_error_main_(false), 1031 did_intercept_redirect_(false), did_cancel_redirect_(false), 1032 did_intercept_final_(false), did_cancel_final_(false) { 1033 URLRequest::Deprecated::RegisterRequestInterceptor(this); 1034 } 1035 1036 virtual ~TestInterceptor() { 1037 URLRequest::Deprecated::UnregisterRequestInterceptor(this); 1038 } 1039 1040 virtual URLRequestJob* MaybeIntercept( 1041 URLRequest* request, 1042 NetworkDelegate* network_delegate) OVERRIDE { 1043 if (restart_main_request_) { 1044 restart_main_request_ = false; 1045 did_restart_main_ = true; 1046 return new RestartTestJob(request, network_delegate); 1047 } 1048 if (cancel_main_request_) { 1049 cancel_main_request_ = false; 1050 did_cancel_main_ = true; 1051 return new CancelTestJob(request, network_delegate); 1052 } 1053 if (cancel_then_restart_main_request_) { 1054 cancel_then_restart_main_request_ = false; 1055 did_cancel_then_restart_main_ = true; 1056 return new CancelThenRestartTestJob(request, network_delegate); 1057 } 1058 if (simulate_main_network_error_) { 1059 simulate_main_network_error_ = false; 1060 did_simulate_error_main_ = true; 1061 // will error since the requeted url is not one of its canned urls 1062 return new URLRequestTestJob(request, network_delegate, true); 1063 } 1064 if (!intercept_main_request_) 1065 return NULL; 1066 intercept_main_request_ = false; 1067 did_intercept_main_ = true; 1068 URLRequestTestJob* job = new URLRequestTestJob(request, 1069 network_delegate, 1070 main_headers_, 1071 main_data_, 1072 true); 1073 job->set_load_timing_info(main_request_load_timing_info_); 1074 return job; 1075 } 1076 1077 virtual URLRequestJob* MaybeInterceptRedirect( 1078 URLRequest* request, 1079 NetworkDelegate* network_delegate, 1080 const GURL& location) OVERRIDE { 1081 if (cancel_redirect_request_) { 1082 cancel_redirect_request_ = false; 1083 did_cancel_redirect_ = true; 1084 return new CancelTestJob(request, network_delegate); 1085 } 1086 if (!intercept_redirect_) 1087 return NULL; 1088 intercept_redirect_ = false; 1089 did_intercept_redirect_ = true; 1090 return new URLRequestTestJob(request, 1091 network_delegate, 1092 redirect_headers_, 1093 redirect_data_, 1094 true); 1095 } 1096 1097 virtual URLRequestJob* MaybeInterceptResponse( 1098 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE { 1099 if (cancel_final_request_) { 1100 cancel_final_request_ = false; 1101 did_cancel_final_ = true; 1102 return new CancelTestJob(request, network_delegate); 1103 } 1104 if (!intercept_final_response_) 1105 return NULL; 1106 intercept_final_response_ = false; 1107 did_intercept_final_ = true; 1108 return new URLRequestTestJob(request, 1109 network_delegate, 1110 final_headers_, 1111 final_data_, 1112 true); 1113 } 1114 1115 // Whether to intercept the main request, and if so the response to return and 1116 // the LoadTimingInfo to use. 1117 bool intercept_main_request_; 1118 std::string main_headers_; 1119 std::string main_data_; 1120 LoadTimingInfo main_request_load_timing_info_; 1121 1122 // Other actions we take at MaybeIntercept time 1123 bool restart_main_request_; 1124 bool cancel_main_request_; 1125 bool cancel_then_restart_main_request_; 1126 bool simulate_main_network_error_; 1127 1128 // Whether to intercept redirects, and if so the response to return. 1129 bool intercept_redirect_; 1130 std::string redirect_headers_; 1131 std::string redirect_data_; 1132 1133 // Other actions we can take at MaybeInterceptRedirect time 1134 bool cancel_redirect_request_; 1135 1136 // Whether to intercept final response, and if so the response to return. 1137 bool intercept_final_response_; 1138 std::string final_headers_; 1139 std::string final_data_; 1140 1141 // Other actions we can take at MaybeInterceptResponse time 1142 bool cancel_final_request_; 1143 1144 // If we did something or not 1145 bool did_intercept_main_; 1146 bool did_restart_main_; 1147 bool did_cancel_main_; 1148 bool did_cancel_then_restart_main_; 1149 bool did_simulate_error_main_; 1150 bool did_intercept_redirect_; 1151 bool did_cancel_redirect_; 1152 bool did_intercept_final_; 1153 bool did_cancel_final_; 1154 1155 // Static getters for canned response header and data strings 1156 1157 static std::string ok_data() { 1158 return URLRequestTestJob::test_data_1(); 1159 } 1160 1161 static std::string ok_headers() { 1162 return URLRequestTestJob::test_headers(); 1163 } 1164 1165 static std::string redirect_data() { 1166 return std::string(); 1167 } 1168 1169 static std::string redirect_headers() { 1170 return URLRequestTestJob::test_redirect_headers(); 1171 } 1172 1173 static std::string error_data() { 1174 return std::string("ohhh nooooo mr. bill!"); 1175 } 1176 1177 static std::string error_headers() { 1178 return URLRequestTestJob::test_error_headers(); 1179 } 1180}; 1181 1182TEST_F(URLRequestTest, Intercept) { 1183 TestInterceptor interceptor; 1184 1185 // intercept the main request and respond with a simple response 1186 interceptor.intercept_main_request_ = true; 1187 interceptor.main_headers_ = TestInterceptor::ok_headers(); 1188 interceptor.main_data_ = TestInterceptor::ok_data(); 1189 1190 TestDelegate d; 1191 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1192 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data(); 1193 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data(); 1194 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data(); 1195 req.SetUserData(NULL, user_data0); 1196 req.SetUserData(&user_data1, user_data1); 1197 req.SetUserData(&user_data2, user_data2); 1198 req.set_method("GET"); 1199 req.Start(); 1200 base::RunLoop().Run(); 1201 1202 // Make sure we can retrieve our specific user data 1203 EXPECT_EQ(user_data0, req.GetUserData(NULL)); 1204 EXPECT_EQ(user_data1, req.GetUserData(&user_data1)); 1205 EXPECT_EQ(user_data2, req.GetUserData(&user_data2)); 1206 1207 // Check the interceptor got called as expected 1208 EXPECT_TRUE(interceptor.did_intercept_main_); 1209 1210 // Check we got one good response 1211 EXPECT_TRUE(req.status().is_success()); 1212 EXPECT_EQ(200, req.response_headers()->response_code()); 1213 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received()); 1214 EXPECT_EQ(1, d.response_started_count()); 1215 EXPECT_EQ(0, d.received_redirect_count()); 1216} 1217 1218TEST_F(URLRequestTest, InterceptRedirect) { 1219 TestInterceptor interceptor; 1220 1221 // intercept the main request and respond with a redirect 1222 interceptor.intercept_main_request_ = true; 1223 interceptor.main_headers_ = TestInterceptor::redirect_headers(); 1224 interceptor.main_data_ = TestInterceptor::redirect_data(); 1225 1226 // intercept that redirect and respond a final OK response 1227 interceptor.intercept_redirect_ = true; 1228 interceptor.redirect_headers_ = TestInterceptor::ok_headers(); 1229 interceptor.redirect_data_ = TestInterceptor::ok_data(); 1230 1231 TestDelegate d; 1232 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1233 req.set_method("GET"); 1234 req.Start(); 1235 base::RunLoop().Run(); 1236 1237 // Check the interceptor got called as expected 1238 EXPECT_TRUE(interceptor.did_intercept_main_); 1239 EXPECT_TRUE(interceptor.did_intercept_redirect_); 1240 1241 // Check we got one good response 1242 EXPECT_TRUE(req.status().is_success()); 1243 if (req.status().is_success()) { 1244 EXPECT_EQ(200, req.response_headers()->response_code()); 1245 } 1246 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received()); 1247 EXPECT_EQ(1, d.response_started_count()); 1248 EXPECT_EQ(0, d.received_redirect_count()); 1249} 1250 1251TEST_F(URLRequestTest, InterceptServerError) { 1252 TestInterceptor interceptor; 1253 1254 // intercept the main request to generate a server error response 1255 interceptor.intercept_main_request_ = true; 1256 interceptor.main_headers_ = TestInterceptor::error_headers(); 1257 interceptor.main_data_ = TestInterceptor::error_data(); 1258 1259 // intercept that error and respond with an OK response 1260 interceptor.intercept_final_response_ = true; 1261 interceptor.final_headers_ = TestInterceptor::ok_headers(); 1262 interceptor.final_data_ = TestInterceptor::ok_data(); 1263 1264 TestDelegate d; 1265 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1266 req.set_method("GET"); 1267 req.Start(); 1268 base::RunLoop().Run(); 1269 1270 // Check the interceptor got called as expected 1271 EXPECT_TRUE(interceptor.did_intercept_main_); 1272 EXPECT_TRUE(interceptor.did_intercept_final_); 1273 1274 // Check we got one good response 1275 EXPECT_TRUE(req.status().is_success()); 1276 EXPECT_EQ(200, req.response_headers()->response_code()); 1277 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received()); 1278 EXPECT_EQ(1, d.response_started_count()); 1279 EXPECT_EQ(0, d.received_redirect_count()); 1280} 1281 1282TEST_F(URLRequestTest, InterceptNetworkError) { 1283 TestInterceptor interceptor; 1284 1285 // intercept the main request to simulate a network error 1286 interceptor.simulate_main_network_error_ = true; 1287 1288 // intercept that error and respond with an OK response 1289 interceptor.intercept_final_response_ = true; 1290 interceptor.final_headers_ = TestInterceptor::ok_headers(); 1291 interceptor.final_data_ = TestInterceptor::ok_data(); 1292 1293 TestDelegate d; 1294 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1295 req.set_method("GET"); 1296 req.Start(); 1297 base::RunLoop().Run(); 1298 1299 // Check the interceptor got called as expected 1300 EXPECT_TRUE(interceptor.did_simulate_error_main_); 1301 EXPECT_TRUE(interceptor.did_intercept_final_); 1302 1303 // Check we received one good response 1304 EXPECT_TRUE(req.status().is_success()); 1305 EXPECT_EQ(200, req.response_headers()->response_code()); 1306 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received()); 1307 EXPECT_EQ(1, d.response_started_count()); 1308 EXPECT_EQ(0, d.received_redirect_count()); 1309} 1310 1311TEST_F(URLRequestTest, InterceptRestartRequired) { 1312 TestInterceptor interceptor; 1313 1314 // restart the main request 1315 interceptor.restart_main_request_ = true; 1316 1317 // then intercept the new main request and respond with an OK response 1318 interceptor.intercept_main_request_ = true; 1319 interceptor.main_headers_ = TestInterceptor::ok_headers(); 1320 interceptor.main_data_ = TestInterceptor::ok_data(); 1321 1322 TestDelegate d; 1323 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1324 req.set_method("GET"); 1325 req.Start(); 1326 base::RunLoop().Run(); 1327 1328 // Check the interceptor got called as expected 1329 EXPECT_TRUE(interceptor.did_restart_main_); 1330 EXPECT_TRUE(interceptor.did_intercept_main_); 1331 1332 // Check we received one good response 1333 EXPECT_TRUE(req.status().is_success()); 1334 if (req.status().is_success()) { 1335 EXPECT_EQ(200, req.response_headers()->response_code()); 1336 } 1337 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received()); 1338 EXPECT_EQ(1, d.response_started_count()); 1339 EXPECT_EQ(0, d.received_redirect_count()); 1340} 1341 1342TEST_F(URLRequestTest, InterceptRespectsCancelMain) { 1343 TestInterceptor interceptor; 1344 1345 // intercept the main request and cancel from within the restarted job 1346 interceptor.cancel_main_request_ = true; 1347 1348 // setup to intercept final response and override it with an OK response 1349 interceptor.intercept_final_response_ = true; 1350 interceptor.final_headers_ = TestInterceptor::ok_headers(); 1351 interceptor.final_data_ = TestInterceptor::ok_data(); 1352 1353 TestDelegate d; 1354 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1355 req.set_method("GET"); 1356 req.Start(); 1357 base::RunLoop().Run(); 1358 1359 // Check the interceptor got called as expected 1360 EXPECT_TRUE(interceptor.did_cancel_main_); 1361 EXPECT_FALSE(interceptor.did_intercept_final_); 1362 1363 // Check we see a canceled request 1364 EXPECT_FALSE(req.status().is_success()); 1365 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status()); 1366} 1367 1368TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) { 1369 TestInterceptor interceptor; 1370 1371 // intercept the main request and respond with a redirect 1372 interceptor.intercept_main_request_ = true; 1373 interceptor.main_headers_ = TestInterceptor::redirect_headers(); 1374 interceptor.main_data_ = TestInterceptor::redirect_data(); 1375 1376 // intercept the redirect and cancel from within that job 1377 interceptor.cancel_redirect_request_ = true; 1378 1379 // setup to intercept final response and override it with an OK response 1380 interceptor.intercept_final_response_ = true; 1381 interceptor.final_headers_ = TestInterceptor::ok_headers(); 1382 interceptor.final_data_ = TestInterceptor::ok_data(); 1383 1384 TestDelegate d; 1385 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1386 req.set_method("GET"); 1387 req.Start(); 1388 base::RunLoop().Run(); 1389 1390 // Check the interceptor got called as expected 1391 EXPECT_TRUE(interceptor.did_intercept_main_); 1392 EXPECT_TRUE(interceptor.did_cancel_redirect_); 1393 EXPECT_FALSE(interceptor.did_intercept_final_); 1394 1395 // Check we see a canceled request 1396 EXPECT_FALSE(req.status().is_success()); 1397 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status()); 1398} 1399 1400TEST_F(URLRequestTest, InterceptRespectsCancelFinal) { 1401 TestInterceptor interceptor; 1402 1403 // intercept the main request to simulate a network error 1404 interceptor.simulate_main_network_error_ = true; 1405 1406 // setup to intercept final response and cancel from within that job 1407 interceptor.cancel_final_request_ = true; 1408 1409 TestDelegate d; 1410 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1411 req.set_method("GET"); 1412 req.Start(); 1413 base::RunLoop().Run(); 1414 1415 // Check the interceptor got called as expected 1416 EXPECT_TRUE(interceptor.did_simulate_error_main_); 1417 EXPECT_TRUE(interceptor.did_cancel_final_); 1418 1419 // Check we see a canceled request 1420 EXPECT_FALSE(req.status().is_success()); 1421 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status()); 1422} 1423 1424TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) { 1425 TestInterceptor interceptor; 1426 1427 // intercept the main request and cancel then restart from within that job 1428 interceptor.cancel_then_restart_main_request_ = true; 1429 1430 // setup to intercept final response and override it with an OK response 1431 interceptor.intercept_final_response_ = true; 1432 interceptor.final_headers_ = TestInterceptor::ok_headers(); 1433 interceptor.final_data_ = TestInterceptor::ok_data(); 1434 1435 TestDelegate d; 1436 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1437 req.set_method("GET"); 1438 req.Start(); 1439 base::RunLoop().Run(); 1440 1441 // Check the interceptor got called as expected 1442 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_); 1443 EXPECT_FALSE(interceptor.did_intercept_final_); 1444 1445 // Check we see a canceled request 1446 EXPECT_FALSE(req.status().is_success()); 1447 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status()); 1448} 1449 1450LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing, 1451 URLRequestContext* context) { 1452 TestInterceptor interceptor; 1453 interceptor.intercept_main_request_ = true; 1454 interceptor.main_request_load_timing_info_ = job_load_timing; 1455 TestDelegate d; 1456 URLRequest req(GURL("http://test_intercept/foo"), &d, context); 1457 req.Start(); 1458 base::RunLoop().Run(); 1459 1460 LoadTimingInfo resulting_load_timing; 1461 req.GetLoadTimingInfo(&resulting_load_timing); 1462 1463 // None of these should be modified by the URLRequest. 1464 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused); 1465 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id); 1466 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start); 1467 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end); 1468 EXPECT_EQ(job_load_timing.receive_headers_end, 1469 resulting_load_timing.receive_headers_end); 1470 1471 return resulting_load_timing; 1472} 1473 1474// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not 1475// reused. |connect_time_flags| is used to indicate if there should be dns 1476// or SSL times, and |used_proxy| is used for proxy times. 1477LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now, 1478 int connect_time_flags, 1479 bool used_proxy) { 1480 LoadTimingInfo load_timing; 1481 load_timing.socket_log_id = 1; 1482 1483 if (used_proxy) { 1484 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1); 1485 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2); 1486 } 1487 1488 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing; 1489 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) { 1490 connect_timing.dns_start = now + base::TimeDelta::FromDays(3); 1491 connect_timing.dns_end = now + base::TimeDelta::FromDays(4); 1492 } 1493 connect_timing.connect_start = now + base::TimeDelta::FromDays(5); 1494 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) { 1495 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6); 1496 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7); 1497 } 1498 connect_timing.connect_end = now + base::TimeDelta::FromDays(8); 1499 1500 load_timing.send_start = now + base::TimeDelta::FromDays(9); 1501 load_timing.send_end = now + base::TimeDelta::FromDays(10); 1502 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11); 1503 return load_timing; 1504} 1505 1506// Same as above, but in the case of a reused socket. 1507LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now, 1508 bool used_proxy) { 1509 LoadTimingInfo load_timing; 1510 load_timing.socket_log_id = 1; 1511 load_timing.socket_reused = true; 1512 1513 if (used_proxy) { 1514 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1); 1515 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2); 1516 } 1517 1518 load_timing.send_start = now + base::TimeDelta::FromDays(9); 1519 load_timing.send_end = now + base::TimeDelta::FromDays(10); 1520 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11); 1521 return load_timing; 1522} 1523 1524// Basic test that the intercept + load timing tests work. 1525TEST_F(URLRequestTest, InterceptLoadTiming) { 1526 base::TimeTicks now = base::TimeTicks::Now(); 1527 LoadTimingInfo job_load_timing = 1528 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false); 1529 1530 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing, 1531 &default_context_); 1532 1533 // Nothing should have been changed by the URLRequest. 1534 EXPECT_EQ(job_load_timing.proxy_resolve_start, 1535 load_timing_result.proxy_resolve_start); 1536 EXPECT_EQ(job_load_timing.proxy_resolve_end, 1537 load_timing_result.proxy_resolve_end); 1538 EXPECT_EQ(job_load_timing.connect_timing.dns_start, 1539 load_timing_result.connect_timing.dns_start); 1540 EXPECT_EQ(job_load_timing.connect_timing.dns_end, 1541 load_timing_result.connect_timing.dns_end); 1542 EXPECT_EQ(job_load_timing.connect_timing.connect_start, 1543 load_timing_result.connect_timing.connect_start); 1544 EXPECT_EQ(job_load_timing.connect_timing.connect_end, 1545 load_timing_result.connect_timing.connect_end); 1546 EXPECT_EQ(job_load_timing.connect_timing.ssl_start, 1547 load_timing_result.connect_timing.ssl_start); 1548 EXPECT_EQ(job_load_timing.connect_timing.ssl_end, 1549 load_timing_result.connect_timing.ssl_end); 1550 1551 // Redundant sanity check. 1552 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES); 1553} 1554 1555// Another basic test, with proxy and SSL times, but no DNS times. 1556TEST_F(URLRequestTest, InterceptLoadTimingProxy) { 1557 base::TimeTicks now = base::TimeTicks::Now(); 1558 LoadTimingInfo job_load_timing = 1559 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true); 1560 1561 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing, 1562 &default_context_); 1563 1564 // Nothing should have been changed by the URLRequest. 1565 EXPECT_EQ(job_load_timing.proxy_resolve_start, 1566 load_timing_result.proxy_resolve_start); 1567 EXPECT_EQ(job_load_timing.proxy_resolve_end, 1568 load_timing_result.proxy_resolve_end); 1569 EXPECT_EQ(job_load_timing.connect_timing.dns_start, 1570 load_timing_result.connect_timing.dns_start); 1571 EXPECT_EQ(job_load_timing.connect_timing.dns_end, 1572 load_timing_result.connect_timing.dns_end); 1573 EXPECT_EQ(job_load_timing.connect_timing.connect_start, 1574 load_timing_result.connect_timing.connect_start); 1575 EXPECT_EQ(job_load_timing.connect_timing.connect_end, 1576 load_timing_result.connect_timing.connect_end); 1577 EXPECT_EQ(job_load_timing.connect_timing.ssl_start, 1578 load_timing_result.connect_timing.ssl_start); 1579 EXPECT_EQ(job_load_timing.connect_timing.ssl_end, 1580 load_timing_result.connect_timing.ssl_end); 1581 1582 // Redundant sanity check. 1583 TestLoadTimingNotReusedWithProxy(load_timing_result, 1584 CONNECT_TIMING_HAS_SSL_TIMES); 1585} 1586 1587// Make sure that URLRequest correctly adjusts proxy times when they're before 1588// |request_start|, due to already having a connected socket. This happens in 1589// the case of reusing a SPDY session or HTTP pipeline. The connected socket is 1590// not considered reused in this test (May be a preconnect). 1591// 1592// To mix things up from the test above, assumes DNS times but no SSL times. 1593TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) { 1594 base::TimeTicks now = base::TimeTicks::Now(); 1595 LoadTimingInfo job_load_timing = 1596 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true); 1597 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6); 1598 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5); 1599 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4); 1600 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3); 1601 job_load_timing.connect_timing.connect_start = 1602 now - base::TimeDelta::FromDays(2); 1603 job_load_timing.connect_timing.connect_end = 1604 now - base::TimeDelta::FromDays(1); 1605 1606 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing, 1607 &default_context_); 1608 1609 // Proxy times, connect times, and DNS times should all be replaced with 1610 // request_start. 1611 EXPECT_EQ(load_timing_result.request_start, 1612 load_timing_result.proxy_resolve_start); 1613 EXPECT_EQ(load_timing_result.request_start, 1614 load_timing_result.proxy_resolve_end); 1615 EXPECT_EQ(load_timing_result.request_start, 1616 load_timing_result.connect_timing.dns_start); 1617 EXPECT_EQ(load_timing_result.request_start, 1618 load_timing_result.connect_timing.dns_end); 1619 EXPECT_EQ(load_timing_result.request_start, 1620 load_timing_result.connect_timing.connect_start); 1621 EXPECT_EQ(load_timing_result.request_start, 1622 load_timing_result.connect_timing.connect_end); 1623 1624 // Other times should have been left null. 1625 TestLoadTimingNotReusedWithProxy(load_timing_result, 1626 CONNECT_TIMING_HAS_DNS_TIMES); 1627} 1628 1629// Same as above, but in the reused case. 1630TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) { 1631 base::TimeTicks now = base::TimeTicks::Now(); 1632 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true); 1633 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4); 1634 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3); 1635 1636 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing, 1637 &default_context_); 1638 1639 // Proxy times and connect times should all be replaced with request_start. 1640 EXPECT_EQ(load_timing_result.request_start, 1641 load_timing_result.proxy_resolve_start); 1642 EXPECT_EQ(load_timing_result.request_start, 1643 load_timing_result.proxy_resolve_end); 1644 1645 // Other times should have been left null. 1646 TestLoadTimingReusedWithProxy(load_timing_result); 1647} 1648 1649// Make sure that URLRequest correctly adjusts connect times when they're before 1650// |request_start|, due to reusing a connected socket. The connected socket is 1651// not considered reused in this test (May be a preconnect). 1652// 1653// To mix things up, the request has SSL times, but no DNS times. 1654TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) { 1655 base::TimeTicks now = base::TimeTicks::Now(); 1656 LoadTimingInfo job_load_timing = 1657 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false); 1658 job_load_timing.connect_timing.connect_start = 1659 now - base::TimeDelta::FromDays(1); 1660 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2); 1661 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3); 1662 job_load_timing.connect_timing.connect_end = 1663 now - base::TimeDelta::FromDays(4); 1664 1665 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing, 1666 &default_context_); 1667 1668 // Connect times, and SSL times should be replaced with request_start. 1669 EXPECT_EQ(load_timing_result.request_start, 1670 load_timing_result.connect_timing.connect_start); 1671 EXPECT_EQ(load_timing_result.request_start, 1672 load_timing_result.connect_timing.ssl_start); 1673 EXPECT_EQ(load_timing_result.request_start, 1674 load_timing_result.connect_timing.ssl_end); 1675 EXPECT_EQ(load_timing_result.request_start, 1676 load_timing_result.connect_timing.connect_end); 1677 1678 // Other times should have been left null. 1679 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES); 1680} 1681 1682// Make sure that URLRequest correctly adjusts connect times when they're before 1683// |request_start|, due to reusing a connected socket in the case that there 1684// are also proxy times. The connected socket is not considered reused in this 1685// test (May be a preconnect). 1686// 1687// In this test, there are no SSL or DNS times. 1688TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) { 1689 base::TimeTicks now = base::TimeTicks::Now(); 1690 LoadTimingInfo job_load_timing = 1691 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true); 1692 job_load_timing.connect_timing.connect_start = 1693 now - base::TimeDelta::FromDays(1); 1694 job_load_timing.connect_timing.connect_end = 1695 now - base::TimeDelta::FromDays(2); 1696 1697 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing, 1698 &default_context_); 1699 1700 // Connect times should be replaced with proxy_resolve_end. 1701 EXPECT_EQ(load_timing_result.proxy_resolve_end, 1702 load_timing_result.connect_timing.connect_start); 1703 EXPECT_EQ(load_timing_result.proxy_resolve_end, 1704 load_timing_result.connect_timing.connect_end); 1705 1706 // Other times should have been left null. 1707 TestLoadTimingNotReusedWithProxy(load_timing_result, 1708 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY); 1709} 1710 1711// Check that two different URL requests have different identifiers. 1712TEST_F(URLRequestTest, Identifiers) { 1713 TestDelegate d; 1714 TestURLRequestContext context; 1715 TestURLRequest req(GURL("http://example.com"), &d, &context, NULL); 1716 TestURLRequest other_req(GURL("http://example.com"), &d, &context, NULL); 1717 1718 ASSERT_NE(req.identifier(), other_req.identifier()); 1719} 1720 1721// Check that a failure to connect to the proxy is reported to the network 1722// delegate. 1723TEST_F(URLRequestTest, NetworkDelegateProxyError) { 1724 MockHostResolver host_resolver; 1725 host_resolver.rules()->AddSimulatedFailure("*"); 1726 1727 TestNetworkDelegate network_delegate; // Must outlive URLRequests. 1728 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate); 1729 1730 TestDelegate d; 1731 URLRequest req(GURL("http://example.com"), &d, &context); 1732 req.set_method("GET"); 1733 1734 req.Start(); 1735 base::RunLoop().Run(); 1736 1737 // Check we see a failed request. 1738 EXPECT_FALSE(req.status().is_success()); 1739 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status()); 1740 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error()); 1741 1742 EXPECT_EQ(1, network_delegate.error_count()); 1743 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error()); 1744 EXPECT_EQ(1, network_delegate.completed_requests()); 1745} 1746 1747// Make sure that net::NetworkDelegate::NotifyCompleted is called if 1748// content is empty. 1749TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) { 1750 TestDelegate d; 1751 URLRequest req(GURL("data:,"), &d, &default_context_); 1752 req.Start(); 1753 base::RunLoop().Run(); 1754 EXPECT_EQ("", d.data_received()); 1755 EXPECT_EQ(1, default_network_delegate_.completed_requests()); 1756} 1757 1758// Make sure that SetPriority actually sets the URLRequest's priority 1759// correctly, both before and after start. 1760TEST_F(URLRequestTest, SetPriorityBasic) { 1761 TestDelegate d; 1762 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1763 EXPECT_EQ(DEFAULT_PRIORITY, req.priority()); 1764 1765 req.SetPriority(LOW); 1766 EXPECT_EQ(LOW, req.priority()); 1767 1768 req.Start(); 1769 EXPECT_EQ(LOW, req.priority()); 1770 1771 req.SetPriority(MEDIUM); 1772 EXPECT_EQ(MEDIUM, req.priority()); 1773} 1774 1775// Make sure that URLRequest calls SetPriority on a job before calling 1776// Start on it. 1777TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) { 1778 TestDelegate d; 1779 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1780 EXPECT_EQ(DEFAULT_PRIORITY, req.priority()); 1781 1782 scoped_refptr<URLRequestTestJob> job = 1783 new URLRequestTestJob(&req, &default_network_delegate_); 1784 AddTestInterceptor()->set_main_intercept_job(job.get()); 1785 EXPECT_EQ(DEFAULT_PRIORITY, job->priority()); 1786 1787 req.SetPriority(LOW); 1788 1789 req.Start(); 1790 EXPECT_EQ(LOW, job->priority()); 1791} 1792 1793// Make sure that URLRequest passes on its priority updates to its 1794// job. 1795TEST_F(URLRequestTest, SetJobPriority) { 1796 TestDelegate d; 1797 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_); 1798 1799 scoped_refptr<URLRequestTestJob> job = 1800 new URLRequestTestJob(&req, &default_network_delegate_); 1801 AddTestInterceptor()->set_main_intercept_job(job.get()); 1802 1803 req.SetPriority(LOW); 1804 req.Start(); 1805 EXPECT_EQ(LOW, job->priority()); 1806 1807 req.SetPriority(MEDIUM); 1808 EXPECT_EQ(MEDIUM, req.priority()); 1809 EXPECT_EQ(MEDIUM, job->priority()); 1810} 1811 1812// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666). 1813#if !defined(OS_IOS) 1814// A subclass of SpawnedTestServer that uses a statically-configured hostname. 1815// This is to work around mysterious failures in chrome_frame_net_tests. See: 1816// http://crbug.com/114369 1817class LocalHttpTestServer : public SpawnedTestServer { 1818 public: 1819 explicit LocalHttpTestServer(const base::FilePath& document_root) 1820 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP, 1821 ScopedCustomUrlRequestTestHttpHost::value(), 1822 document_root) {} 1823 LocalHttpTestServer() 1824 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP, 1825 ScopedCustomUrlRequestTestHttpHost::value(), 1826 base::FilePath()) {} 1827}; 1828 1829TEST_F(URLRequestTest, DelayedCookieCallback) { 1830 LocalHttpTestServer test_server; 1831 ASSERT_TRUE(test_server.Start()); 1832 1833 TestURLRequestContext context; 1834 scoped_refptr<DelayedCookieMonster> delayed_cm = 1835 new DelayedCookieMonster(); 1836 scoped_refptr<CookieStore> cookie_store = delayed_cm; 1837 context.set_cookie_store(delayed_cm.get()); 1838 1839 // Set up a cookie. 1840 { 1841 TestNetworkDelegate network_delegate; 1842 context.set_network_delegate(&network_delegate); 1843 TestDelegate d; 1844 URLRequest req( 1845 test_server.GetURL("set-cookie?CookieToNotSend=1"), &d, &context); 1846 req.Start(); 1847 base::RunLoop().Run(); 1848 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1849 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1850 EXPECT_EQ(1, network_delegate.set_cookie_count()); 1851 } 1852 1853 // Verify that the cookie is set. 1854 { 1855 TestNetworkDelegate network_delegate; 1856 context.set_network_delegate(&network_delegate); 1857 TestDelegate d; 1858 URLRequest req(test_server.GetURL("echoheader?Cookie"), &d, &context); 1859 req.Start(); 1860 base::RunLoop().Run(); 1861 1862 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") 1863 != std::string::npos); 1864 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1865 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1866 } 1867} 1868 1869TEST_F(URLRequestTest, DoNotSendCookies) { 1870 LocalHttpTestServer test_server; 1871 ASSERT_TRUE(test_server.Start()); 1872 1873 // Set up a cookie. 1874 { 1875 TestNetworkDelegate network_delegate; 1876 default_context_.set_network_delegate(&network_delegate); 1877 TestDelegate d; 1878 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"), 1879 &d, 1880 &default_context_); 1881 req.Start(); 1882 base::RunLoop().Run(); 1883 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1884 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1885 } 1886 1887 // Verify that the cookie is set. 1888 { 1889 TestNetworkDelegate network_delegate; 1890 default_context_.set_network_delegate(&network_delegate); 1891 TestDelegate d; 1892 URLRequest req( 1893 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 1894 req.Start(); 1895 base::RunLoop().Run(); 1896 1897 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") 1898 != std::string::npos); 1899 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1900 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1901 } 1902 1903 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set. 1904 { 1905 TestNetworkDelegate network_delegate; 1906 default_context_.set_network_delegate(&network_delegate); 1907 TestDelegate d; 1908 URLRequest req( 1909 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 1910 req.set_load_flags(LOAD_DO_NOT_SEND_COOKIES); 1911 req.Start(); 1912 base::RunLoop().Run(); 1913 1914 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") 1915 == std::string::npos); 1916 1917 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies. 1918 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1919 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1920 } 1921} 1922 1923TEST_F(URLRequestTest, DoNotSaveCookies) { 1924 LocalHttpTestServer test_server; 1925 ASSERT_TRUE(test_server.Start()); 1926 1927 // Set up a cookie. 1928 { 1929 TestNetworkDelegate network_delegate; 1930 default_context_.set_network_delegate(&network_delegate); 1931 TestDelegate d; 1932 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"), 1933 &d, 1934 &default_context_); 1935 req.Start(); 1936 base::RunLoop().Run(); 1937 1938 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1939 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1940 EXPECT_EQ(1, network_delegate.set_cookie_count()); 1941 } 1942 1943 // Try to set-up another cookie and update the previous cookie. 1944 { 1945 TestNetworkDelegate network_delegate; 1946 default_context_.set_network_delegate(&network_delegate); 1947 TestDelegate d; 1948 URLRequest req( 1949 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"), 1950 &d, 1951 &default_context_); 1952 req.set_load_flags(LOAD_DO_NOT_SAVE_COOKIES); 1953 req.Start(); 1954 1955 base::RunLoop().Run(); 1956 1957 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie. 1958 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1959 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1960 EXPECT_EQ(0, network_delegate.set_cookie_count()); 1961 } 1962 1963 // Verify the cookies weren't saved or updated. 1964 { 1965 TestNetworkDelegate network_delegate; 1966 default_context_.set_network_delegate(&network_delegate); 1967 TestDelegate d; 1968 URLRequest req( 1969 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 1970 req.Start(); 1971 base::RunLoop().Run(); 1972 1973 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") 1974 == std::string::npos); 1975 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") 1976 != std::string::npos); 1977 1978 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 1979 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 1980 EXPECT_EQ(0, network_delegate.set_cookie_count()); 1981 } 1982} 1983 1984TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) { 1985 LocalHttpTestServer test_server; 1986 ASSERT_TRUE(test_server.Start()); 1987 1988 // Set up a cookie. 1989 { 1990 TestNetworkDelegate network_delegate; 1991 default_context_.set_network_delegate(&network_delegate); 1992 TestDelegate d; 1993 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"), 1994 &d, 1995 &default_context_); 1996 req.Start(); 1997 base::RunLoop().Run(); 1998 1999 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2000 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2001 } 2002 2003 // Verify that the cookie is set. 2004 { 2005 TestNetworkDelegate network_delegate; 2006 default_context_.set_network_delegate(&network_delegate); 2007 TestDelegate d; 2008 URLRequest req( 2009 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2010 req.Start(); 2011 base::RunLoop().Run(); 2012 2013 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") 2014 != std::string::npos); 2015 2016 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2017 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2018 } 2019 2020 // Verify that the cookie isn't sent. 2021 { 2022 TestNetworkDelegate network_delegate; 2023 default_context_.set_network_delegate(&network_delegate); 2024 TestDelegate d; 2025 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES); 2026 URLRequest req( 2027 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2028 req.Start(); 2029 base::RunLoop().Run(); 2030 2031 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") 2032 == std::string::npos); 2033 2034 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count()); 2035 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2036 } 2037} 2038 2039TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) { 2040 LocalHttpTestServer test_server; 2041 ASSERT_TRUE(test_server.Start()); 2042 2043 // Set up a cookie. 2044 { 2045 TestNetworkDelegate network_delegate; 2046 default_context_.set_network_delegate(&network_delegate); 2047 TestDelegate d; 2048 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"), 2049 &d, 2050 &default_context_); 2051 req.Start(); 2052 base::RunLoop().Run(); 2053 2054 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2055 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2056 } 2057 2058 // Try to set-up another cookie and update the previous cookie. 2059 { 2060 TestNetworkDelegate network_delegate; 2061 default_context_.set_network_delegate(&network_delegate); 2062 TestDelegate d; 2063 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE); 2064 URLRequest req( 2065 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"), 2066 &d, 2067 &default_context_); 2068 req.Start(); 2069 2070 base::RunLoop().Run(); 2071 2072 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2073 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count()); 2074 } 2075 2076 // Verify the cookies weren't saved or updated. 2077 { 2078 TestNetworkDelegate network_delegate; 2079 default_context_.set_network_delegate(&network_delegate); 2080 TestDelegate d; 2081 URLRequest req( 2082 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2083 req.Start(); 2084 base::RunLoop().Run(); 2085 2086 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") 2087 == std::string::npos); 2088 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") 2089 != std::string::npos); 2090 2091 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2092 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2093 } 2094} 2095 2096TEST_F(URLRequestTest, DoNotSaveEmptyCookies) { 2097 LocalHttpTestServer test_server; 2098 ASSERT_TRUE(test_server.Start()); 2099 2100 // Set up an empty cookie. 2101 { 2102 TestNetworkDelegate network_delegate; 2103 default_context_.set_network_delegate(&network_delegate); 2104 TestDelegate d; 2105 URLRequest req(test_server.GetURL("set-cookie"), &d, &default_context_); 2106 req.Start(); 2107 base::RunLoop().Run(); 2108 2109 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2110 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2111 EXPECT_EQ(0, network_delegate.set_cookie_count()); 2112 } 2113} 2114 2115TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) { 2116 LocalHttpTestServer test_server; 2117 ASSERT_TRUE(test_server.Start()); 2118 2119 // Set up a cookie. 2120 { 2121 TestNetworkDelegate network_delegate; 2122 default_context_.set_network_delegate(&network_delegate); 2123 TestDelegate d; 2124 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"), 2125 &d, 2126 &default_context_); 2127 req.Start(); 2128 base::RunLoop().Run(); 2129 2130 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2131 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2132 } 2133 2134 // Verify that the cookie is set. 2135 { 2136 TestNetworkDelegate network_delegate; 2137 default_context_.set_network_delegate(&network_delegate); 2138 TestDelegate d; 2139 URLRequest req( 2140 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2141 req.Start(); 2142 base::RunLoop().Run(); 2143 2144 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1") 2145 != std::string::npos); 2146 2147 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2148 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2149 } 2150 2151 // Verify that the cookie isn't sent. 2152 { 2153 TestNetworkDelegate network_delegate; 2154 default_context_.set_network_delegate(&network_delegate); 2155 TestDelegate d; 2156 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES); 2157 URLRequest req( 2158 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2159 req.Start(); 2160 base::RunLoop().Run(); 2161 2162 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1") 2163 == std::string::npos); 2164 2165 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count()); 2166 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2167 } 2168} 2169 2170TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) { 2171 LocalHttpTestServer test_server; 2172 ASSERT_TRUE(test_server.Start()); 2173 2174 // Set up a cookie. 2175 { 2176 TestNetworkDelegate network_delegate; 2177 default_context_.set_network_delegate(&network_delegate); 2178 TestDelegate d; 2179 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"), 2180 &d, 2181 &default_context_); 2182 req.Start(); 2183 base::RunLoop().Run(); 2184 2185 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2186 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2187 } 2188 2189 // Try to set-up another cookie and update the previous cookie. 2190 { 2191 TestNetworkDelegate network_delegate; 2192 default_context_.set_network_delegate(&network_delegate); 2193 TestDelegate d; 2194 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE); 2195 URLRequest req( 2196 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"), 2197 &d, 2198 &default_context_); 2199 req.Start(); 2200 2201 base::RunLoop().Run(); 2202 2203 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2204 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count()); 2205 } 2206 2207 // Verify the cookies weren't saved or updated. 2208 { 2209 TestNetworkDelegate network_delegate; 2210 default_context_.set_network_delegate(&network_delegate); 2211 TestDelegate d; 2212 URLRequest req( 2213 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2214 req.Start(); 2215 base::RunLoop().Run(); 2216 2217 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1") 2218 == std::string::npos); 2219 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2") 2220 != std::string::npos); 2221 2222 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count()); 2223 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count()); 2224 } 2225} 2226 2227// FixedDateNetworkDelegate swaps out the server's HTTP Date response header 2228// value for the |fixed_date| argument given to the constructor. 2229class FixedDateNetworkDelegate : public TestNetworkDelegate { 2230 public: 2231 explicit FixedDateNetworkDelegate(const std::string& fixed_date) 2232 : fixed_date_(fixed_date) {} 2233 virtual ~FixedDateNetworkDelegate() {} 2234 2235 // net::NetworkDelegate implementation 2236 virtual int OnHeadersReceived( 2237 net::URLRequest* request, 2238 const net::CompletionCallback& callback, 2239 const net::HttpResponseHeaders* original_response_headers, 2240 scoped_refptr<net::HttpResponseHeaders>* override_response_headers) 2241 OVERRIDE; 2242 2243 private: 2244 std::string fixed_date_; 2245 2246 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate); 2247}; 2248 2249int FixedDateNetworkDelegate::OnHeadersReceived( 2250 net::URLRequest* request, 2251 const net::CompletionCallback& callback, 2252 const net::HttpResponseHeaders* original_response_headers, 2253 scoped_refptr<net::HttpResponseHeaders>* override_response_headers) { 2254 net::HttpResponseHeaders* new_response_headers = 2255 new net::HttpResponseHeaders(original_response_headers->raw_headers()); 2256 2257 new_response_headers->RemoveHeader("Date"); 2258 new_response_headers->AddHeader("Date: " + fixed_date_); 2259 2260 *override_response_headers = new_response_headers; 2261 return TestNetworkDelegate::OnHeadersReceived(request, 2262 callback, 2263 original_response_headers, 2264 override_response_headers); 2265} 2266 2267// Test that cookie expiration times are adjusted for server/client clock 2268// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date 2269// headers by defaulting to GMT. (crbug.com/135131) 2270TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) { 2271 LocalHttpTestServer test_server; 2272 ASSERT_TRUE(test_server.Start()); 2273 2274 // Set up an expired cookie. 2275 { 2276 TestNetworkDelegate network_delegate; 2277 default_context_.set_network_delegate(&network_delegate); 2278 TestDelegate d; 2279 URLRequest req(test_server.GetURL( 2280 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"), 2281 &d, 2282 &default_context_); 2283 req.Start(); 2284 base::RunLoop().Run(); 2285 } 2286 // Verify that the cookie is not set. 2287 { 2288 TestNetworkDelegate network_delegate; 2289 default_context_.set_network_delegate(&network_delegate); 2290 TestDelegate d; 2291 URLRequest req( 2292 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2293 req.Start(); 2294 base::RunLoop().Run(); 2295 2296 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos); 2297 } 2298 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier. 2299 { 2300 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC"); 2301 default_context_.set_network_delegate(&network_delegate); 2302 TestDelegate d; 2303 URLRequest req(test_server.GetURL( 2304 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"), 2305 &d, 2306 &default_context_); 2307 req.Start(); 2308 base::RunLoop().Run(); 2309 } 2310 // Verify that the cookie is set. 2311 { 2312 TestNetworkDelegate network_delegate; 2313 default_context_.set_network_delegate(&network_delegate); 2314 TestDelegate d; 2315 URLRequest req( 2316 test_server.GetURL("echoheader?Cookie"), &d, &default_context_); 2317 req.Start(); 2318 base::RunLoop().Run(); 2319 2320 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos); 2321 } 2322} 2323 2324 2325// Check that it is impossible to change the referrer in the extra headers of 2326// an URLRequest. 2327TEST_F(URLRequestTest, DoNotOverrideReferrer) { 2328 LocalHttpTestServer test_server; 2329 ASSERT_TRUE(test_server.Start()); 2330 2331 // If extra headers contain referer and the request contains a referer, 2332 // only the latter shall be respected. 2333 { 2334 TestDelegate d; 2335 URLRequest req( 2336 test_server.GetURL("echoheader?Referer"), &d, &default_context_); 2337 req.SetReferrer("http://foo.com/"); 2338 2339 HttpRequestHeaders headers; 2340 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/"); 2341 req.SetExtraRequestHeaders(headers); 2342 2343 req.Start(); 2344 base::RunLoop().Run(); 2345 2346 EXPECT_EQ("http://foo.com/", d.data_received()); 2347 } 2348 2349 // If extra headers contain a referer but the request does not, no referer 2350 // shall be sent in the header. 2351 { 2352 TestDelegate d; 2353 URLRequest req( 2354 test_server.GetURL("echoheader?Referer"), &d, &default_context_); 2355 2356 HttpRequestHeaders headers; 2357 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/"); 2358 req.SetExtraRequestHeaders(headers); 2359 req.set_load_flags(LOAD_VALIDATE_CACHE); 2360 2361 req.Start(); 2362 base::RunLoop().Run(); 2363 2364 EXPECT_EQ("None", d.data_received()); 2365 } 2366} 2367 2368class URLRequestTestHTTP : public URLRequestTest { 2369 public: 2370 URLRequestTestHTTP() 2371 : test_server_(base::FilePath(FILE_PATH_LITERAL( 2372 "net/data/url_request_unittest"))) { 2373 } 2374 2375 protected: 2376 // Requests |redirect_url|, which must return a HTTP 3xx redirect. 2377 // |request_method| is the method to use for the initial request. 2378 // |redirect_method| is the method that is expected to be used for the second 2379 // request, after redirection. 2380 // If |include_data| is true, data is uploaded with the request. The 2381 // response body is expected to match it exactly, if and only if 2382 // |request_method| == |redirect_method|. 2383 void HTTPRedirectMethodTest(const GURL& redirect_url, 2384 const std::string& request_method, 2385 const std::string& redirect_method, 2386 bool include_data) { 2387 static const char kData[] = "hello world"; 2388 TestDelegate d; 2389 URLRequest req(redirect_url, &d, &default_context_); 2390 req.set_method(request_method); 2391 if (include_data) { 2392 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData))); 2393 HttpRequestHeaders headers; 2394 headers.SetHeader(HttpRequestHeaders::kContentLength, 2395 base::UintToString(arraysize(kData) - 1)); 2396 req.SetExtraRequestHeaders(headers); 2397 } 2398 req.Start(); 2399 base::RunLoop().Run(); 2400 EXPECT_EQ(redirect_method, req.method()); 2401 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status()); 2402 EXPECT_EQ(OK, req.status().error()); 2403 if (include_data) { 2404 if (request_method == redirect_method) { 2405 EXPECT_EQ(kData, d.data_received()); 2406 } else { 2407 EXPECT_NE(kData, d.data_received()); 2408 } 2409 } 2410 if (HasFailure()) 2411 LOG(WARNING) << "Request method was: " << request_method; 2412 } 2413 2414 void HTTPUploadDataOperationTest(const std::string& method) { 2415 const int kMsgSize = 20000; // multiple of 10 2416 const int kIterations = 50; 2417 char* uploadBytes = new char[kMsgSize+1]; 2418 char* ptr = uploadBytes; 2419 char marker = 'a'; 2420 for (int idx = 0; idx < kMsgSize/10; idx++) { 2421 memcpy(ptr, "----------", 10); 2422 ptr += 10; 2423 if (idx % 100 == 0) { 2424 ptr--; 2425 *ptr++ = marker; 2426 if (++marker > 'z') 2427 marker = 'a'; 2428 } 2429 } 2430 uploadBytes[kMsgSize] = '\0'; 2431 2432 for (int i = 0; i < kIterations; ++i) { 2433 TestDelegate d; 2434 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_); 2435 r.set_method(method.c_str()); 2436 2437 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes))); 2438 2439 r.Start(); 2440 EXPECT_TRUE(r.is_pending()); 2441 2442 base::RunLoop().Run(); 2443 2444 ASSERT_EQ(1, d.response_started_count()) 2445 << "request failed: " << r.status().status() 2446 << ", os error: " << r.status().error(); 2447 2448 EXPECT_FALSE(d.received_data_before_response()); 2449 EXPECT_EQ(uploadBytes, d.data_received()); 2450 } 2451 delete[] uploadBytes; 2452 } 2453 2454 void AddChunksToUpload(URLRequest* r) { 2455 r->AppendChunkToUpload("a", 1, false); 2456 r->AppendChunkToUpload("bcd", 3, false); 2457 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false); 2458 r->AppendChunkToUpload("\r\n\r\n", 4, false); 2459 r->AppendChunkToUpload("0", 1, false); 2460 r->AppendChunkToUpload("2323", 4, true); 2461 } 2462 2463 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) { 2464 // This should match the chunks sent by AddChunksToUpload(). 2465 const std::string expected_data = 2466 "abcdthis is a longer chunk than before.\r\n\r\n02323"; 2467 2468 ASSERT_EQ(1, d->response_started_count()) 2469 << "request failed: " << r->status().status() 2470 << ", os error: " << r->status().error(); 2471 2472 EXPECT_FALSE(d->received_data_before_response()); 2473 2474 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received())); 2475 EXPECT_EQ(expected_data, d->data_received()); 2476 } 2477 2478 bool DoManyCookiesRequest(int num_cookies) { 2479 TestDelegate d; 2480 URLRequest r(test_server_.GetURL("set-many-cookies?" + 2481 base::IntToString(num_cookies)), 2482 &d, 2483 &default_context_); 2484 2485 r.Start(); 2486 EXPECT_TRUE(r.is_pending()); 2487 2488 base::RunLoop().Run(); 2489 2490 bool is_success = r.status().is_success(); 2491 2492 if (!is_success) { 2493 // Requests handled by ChromeFrame send a less precise error message, 2494 // ERR_CONNECTION_ABORTED. 2495 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG || 2496 r.status().error() == ERR_CONNECTION_ABORTED); 2497 // The test server appears to be unable to handle subsequent requests 2498 // after this error is triggered. Force it to restart. 2499 EXPECT_TRUE(test_server_.Stop()); 2500 EXPECT_TRUE(test_server_.Start()); 2501 } 2502 2503 return is_success; 2504 } 2505 2506 LocalHttpTestServer test_server_; 2507}; 2508 2509// In this unit test, we're using the HTTPTestServer as a proxy server and 2510// issuing a CONNECT request with the magic host name "www.redirect.com". 2511// The HTTPTestServer will return a 302 response, which we should not 2512// follow. 2513TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) { 2514 ASSERT_TRUE(test_server_.Start()); 2515 2516 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 2517 TestURLRequestContextWithProxy context( 2518 test_server_.host_port_pair().ToString(), 2519 &network_delegate); 2520 2521 TestDelegate d; 2522 { 2523 URLRequest r(GURL("https://www.redirect.com/"), &d, &context); 2524 r.Start(); 2525 EXPECT_TRUE(r.is_pending()); 2526 2527 base::RunLoop().Run(); 2528 2529 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status()); 2530 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error()); 2531 EXPECT_EQ(1, d.response_started_count()); 2532 // We should not have followed the redirect. 2533 EXPECT_EQ(0, d.received_redirect_count()); 2534 } 2535} 2536 2537// This is the same as the previous test, but checks that the network delegate 2538// registers the error. 2539TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) { 2540 ASSERT_TRUE(test_server_.Start()); 2541 2542 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 2543 TestURLRequestContextWithProxy context( 2544 test_server_.host_port_pair().ToString(), 2545 &network_delegate); 2546 2547 TestDelegate d; 2548 { 2549 URLRequest r(GURL("https://www.redirect.com/"), &d, &context); 2550 r.Start(); 2551 EXPECT_TRUE(r.is_pending()); 2552 2553 base::RunLoop().Run(); 2554 2555 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status()); 2556 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error()); 2557 EXPECT_EQ(1, d.response_started_count()); 2558 // We should not have followed the redirect. 2559 EXPECT_EQ(0, d.received_redirect_count()); 2560 2561 EXPECT_EQ(1, network_delegate.error_count()); 2562 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error()); 2563 } 2564} 2565 2566// Tests that we can block and asynchronously return OK in various stages. 2567TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) { 2568 static const BlockingNetworkDelegate::Stage blocking_stages[] = { 2569 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST, 2570 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS, 2571 BlockingNetworkDelegate::ON_HEADERS_RECEIVED 2572 }; 2573 static const size_t blocking_stages_length = arraysize(blocking_stages); 2574 2575 ASSERT_TRUE(test_server_.Start()); 2576 2577 TestDelegate d; 2578 BlockingNetworkDelegate network_delegate( 2579 BlockingNetworkDelegate::USER_CALLBACK); 2580 network_delegate.set_block_on( 2581 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST | 2582 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS | 2583 BlockingNetworkDelegate::ON_HEADERS_RECEIVED); 2584 2585 TestURLRequestContext context(true); 2586 context.set_network_delegate(&network_delegate); 2587 context.Init(); 2588 2589 { 2590 URLRequest r(test_server_.GetURL("empty.html"), &d, &context); 2591 2592 r.Start(); 2593 for (size_t i = 0; i < blocking_stages_length; ++i) { 2594 base::RunLoop().Run(); 2595 EXPECT_EQ(blocking_stages[i], 2596 network_delegate.stage_blocked_for_callback()); 2597 network_delegate.DoCallback(OK); 2598 } 2599 base::RunLoop().Run(); 2600 EXPECT_EQ(200, r.GetResponseCode()); 2601 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2602 EXPECT_EQ(1, network_delegate.created_requests()); 2603 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2604 } 2605 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2606} 2607 2608// Tests that the network delegate can block and cancel a request. 2609TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) { 2610 ASSERT_TRUE(test_server_.Start()); 2611 2612 TestDelegate d; 2613 BlockingNetworkDelegate network_delegate( 2614 BlockingNetworkDelegate::AUTO_CALLBACK); 2615 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST); 2616 network_delegate.set_retval(ERR_EMPTY_RESPONSE); 2617 2618 TestURLRequestContextWithProxy context( 2619 test_server_.host_port_pair().ToString(), 2620 &network_delegate); 2621 2622 { 2623 URLRequest r(test_server_.GetURL(std::string()), &d, &context); 2624 2625 r.Start(); 2626 base::RunLoop().Run(); 2627 2628 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status()); 2629 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error()); 2630 EXPECT_EQ(1, network_delegate.created_requests()); 2631 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2632 } 2633 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2634} 2635 2636// Helper function for NetworkDelegateCancelRequestAsynchronously and 2637// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network 2638// delegate operating in |block_mode| and a request for |url|. It blocks the 2639// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT. 2640void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode, 2641 BlockingNetworkDelegate::Stage stage, 2642 const GURL& url) { 2643 TestDelegate d; 2644 BlockingNetworkDelegate network_delegate(block_mode); 2645 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT); 2646 network_delegate.set_block_on(stage); 2647 2648 TestURLRequestContext context(true); 2649 context.set_network_delegate(&network_delegate); 2650 context.Init(); 2651 2652 { 2653 URLRequest r(url, &d, &context); 2654 2655 r.Start(); 2656 base::RunLoop().Run(); 2657 2658 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status()); 2659 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error()); 2660 EXPECT_EQ(1, network_delegate.created_requests()); 2661 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2662 } 2663 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2664} 2665 2666// The following 3 tests check that the network delegate can cancel a request 2667// synchronously in various stages of the request. 2668TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) { 2669 ASSERT_TRUE(test_server_.Start()); 2670 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS, 2671 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST, 2672 test_server_.GetURL(std::string())); 2673} 2674 2675TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) { 2676 ASSERT_TRUE(test_server_.Start()); 2677 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS, 2678 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS, 2679 test_server_.GetURL(std::string())); 2680} 2681 2682TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) { 2683 ASSERT_TRUE(test_server_.Start()); 2684 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS, 2685 BlockingNetworkDelegate::ON_HEADERS_RECEIVED, 2686 test_server_.GetURL(std::string())); 2687} 2688 2689// The following 3 tests check that the network delegate can cancel a request 2690// asynchronously in various stages of the request. 2691TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) { 2692 ASSERT_TRUE(test_server_.Start()); 2693 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK, 2694 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST, 2695 test_server_.GetURL(std::string())); 2696} 2697 2698TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) { 2699 ASSERT_TRUE(test_server_.Start()); 2700 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK, 2701 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS, 2702 test_server_.GetURL(std::string())); 2703} 2704 2705TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) { 2706 ASSERT_TRUE(test_server_.Start()); 2707 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK, 2708 BlockingNetworkDelegate::ON_HEADERS_RECEIVED, 2709 test_server_.GetURL(std::string())); 2710} 2711 2712// Tests that the network delegate can block and redirect a request to a new 2713// URL. 2714TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) { 2715 ASSERT_TRUE(test_server_.Start()); 2716 2717 TestDelegate d; 2718 BlockingNetworkDelegate network_delegate( 2719 BlockingNetworkDelegate::AUTO_CALLBACK); 2720 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST); 2721 GURL redirect_url(test_server_.GetURL("simple.html")); 2722 network_delegate.set_redirect_url(redirect_url); 2723 2724 TestURLRequestContextWithProxy context( 2725 test_server_.host_port_pair().ToString(), 2726 &network_delegate); 2727 2728 { 2729 GURL original_url(test_server_.GetURL("empty.html")); 2730 URLRequest r(original_url, &d, &context); 2731 2732 r.Start(); 2733 base::RunLoop().Run(); 2734 2735 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2736 EXPECT_EQ(0, r.status().error()); 2737 EXPECT_EQ(redirect_url, r.url()); 2738 EXPECT_EQ(original_url, r.original_url()); 2739 EXPECT_EQ(2U, r.url_chain().size()); 2740 EXPECT_EQ(1, network_delegate.created_requests()); 2741 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2742 } 2743 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2744} 2745 2746// Tests that the network delegate can block and redirect a request to a new 2747// URL by setting a redirect_url and returning in OnBeforeURLRequest directly. 2748TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) { 2749 ASSERT_TRUE(test_server_.Start()); 2750 2751 TestDelegate d; 2752 BlockingNetworkDelegate network_delegate( 2753 BlockingNetworkDelegate::SYNCHRONOUS); 2754 GURL redirect_url(test_server_.GetURL("simple.html")); 2755 network_delegate.set_redirect_url(redirect_url); 2756 2757 TestURLRequestContextWithProxy context( 2758 test_server_.host_port_pair().ToString(), 2759 &network_delegate); 2760 2761 { 2762 GURL original_url(test_server_.GetURL("empty.html")); 2763 URLRequest r(original_url, &d, &context); 2764 2765 r.Start(); 2766 base::RunLoop().Run(); 2767 2768 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2769 EXPECT_EQ(0, r.status().error()); 2770 EXPECT_EQ(redirect_url, r.url()); 2771 EXPECT_EQ(original_url, r.original_url()); 2772 EXPECT_EQ(2U, r.url_chain().size()); 2773 EXPECT_EQ(1, network_delegate.created_requests()); 2774 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2775 } 2776 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2777} 2778 2779// Tests that redirects caused by the network delegate preserve POST data. 2780TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) { 2781 ASSERT_TRUE(test_server_.Start()); 2782 2783 const char kData[] = "hello world"; 2784 2785 TestDelegate d; 2786 BlockingNetworkDelegate network_delegate( 2787 BlockingNetworkDelegate::AUTO_CALLBACK); 2788 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST); 2789 GURL redirect_url(test_server_.GetURL("echo")); 2790 network_delegate.set_redirect_url(redirect_url); 2791 2792 TestURLRequestContext context(true); 2793 context.set_network_delegate(&network_delegate); 2794 context.Init(); 2795 2796 { 2797 GURL original_url(test_server_.GetURL("empty.html")); 2798 URLRequest r(original_url, &d, &context); 2799 r.set_method("POST"); 2800 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData))); 2801 HttpRequestHeaders headers; 2802 headers.SetHeader(HttpRequestHeaders::kContentLength, 2803 base::UintToString(arraysize(kData) - 1)); 2804 r.SetExtraRequestHeaders(headers); 2805 r.Start(); 2806 base::RunLoop().Run(); 2807 2808 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2809 EXPECT_EQ(0, r.status().error()); 2810 EXPECT_EQ(redirect_url, r.url()); 2811 EXPECT_EQ(original_url, r.original_url()); 2812 EXPECT_EQ(2U, r.url_chain().size()); 2813 EXPECT_EQ(1, network_delegate.created_requests()); 2814 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2815 EXPECT_EQ("POST", r.method()); 2816 EXPECT_EQ(kData, d.data_received()); 2817 } 2818 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2819} 2820 2821// Tests that the network delegate can synchronously complete OnAuthRequired 2822// by taking no action. This indicates that the NetworkDelegate does not want to 2823// handle the challenge, and is passing the buck along to the 2824// URLRequest::Delegate. 2825TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) { 2826 ASSERT_TRUE(test_server_.Start()); 2827 2828 TestDelegate d; 2829 BlockingNetworkDelegate network_delegate( 2830 BlockingNetworkDelegate::SYNCHRONOUS); 2831 2832 TestURLRequestContext context(true); 2833 context.set_network_delegate(&network_delegate); 2834 context.Init(); 2835 2836 d.set_credentials(AuthCredentials(kUser, kSecret)); 2837 2838 { 2839 GURL url(test_server_.GetURL("auth-basic")); 2840 URLRequest r(url, &d, &context); 2841 r.Start(); 2842 2843 base::RunLoop().Run(); 2844 2845 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2846 EXPECT_EQ(0, r.status().error()); 2847 EXPECT_EQ(200, r.GetResponseCode()); 2848 EXPECT_TRUE(d.auth_required_called()); 2849 EXPECT_EQ(1, network_delegate.created_requests()); 2850 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2851 } 2852 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2853} 2854 2855TEST_F(URLRequestTestHTTP, 2856 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) { 2857 ASSERT_TRUE(test_server_.Start()); 2858 2859 TestDelegate d; 2860 BlockingNetworkDelegate network_delegate( 2861 BlockingNetworkDelegate::SYNCHRONOUS); 2862 2863 TestURLRequestContext context(true); 2864 context.set_network_delegate(&network_delegate); 2865 context.Init(); 2866 2867 d.set_credentials(AuthCredentials(kUser, kSecret)); 2868 2869 { 2870 GURL url(test_server_.GetURL("auth-basic")); 2871 URLRequest r(url, &d, &context); 2872 r.Start(); 2873 2874 { 2875 HttpRequestHeaders headers; 2876 EXPECT_TRUE(r.GetFullRequestHeaders(&headers)); 2877 EXPECT_FALSE(headers.HasHeader("Authorization")); 2878 } 2879 2880 base::RunLoop().Run(); 2881 2882 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2883 EXPECT_EQ(0, r.status().error()); 2884 EXPECT_EQ(200, r.GetResponseCode()); 2885 EXPECT_TRUE(d.auth_required_called()); 2886 EXPECT_EQ(1, network_delegate.created_requests()); 2887 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2888 } 2889 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2890} 2891 2892// Tests that the network delegate can synchronously complete OnAuthRequired 2893// by setting credentials. 2894TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) { 2895 ASSERT_TRUE(test_server_.Start()); 2896 2897 TestDelegate d; 2898 BlockingNetworkDelegate network_delegate( 2899 BlockingNetworkDelegate::SYNCHRONOUS); 2900 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED); 2901 network_delegate.set_auth_retval( 2902 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH); 2903 2904 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret)); 2905 2906 TestURLRequestContext context(true); 2907 context.set_network_delegate(&network_delegate); 2908 context.Init(); 2909 2910 { 2911 GURL url(test_server_.GetURL("auth-basic")); 2912 URLRequest r(url, &d, &context); 2913 r.Start(); 2914 base::RunLoop().Run(); 2915 2916 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2917 EXPECT_EQ(0, r.status().error()); 2918 EXPECT_EQ(200, r.GetResponseCode()); 2919 EXPECT_FALSE(d.auth_required_called()); 2920 EXPECT_EQ(1, network_delegate.created_requests()); 2921 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2922 } 2923 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2924} 2925 2926// Same as above, but also tests that GetFullRequestHeaders returns the proper 2927// headers (for the first or second request) when called at the proper times. 2928TEST_F(URLRequestTestHTTP, 2929 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) { 2930 ASSERT_TRUE(test_server_.Start()); 2931 2932 TestDelegate d; 2933 BlockingNetworkDelegate network_delegate( 2934 BlockingNetworkDelegate::SYNCHRONOUS); 2935 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED); 2936 network_delegate.set_auth_retval( 2937 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH); 2938 2939 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret)); 2940 2941 TestURLRequestContext context(true); 2942 context.set_network_delegate(&network_delegate); 2943 context.Init(); 2944 2945 { 2946 GURL url(test_server_.GetURL("auth-basic")); 2947 URLRequest r(url, &d, &context); 2948 r.Start(); 2949 base::RunLoop().Run(); 2950 2951 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2952 EXPECT_EQ(0, r.status().error()); 2953 EXPECT_EQ(200, r.GetResponseCode()); 2954 EXPECT_FALSE(d.auth_required_called()); 2955 EXPECT_EQ(1, network_delegate.created_requests()); 2956 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2957 2958 { 2959 HttpRequestHeaders headers; 2960 EXPECT_TRUE(r.GetFullRequestHeaders(&headers)); 2961 EXPECT_TRUE(headers.HasHeader("Authorization")); 2962 } 2963 } 2964 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2965} 2966 2967// Tests that the network delegate can synchronously complete OnAuthRequired 2968// by cancelling authentication. 2969TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) { 2970 ASSERT_TRUE(test_server_.Start()); 2971 2972 TestDelegate d; 2973 BlockingNetworkDelegate network_delegate( 2974 BlockingNetworkDelegate::SYNCHRONOUS); 2975 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED); 2976 network_delegate.set_auth_retval( 2977 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH); 2978 2979 TestURLRequestContext context(true); 2980 context.set_network_delegate(&network_delegate); 2981 context.Init(); 2982 2983 { 2984 GURL url(test_server_.GetURL("auth-basic")); 2985 URLRequest r(url, &d, &context); 2986 r.Start(); 2987 base::RunLoop().Run(); 2988 2989 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 2990 EXPECT_EQ(OK, r.status().error()); 2991 EXPECT_EQ(401, r.GetResponseCode()); 2992 EXPECT_FALSE(d.auth_required_called()); 2993 EXPECT_EQ(1, network_delegate.created_requests()); 2994 EXPECT_EQ(0, network_delegate.destroyed_requests()); 2995 } 2996 EXPECT_EQ(1, network_delegate.destroyed_requests()); 2997} 2998 2999// Tests that the network delegate can asynchronously complete OnAuthRequired 3000// by taking no action. This indicates that the NetworkDelegate does not want 3001// to handle the challenge, and is passing the buck along to the 3002// URLRequest::Delegate. 3003TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) { 3004 ASSERT_TRUE(test_server_.Start()); 3005 3006 TestDelegate d; 3007 BlockingNetworkDelegate network_delegate( 3008 BlockingNetworkDelegate::AUTO_CALLBACK); 3009 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED); 3010 3011 TestURLRequestContext context(true); 3012 context.set_network_delegate(&network_delegate); 3013 context.Init(); 3014 3015 d.set_credentials(AuthCredentials(kUser, kSecret)); 3016 3017 { 3018 GURL url(test_server_.GetURL("auth-basic")); 3019 URLRequest r(url, &d, &context); 3020 r.Start(); 3021 base::RunLoop().Run(); 3022 3023 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 3024 EXPECT_EQ(0, r.status().error()); 3025 EXPECT_EQ(200, r.GetResponseCode()); 3026 EXPECT_TRUE(d.auth_required_called()); 3027 EXPECT_EQ(1, network_delegate.created_requests()); 3028 EXPECT_EQ(0, network_delegate.destroyed_requests()); 3029 } 3030 EXPECT_EQ(1, network_delegate.destroyed_requests()); 3031} 3032 3033// Tests that the network delegate can asynchronously complete OnAuthRequired 3034// by setting credentials. 3035TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) { 3036 ASSERT_TRUE(test_server_.Start()); 3037 3038 TestDelegate d; 3039 BlockingNetworkDelegate network_delegate( 3040 BlockingNetworkDelegate::AUTO_CALLBACK); 3041 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED); 3042 network_delegate.set_auth_retval( 3043 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH); 3044 3045 AuthCredentials auth_credentials(kUser, kSecret); 3046 network_delegate.set_auth_credentials(auth_credentials); 3047 3048 TestURLRequestContext context(true); 3049 context.set_network_delegate(&network_delegate); 3050 context.Init(); 3051 3052 { 3053 GURL url(test_server_.GetURL("auth-basic")); 3054 URLRequest r(url, &d, &context); 3055 r.Start(); 3056 base::RunLoop().Run(); 3057 3058 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 3059 EXPECT_EQ(0, r.status().error()); 3060 3061 EXPECT_EQ(200, r.GetResponseCode()); 3062 EXPECT_FALSE(d.auth_required_called()); 3063 EXPECT_EQ(1, network_delegate.created_requests()); 3064 EXPECT_EQ(0, network_delegate.destroyed_requests()); 3065 } 3066 EXPECT_EQ(1, network_delegate.destroyed_requests()); 3067} 3068 3069// Tests that the network delegate can asynchronously complete OnAuthRequired 3070// by cancelling authentication. 3071TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) { 3072 ASSERT_TRUE(test_server_.Start()); 3073 3074 TestDelegate d; 3075 BlockingNetworkDelegate network_delegate( 3076 BlockingNetworkDelegate::AUTO_CALLBACK); 3077 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED); 3078 network_delegate.set_auth_retval( 3079 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH); 3080 3081 TestURLRequestContext context(true); 3082 context.set_network_delegate(&network_delegate); 3083 context.Init(); 3084 3085 { 3086 GURL url(test_server_.GetURL("auth-basic")); 3087 URLRequest r(url, &d, &context); 3088 r.Start(); 3089 base::RunLoop().Run(); 3090 3091 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 3092 EXPECT_EQ(OK, r.status().error()); 3093 EXPECT_EQ(401, r.GetResponseCode()); 3094 EXPECT_FALSE(d.auth_required_called()); 3095 EXPECT_EQ(1, network_delegate.created_requests()); 3096 EXPECT_EQ(0, network_delegate.destroyed_requests()); 3097 } 3098 EXPECT_EQ(1, network_delegate.destroyed_requests()); 3099} 3100 3101// Tests that we can handle when a network request was canceled while we were 3102// waiting for the network delegate. 3103// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback. 3104TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) { 3105 ASSERT_TRUE(test_server_.Start()); 3106 3107 TestDelegate d; 3108 BlockingNetworkDelegate network_delegate( 3109 BlockingNetworkDelegate::USER_CALLBACK); 3110 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST); 3111 3112 TestURLRequestContext context(true); 3113 context.set_network_delegate(&network_delegate); 3114 context.Init(); 3115 3116 { 3117 URLRequest r(test_server_.GetURL(std::string()), &d, &context); 3118 3119 r.Start(); 3120 base::RunLoop().Run(); 3121 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST, 3122 network_delegate.stage_blocked_for_callback()); 3123 EXPECT_EQ(0, network_delegate.completed_requests()); 3124 // Cancel before callback. 3125 r.Cancel(); 3126 // Ensure that network delegate is notified. 3127 EXPECT_EQ(1, network_delegate.completed_requests()); 3128 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status()); 3129 EXPECT_EQ(ERR_ABORTED, r.status().error()); 3130 EXPECT_EQ(1, network_delegate.created_requests()); 3131 EXPECT_EQ(0, network_delegate.destroyed_requests()); 3132 } 3133 EXPECT_EQ(1, network_delegate.destroyed_requests()); 3134} 3135 3136// Tests that we can handle when a network request was canceled while we were 3137// waiting for the network delegate. 3138// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback. 3139TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) { 3140 ASSERT_TRUE(test_server_.Start()); 3141 3142 TestDelegate d; 3143 BlockingNetworkDelegate network_delegate( 3144 BlockingNetworkDelegate::USER_CALLBACK); 3145 network_delegate.set_block_on( 3146 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS); 3147 3148 TestURLRequestContext context(true); 3149 context.set_network_delegate(&network_delegate); 3150 context.Init(); 3151 3152 { 3153 URLRequest r(test_server_.GetURL(std::string()), &d, &context); 3154 3155 r.Start(); 3156 base::RunLoop().Run(); 3157 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS, 3158 network_delegate.stage_blocked_for_callback()); 3159 EXPECT_EQ(0, network_delegate.completed_requests()); 3160 // Cancel before callback. 3161 r.Cancel(); 3162 // Ensure that network delegate is notified. 3163 EXPECT_EQ(1, network_delegate.completed_requests()); 3164 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status()); 3165 EXPECT_EQ(ERR_ABORTED, r.status().error()); 3166 EXPECT_EQ(1, network_delegate.created_requests()); 3167 EXPECT_EQ(0, network_delegate.destroyed_requests()); 3168 } 3169 EXPECT_EQ(1, network_delegate.destroyed_requests()); 3170} 3171 3172// Tests that we can handle when a network request was canceled while we were 3173// waiting for the network delegate. 3174// Part 3: Request is cancelled while waiting for OnHeadersReceived callback. 3175TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) { 3176 ASSERT_TRUE(test_server_.Start()); 3177 3178 TestDelegate d; 3179 BlockingNetworkDelegate network_delegate( 3180 BlockingNetworkDelegate::USER_CALLBACK); 3181 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED); 3182 3183 TestURLRequestContext context(true); 3184 context.set_network_delegate(&network_delegate); 3185 context.Init(); 3186 3187 { 3188 URLRequest r(test_server_.GetURL(std::string()), &d, &context); 3189 3190 r.Start(); 3191 base::RunLoop().Run(); 3192 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED, 3193 network_delegate.stage_blocked_for_callback()); 3194 EXPECT_EQ(0, network_delegate.completed_requests()); 3195 // Cancel before callback. 3196 r.Cancel(); 3197 // Ensure that network delegate is notified. 3198 EXPECT_EQ(1, network_delegate.completed_requests()); 3199 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status()); 3200 EXPECT_EQ(ERR_ABORTED, r.status().error()); 3201 EXPECT_EQ(1, network_delegate.created_requests()); 3202 EXPECT_EQ(0, network_delegate.destroyed_requests()); 3203 } 3204 EXPECT_EQ(1, network_delegate.destroyed_requests()); 3205} 3206 3207// Tests that we can handle when a network request was canceled while we were 3208// waiting for the network delegate. 3209// Part 4: Request is cancelled while waiting for OnAuthRequired callback. 3210TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) { 3211 ASSERT_TRUE(test_server_.Start()); 3212 3213 TestDelegate d; 3214 BlockingNetworkDelegate network_delegate( 3215 BlockingNetworkDelegate::USER_CALLBACK); 3216 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED); 3217 3218 TestURLRequestContext context(true); 3219 context.set_network_delegate(&network_delegate); 3220 context.Init(); 3221 3222 { 3223 URLRequest r(test_server_.GetURL("auth-basic"), &d, &context); 3224 3225 r.Start(); 3226 base::RunLoop().Run(); 3227 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED, 3228 network_delegate.stage_blocked_for_callback()); 3229 EXPECT_EQ(0, network_delegate.completed_requests()); 3230 // Cancel before callback. 3231 r.Cancel(); 3232 // Ensure that network delegate is notified. 3233 EXPECT_EQ(1, network_delegate.completed_requests()); 3234 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status()); 3235 EXPECT_EQ(ERR_ABORTED, r.status().error()); 3236 EXPECT_EQ(1, network_delegate.created_requests()); 3237 EXPECT_EQ(0, network_delegate.destroyed_requests()); 3238 } 3239 EXPECT_EQ(1, network_delegate.destroyed_requests()); 3240} 3241 3242// In this unit test, we're using the HTTPTestServer as a proxy server and 3243// issuing a CONNECT request with the magic host name "www.server-auth.com". 3244// The HTTPTestServer will return a 401 response, which we should balk at. 3245TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) { 3246 ASSERT_TRUE(test_server_.Start()); 3247 3248 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 3249 TestURLRequestContextWithProxy context( 3250 test_server_.host_port_pair().ToString(), 3251 &network_delegate); 3252 3253 TestDelegate d; 3254 { 3255 URLRequest r(GURL("https://www.server-auth.com/"), &d, &context); 3256 3257 r.Start(); 3258 EXPECT_TRUE(r.is_pending()); 3259 3260 base::RunLoop().Run(); 3261 3262 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status()); 3263 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error()); 3264 } 3265} 3266 3267TEST_F(URLRequestTestHTTP, GetTest_NoCache) { 3268 ASSERT_TRUE(test_server_.Start()); 3269 3270 TestDelegate d; 3271 { 3272 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_); 3273 3274 r.Start(); 3275 EXPECT_TRUE(r.is_pending()); 3276 3277 base::RunLoop().Run(); 3278 3279 EXPECT_EQ(1, d.response_started_count()); 3280 EXPECT_FALSE(d.received_data_before_response()); 3281 EXPECT_NE(0, d.bytes_received()); 3282 EXPECT_EQ(test_server_.host_port_pair().host(), 3283 r.GetSocketAddress().host()); 3284 EXPECT_EQ(test_server_.host_port_pair().port(), 3285 r.GetSocketAddress().port()); 3286 3287 // TODO(eroman): Add back the NetLog tests... 3288 } 3289} 3290 3291// This test has the server send a large number of cookies to the client. 3292// To ensure that no number of cookies causes a crash, a galloping binary 3293// search is used to estimate that maximum number of cookies that are accepted 3294// by the browser. Beyond the maximum number, the request will fail with 3295// ERR_RESPONSE_HEADERS_TOO_BIG. 3296#if defined(OS_WIN) 3297// http://crbug.com/177916 3298#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies 3299#else 3300#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies 3301#endif // defined(OS_WIN) 3302TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) { 3303 ASSERT_TRUE(test_server_.Start()); 3304 3305 int lower_bound = 0; 3306 int upper_bound = 1; 3307 3308 // Double the number of cookies until the response header limits are 3309 // exceeded. 3310 while (DoManyCookiesRequest(upper_bound)) { 3311 lower_bound = upper_bound; 3312 upper_bound *= 2; 3313 ASSERT_LT(upper_bound, 1000000); 3314 } 3315 3316 int tolerance = upper_bound * 0.005; 3317 if (tolerance < 2) 3318 tolerance = 2; 3319 3320 // Perform a binary search to find the highest possible number of cookies, 3321 // within the desired tolerance. 3322 while (upper_bound - lower_bound >= tolerance) { 3323 int num_cookies = (lower_bound + upper_bound) / 2; 3324 3325 if (DoManyCookiesRequest(num_cookies)) 3326 lower_bound = num_cookies; 3327 else 3328 upper_bound = num_cookies; 3329 } 3330 // Success: the test did not crash. 3331} 3332 3333TEST_F(URLRequestTestHTTP, GetTest) { 3334 ASSERT_TRUE(test_server_.Start()); 3335 3336 TestDelegate d; 3337 { 3338 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_); 3339 3340 r.Start(); 3341 EXPECT_TRUE(r.is_pending()); 3342 3343 base::RunLoop().Run(); 3344 3345 EXPECT_EQ(1, d.response_started_count()); 3346 EXPECT_FALSE(d.received_data_before_response()); 3347 EXPECT_NE(0, d.bytes_received()); 3348 EXPECT_EQ(test_server_.host_port_pair().host(), 3349 r.GetSocketAddress().host()); 3350 EXPECT_EQ(test_server_.host_port_pair().port(), 3351 r.GetSocketAddress().port()); 3352 } 3353} 3354 3355TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) { 3356 ASSERT_TRUE(test_server_.Start()); 3357 3358 TestDelegate d; 3359 { 3360 GURL test_url(test_server_.GetURL(std::string())); 3361 URLRequest r(test_url, &d, &default_context_); 3362 3363 HttpRequestHeaders headers; 3364 EXPECT_FALSE(r.GetFullRequestHeaders(&headers)); 3365 3366 r.Start(); 3367 EXPECT_TRUE(r.is_pending()); 3368 3369 base::RunLoop().Run(); 3370 3371 EXPECT_EQ(1, d.response_started_count()); 3372 EXPECT_FALSE(d.received_data_before_response()); 3373 EXPECT_NE(0, d.bytes_received()); 3374 EXPECT_EQ(test_server_.host_port_pair().host(), 3375 r.GetSocketAddress().host()); 3376 EXPECT_EQ(test_server_.host_port_pair().port(), 3377 r.GetSocketAddress().port()); 3378 3379 EXPECT_TRUE(d.have_full_request_headers()); 3380 CheckFullRequestHeaders(d.full_request_headers(), test_url); 3381 } 3382} 3383 3384TEST_F(URLRequestTestHTTP, GetTestLoadTiming) { 3385 ASSERT_TRUE(test_server_.Start()); 3386 3387 TestDelegate d; 3388 { 3389 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_); 3390 3391 r.Start(); 3392 EXPECT_TRUE(r.is_pending()); 3393 3394 base::RunLoop().Run(); 3395 3396 LoadTimingInfo load_timing_info; 3397 r.GetLoadTimingInfo(&load_timing_info); 3398 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES); 3399 3400 EXPECT_EQ(1, d.response_started_count()); 3401 EXPECT_FALSE(d.received_data_before_response()); 3402 EXPECT_NE(0, d.bytes_received()); 3403 EXPECT_EQ(test_server_.host_port_pair().host(), 3404 r.GetSocketAddress().host()); 3405 EXPECT_EQ(test_server_.host_port_pair().port(), 3406 r.GetSocketAddress().port()); 3407 } 3408} 3409 3410TEST_F(URLRequestTestHTTP, GetZippedTest) { 3411 ASSERT_TRUE(test_server_.Start()); 3412 3413 // Parameter that specifies the Content-Length field in the response: 3414 // C - Compressed length. 3415 // U - Uncompressed length. 3416 // L - Large length (larger than both C & U). 3417 // M - Medium length (between C & U). 3418 // S - Small length (smaller than both C & U). 3419 const char test_parameters[] = "CULMS"; 3420 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL. 3421 // C & U should be OK. 3422 // L & M are larger than the data sent, and show an error. 3423 // S has too little data, but we seem to accept it. 3424 const bool test_expect_success[num_tests] = 3425 { true, true, false, false, true }; 3426 3427 for (int i = 0; i < num_tests ; i++) { 3428 TestDelegate d; 3429 { 3430 std::string test_file = 3431 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c", 3432 test_parameters[i]); 3433 3434 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 3435 TestURLRequestContext context(true); 3436 context.set_network_delegate(&network_delegate); 3437 context.Init(); 3438 3439 URLRequest r(test_server_.GetURL(test_file), &d, &context); 3440 r.Start(); 3441 EXPECT_TRUE(r.is_pending()); 3442 3443 base::RunLoop().Run(); 3444 3445 EXPECT_EQ(1, d.response_started_count()); 3446 EXPECT_FALSE(d.received_data_before_response()); 3447 VLOG(1) << " Received " << d.bytes_received() << " bytes" 3448 << " status = " << r.status().status() 3449 << " error = " << r.status().error(); 3450 if (test_expect_success[i]) { 3451 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()) 3452 << " Parameter = \"" << test_file << "\""; 3453 } else { 3454 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status()); 3455 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error()) 3456 << " Parameter = \"" << test_file << "\""; 3457 } 3458 } 3459 } 3460} 3461 3462TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) { 3463 ASSERT_TRUE(test_server_.Start()); 3464 3465 SpawnedTestServer https_test_server( 3466 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost, 3467 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 3468 ASSERT_TRUE(https_test_server.Start()); 3469 3470 // An https server is sent a request with an https referer, 3471 // and responds with a redirect to an http url. The http 3472 // server should not be sent the referer. 3473 GURL http_destination = test_server_.GetURL(std::string()); 3474 TestDelegate d; 3475 URLRequest req(https_test_server.GetURL( 3476 "server-redirect?" + http_destination.spec()), &d, &default_context_); 3477 req.SetReferrer("https://www.referrer.com/"); 3478 req.Start(); 3479 base::RunLoop().Run(); 3480 3481 EXPECT_EQ(1, d.response_started_count()); 3482 EXPECT_EQ(1, d.received_redirect_count()); 3483 EXPECT_EQ(http_destination, req.url()); 3484 EXPECT_EQ(std::string(), req.referrer()); 3485} 3486 3487TEST_F(URLRequestTestHTTP, RedirectLoadTiming) { 3488 ASSERT_TRUE(test_server_.Start()); 3489 3490 GURL destination_url = test_server_.GetURL(std::string()); 3491 GURL original_url = 3492 test_server_.GetURL("server-redirect?" + destination_url.spec()); 3493 TestDelegate d; 3494 URLRequest req(original_url, &d, &default_context_); 3495 req.Start(); 3496 base::RunLoop().Run(); 3497 3498 EXPECT_EQ(1, d.response_started_count()); 3499 EXPECT_EQ(1, d.received_redirect_count()); 3500 EXPECT_EQ(destination_url, req.url()); 3501 EXPECT_EQ(original_url, req.original_url()); 3502 ASSERT_EQ(2U, req.url_chain().size()); 3503 EXPECT_EQ(original_url, req.url_chain()[0]); 3504 EXPECT_EQ(destination_url, req.url_chain()[1]); 3505 3506 LoadTimingInfo load_timing_info_before_redirect; 3507 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect( 3508 &load_timing_info_before_redirect)); 3509 TestLoadTimingNotReused(load_timing_info_before_redirect, 3510 CONNECT_TIMING_HAS_DNS_TIMES); 3511 3512 LoadTimingInfo load_timing_info; 3513 req.GetLoadTimingInfo(&load_timing_info); 3514 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES); 3515 3516 // Check that a new socket was used on redirect, since the server does not 3517 // supposed keep-alive sockets, and that the times before the redirect are 3518 // before the ones recorded for the second request. 3519 EXPECT_NE(load_timing_info_before_redirect.socket_log_id, 3520 load_timing_info.socket_log_id); 3521 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end, 3522 load_timing_info.connect_timing.connect_start); 3523} 3524 3525TEST_F(URLRequestTestHTTP, MultipleRedirectTest) { 3526 ASSERT_TRUE(test_server_.Start()); 3527 3528 GURL destination_url = test_server_.GetURL(std::string()); 3529 GURL middle_redirect_url = 3530 test_server_.GetURL("server-redirect?" + destination_url.spec()); 3531 GURL original_url = test_server_.GetURL( 3532 "server-redirect?" + middle_redirect_url.spec()); 3533 TestDelegate d; 3534 URLRequest req(original_url, &d, &default_context_); 3535 req.Start(); 3536 base::RunLoop().Run(); 3537 3538 EXPECT_EQ(1, d.response_started_count()); 3539 EXPECT_EQ(2, d.received_redirect_count()); 3540 EXPECT_EQ(destination_url, req.url()); 3541 EXPECT_EQ(original_url, req.original_url()); 3542 ASSERT_EQ(3U, req.url_chain().size()); 3543 EXPECT_EQ(original_url, req.url_chain()[0]); 3544 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]); 3545 EXPECT_EQ(destination_url, req.url_chain()[2]); 3546} 3547 3548namespace { 3549 3550const char kExtraHeader[] = "Allow-Snafu"; 3551const char kExtraValue[] = "fubar"; 3552 3553class RedirectWithAdditionalHeadersDelegate : public TestDelegate { 3554 virtual void OnReceivedRedirect(net::URLRequest* request, 3555 const GURL& new_url, 3556 bool* defer_redirect) OVERRIDE { 3557 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect); 3558 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false); 3559 } 3560}; 3561 3562} // namespace 3563 3564TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) { 3565 ASSERT_TRUE(test_server_.Start()); 3566 3567 GURL destination_url = test_server_.GetURL( 3568 "echoheader?" + std::string(kExtraHeader)); 3569 GURL original_url = test_server_.GetURL( 3570 "server-redirect?" + destination_url.spec()); 3571 RedirectWithAdditionalHeadersDelegate d; 3572 URLRequest req(original_url, &d, &default_context_); 3573 req.Start(); 3574 base::RunLoop().Run(); 3575 3576 std::string value; 3577 const HttpRequestHeaders& headers = req.extra_request_headers(); 3578 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value)); 3579 EXPECT_EQ(kExtraValue, value); 3580 EXPECT_FALSE(req.is_pending()); 3581 EXPECT_FALSE(req.is_redirecting()); 3582 EXPECT_EQ(kExtraValue, d.data_received()); 3583} 3584 3585namespace { 3586 3587const char kExtraHeaderToRemove[] = "To-Be-Removed"; 3588 3589class RedirectWithHeaderRemovalDelegate : public TestDelegate { 3590 virtual void OnReceivedRedirect(net::URLRequest* request, 3591 const GURL& new_url, 3592 bool* defer_redirect) OVERRIDE { 3593 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect); 3594 request->RemoveRequestHeaderByName(kExtraHeaderToRemove); 3595 } 3596}; 3597 3598} // namespace 3599 3600TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) { 3601 ASSERT_TRUE(test_server_.Start()); 3602 3603 GURL destination_url = test_server_.GetURL( 3604 "echoheader?" + std::string(kExtraHeaderToRemove)); 3605 GURL original_url = test_server_.GetURL( 3606 "server-redirect?" + destination_url.spec()); 3607 RedirectWithHeaderRemovalDelegate d; 3608 URLRequest req(original_url, &d, &default_context_); 3609 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false); 3610 req.Start(); 3611 base::RunLoop().Run(); 3612 3613 std::string value; 3614 const HttpRequestHeaders& headers = req.extra_request_headers(); 3615 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value)); 3616 EXPECT_FALSE(req.is_pending()); 3617 EXPECT_FALSE(req.is_redirecting()); 3618 EXPECT_EQ("None", d.data_received()); 3619} 3620 3621TEST_F(URLRequestTestHTTP, CancelTest) { 3622 TestDelegate d; 3623 { 3624 URLRequest r(GURL("http://www.google.com/"), &d, &default_context_); 3625 3626 r.Start(); 3627 EXPECT_TRUE(r.is_pending()); 3628 3629 r.Cancel(); 3630 3631 base::RunLoop().Run(); 3632 3633 // We expect to receive OnResponseStarted even though the request has been 3634 // cancelled. 3635 EXPECT_EQ(1, d.response_started_count()); 3636 EXPECT_EQ(0, d.bytes_received()); 3637 EXPECT_FALSE(d.received_data_before_response()); 3638 } 3639} 3640 3641TEST_F(URLRequestTestHTTP, CancelTest2) { 3642 ASSERT_TRUE(test_server_.Start()); 3643 3644 TestDelegate d; 3645 { 3646 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_); 3647 3648 d.set_cancel_in_response_started(true); 3649 3650 r.Start(); 3651 EXPECT_TRUE(r.is_pending()); 3652 3653 base::RunLoop().Run(); 3654 3655 EXPECT_EQ(1, d.response_started_count()); 3656 EXPECT_EQ(0, d.bytes_received()); 3657 EXPECT_FALSE(d.received_data_before_response()); 3658 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status()); 3659 } 3660} 3661 3662TEST_F(URLRequestTestHTTP, CancelTest3) { 3663 ASSERT_TRUE(test_server_.Start()); 3664 3665 TestDelegate d; 3666 { 3667 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_); 3668 3669 d.set_cancel_in_received_data(true); 3670 3671 r.Start(); 3672 EXPECT_TRUE(r.is_pending()); 3673 3674 base::RunLoop().Run(); 3675 3676 EXPECT_EQ(1, d.response_started_count()); 3677 // There is no guarantee about how much data was received 3678 // before the cancel was issued. It could have been 0 bytes, 3679 // or it could have been all the bytes. 3680 // EXPECT_EQ(0, d.bytes_received()); 3681 EXPECT_FALSE(d.received_data_before_response()); 3682 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status()); 3683 } 3684} 3685 3686TEST_F(URLRequestTestHTTP, CancelTest4) { 3687 ASSERT_TRUE(test_server_.Start()); 3688 3689 TestDelegate d; 3690 { 3691 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_); 3692 3693 r.Start(); 3694 EXPECT_TRUE(r.is_pending()); 3695 3696 // The request will be implicitly canceled when it is destroyed. The 3697 // test delegate must not post a quit message when this happens because 3698 // this test doesn't actually have a message loop. The quit message would 3699 // get put on this thread's message queue and the next test would exit 3700 // early, causing problems. 3701 d.set_quit_on_complete(false); 3702 } 3703 // expect things to just cleanup properly. 3704 3705 // we won't actually get a received reponse here because we've never run the 3706 // message loop 3707 EXPECT_FALSE(d.received_data_before_response()); 3708 EXPECT_EQ(0, d.bytes_received()); 3709} 3710 3711TEST_F(URLRequestTestHTTP, CancelTest5) { 3712 ASSERT_TRUE(test_server_.Start()); 3713 3714 // populate cache 3715 { 3716 TestDelegate d; 3717 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_); 3718 r.Start(); 3719 base::RunLoop().Run(); 3720 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status()); 3721 } 3722 3723 // cancel read from cache (see bug 990242) 3724 { 3725 TestDelegate d; 3726 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_); 3727 r.Start(); 3728 r.Cancel(); 3729 base::RunLoop().Run(); 3730 3731 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status()); 3732 EXPECT_EQ(1, d.response_started_count()); 3733 EXPECT_EQ(0, d.bytes_received()); 3734 EXPECT_FALSE(d.received_data_before_response()); 3735 } 3736} 3737 3738TEST_F(URLRequestTestHTTP, PostTest) { 3739 ASSERT_TRUE(test_server_.Start()); 3740 HTTPUploadDataOperationTest("POST"); 3741} 3742 3743TEST_F(URLRequestTestHTTP, PutTest) { 3744 ASSERT_TRUE(test_server_.Start()); 3745 HTTPUploadDataOperationTest("PUT"); 3746} 3747 3748TEST_F(URLRequestTestHTTP, PostEmptyTest) { 3749 ASSERT_TRUE(test_server_.Start()); 3750 3751 TestDelegate d; 3752 { 3753 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_); 3754 r.set_method("POST"); 3755 3756 r.Start(); 3757 EXPECT_TRUE(r.is_pending()); 3758 3759 base::RunLoop().Run(); 3760 3761 ASSERT_EQ(1, d.response_started_count()) 3762 << "request failed: " << r.status().status() 3763 << ", error: " << r.status().error(); 3764 3765 EXPECT_FALSE(d.received_data_before_response()); 3766 EXPECT_TRUE(d.data_received().empty()); 3767 } 3768} 3769 3770TEST_F(URLRequestTestHTTP, PostFileTest) { 3771 ASSERT_TRUE(test_server_.Start()); 3772 3773 TestDelegate d; 3774 { 3775 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_); 3776 r.set_method("POST"); 3777 3778 base::FilePath dir; 3779 PathService::Get(base::DIR_EXE, &dir); 3780 file_util::SetCurrentDirectory(dir); 3781 3782 ScopedVector<UploadElementReader> element_readers; 3783 3784 base::FilePath path; 3785 PathService::Get(base::DIR_SOURCE_ROOT, &path); 3786 path = path.Append(FILE_PATH_LITERAL("net")); 3787 path = path.Append(FILE_PATH_LITERAL("data")); 3788 path = path.Append(FILE_PATH_LITERAL("url_request_unittest")); 3789 path = path.Append(FILE_PATH_LITERAL("with-headers.html")); 3790 element_readers.push_back( 3791 new UploadFileElementReader(base::MessageLoopProxy::current().get(), 3792 path, 3793 0, 3794 kuint64max, 3795 base::Time())); 3796 3797 // This file should just be ignored in the upload stream. 3798 element_readers.push_back(new UploadFileElementReader( 3799 base::MessageLoopProxy::current().get(), 3800 base::FilePath(FILE_PATH_LITERAL( 3801 "c:\\path\\to\\non\\existant\\file.randomness.12345")), 3802 0, 3803 kuint64max, 3804 base::Time())); 3805 r.set_upload(make_scoped_ptr(new UploadDataStream(&element_readers, 0))); 3806 3807 r.Start(); 3808 EXPECT_TRUE(r.is_pending()); 3809 3810 base::RunLoop().Run(); 3811 3812 int64 size = 0; 3813 ASSERT_EQ(true, file_util::GetFileSize(path, &size)); 3814 scoped_ptr<char[]> buf(new char[size]); 3815 3816 ASSERT_EQ(size, file_util::ReadFile(path, buf.get(), size)); 3817 3818 ASSERT_EQ(1, d.response_started_count()) 3819 << "request failed: " << r.status().status() 3820 << ", error: " << r.status().error(); 3821 3822 EXPECT_FALSE(d.received_data_before_response()); 3823 3824 EXPECT_EQ(size, d.bytes_received()); 3825 EXPECT_EQ(std::string(&buf[0], size), d.data_received()); 3826 } 3827} 3828 3829TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) { 3830 ASSERT_TRUE(test_server_.Start()); 3831 3832 TestDelegate d; 3833 { 3834 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_); 3835 r.EnableChunkedUpload(); 3836 r.set_method("POST"); 3837 AddChunksToUpload(&r); 3838 r.Start(); 3839 EXPECT_TRUE(r.is_pending()); 3840 3841 base::RunLoop().Run(); 3842 3843 VerifyReceivedDataMatchesChunks(&r, &d); 3844 } 3845} 3846 3847TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) { 3848 ASSERT_TRUE(test_server_.Start()); 3849 3850 TestDelegate d; 3851 { 3852 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_); 3853 r.EnableChunkedUpload(); 3854 r.set_method("POST"); 3855 r.Start(); 3856 EXPECT_TRUE(r.is_pending()); 3857 AddChunksToUpload(&r); 3858 base::RunLoop().Run(); 3859 3860 VerifyReceivedDataMatchesChunks(&r, &d); 3861 } 3862} 3863 3864TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) { 3865 ASSERT_TRUE(test_server_.Start()); 3866 3867 TestDelegate d; 3868 { 3869 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_); 3870 r.EnableChunkedUpload(); 3871 r.set_method("POST"); 3872 r.Start(); 3873 EXPECT_TRUE(r.is_pending()); 3874 3875 base::RunLoop().RunUntilIdle(); 3876 AddChunksToUpload(&r); 3877 base::RunLoop().Run(); 3878 3879 VerifyReceivedDataMatchesChunks(&r, &d); 3880 } 3881} 3882 3883TEST_F(URLRequestTestHTTP, ResponseHeadersTest) { 3884 ASSERT_TRUE(test_server_.Start()); 3885 3886 TestDelegate d; 3887 URLRequest req( 3888 test_server_.GetURL("files/with-headers.html"), &d, &default_context_); 3889 req.Start(); 3890 base::RunLoop().Run(); 3891 3892 const HttpResponseHeaders* headers = req.response_headers(); 3893 3894 // Simple sanity check that response_info() accesses the same data. 3895 EXPECT_EQ(headers, req.response_info().headers.get()); 3896 3897 std::string header; 3898 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header)); 3899 EXPECT_EQ("private", header); 3900 3901 header.clear(); 3902 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header)); 3903 EXPECT_EQ("text/html; charset=ISO-8859-1", header); 3904 3905 // The response has two "X-Multiple-Entries" headers. 3906 // This verfies our output has them concatenated together. 3907 header.clear(); 3908 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header)); 3909 EXPECT_EQ("a, b", header); 3910} 3911 3912TEST_F(URLRequestTestHTTP, ProcessSTS) { 3913 SpawnedTestServer::SSLOptions ssl_options; 3914 SpawnedTestServer https_test_server( 3915 SpawnedTestServer::TYPE_HTTPS, 3916 ssl_options, 3917 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest"))); 3918 ASSERT_TRUE(https_test_server.Start()); 3919 3920 TestDelegate d; 3921 URLRequest request( 3922 https_test_server.GetURL("files/hsts-headers.html"), 3923 &d, 3924 &default_context_); 3925 request.Start(); 3926 base::RunLoop().Run(); 3927 3928 TransportSecurityState* security_state = 3929 default_context_.transport_security_state(); 3930 bool sni_available = true; 3931 TransportSecurityState::DomainState domain_state; 3932 EXPECT_TRUE(security_state->GetDomainState( 3933 SpawnedTestServer::kLocalhost, sni_available, &domain_state)); 3934 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS, 3935 domain_state.upgrade_mode); 3936 EXPECT_TRUE(domain_state.sts_include_subdomains); 3937 EXPECT_FALSE(domain_state.pkp_include_subdomains); 3938#if defined(OS_ANDROID) 3939 // Android's CertVerifyProc does not (yet) handle pins. 3940#else 3941 EXPECT_FALSE(domain_state.HasPublicKeyPins()); 3942#endif 3943} 3944 3945// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will 3946// reject HPKP headers, and a test setting only HPKP headers will fail (no 3947// DomainState present because header rejected). 3948#if defined(OS_ANDROID) 3949#define MAYBE_ProcessPKP DISABLED_ProcessPKP 3950#else 3951#define MAYBE_ProcessPKP ProcessPKP 3952#endif 3953 3954// Tests that enabling HPKP on a domain does not affect the HSTS 3955// validity/expiration. 3956TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) { 3957 SpawnedTestServer::SSLOptions ssl_options; 3958 SpawnedTestServer https_test_server( 3959 SpawnedTestServer::TYPE_HTTPS, 3960 ssl_options, 3961 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest"))); 3962 ASSERT_TRUE(https_test_server.Start()); 3963 3964 TestDelegate d; 3965 URLRequest request( 3966 https_test_server.GetURL("files/hpkp-headers.html"), 3967 &d, 3968 &default_context_); 3969 request.Start(); 3970 base::RunLoop().Run(); 3971 3972 TransportSecurityState* security_state = 3973 default_context_.transport_security_state(); 3974 bool sni_available = true; 3975 TransportSecurityState::DomainState domain_state; 3976 EXPECT_TRUE(security_state->GetDomainState( 3977 SpawnedTestServer::kLocalhost, sni_available, &domain_state)); 3978 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT, 3979 domain_state.upgrade_mode); 3980 EXPECT_FALSE(domain_state.sts_include_subdomains); 3981 EXPECT_FALSE(domain_state.pkp_include_subdomains); 3982 EXPECT_TRUE(domain_state.HasPublicKeyPins()); 3983 EXPECT_NE(domain_state.upgrade_expiry, 3984 domain_state.dynamic_spki_hashes_expiry); 3985} 3986 3987TEST_F(URLRequestTestHTTP, ProcessSTSOnce) { 3988 SpawnedTestServer::SSLOptions ssl_options; 3989 SpawnedTestServer https_test_server( 3990 SpawnedTestServer::TYPE_HTTPS, 3991 ssl_options, 3992 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest"))); 3993 ASSERT_TRUE(https_test_server.Start()); 3994 3995 TestDelegate d; 3996 URLRequest request( 3997 https_test_server.GetURL("files/hsts-multiple-headers.html"), 3998 &d, 3999 &default_context_); 4000 request.Start(); 4001 base::RunLoop().Run(); 4002 4003 // We should have set parameters from the first header, not the second. 4004 TransportSecurityState* security_state = 4005 default_context_.transport_security_state(); 4006 bool sni_available = true; 4007 TransportSecurityState::DomainState domain_state; 4008 EXPECT_TRUE(security_state->GetDomainState( 4009 SpawnedTestServer::kLocalhost, sni_available, &domain_state)); 4010 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS, 4011 domain_state.upgrade_mode); 4012 EXPECT_FALSE(domain_state.sts_include_subdomains); 4013 EXPECT_FALSE(domain_state.pkp_include_subdomains); 4014} 4015 4016TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) { 4017 SpawnedTestServer::SSLOptions ssl_options; 4018 SpawnedTestServer https_test_server( 4019 SpawnedTestServer::TYPE_HTTPS, 4020 ssl_options, 4021 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest"))); 4022 ASSERT_TRUE(https_test_server.Start()); 4023 4024 TestDelegate d; 4025 URLRequest request( 4026 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"), 4027 &d, 4028 &default_context_); 4029 request.Start(); 4030 base::RunLoop().Run(); 4031 4032 // We should have set parameters from the first header, not the second. 4033 TransportSecurityState* security_state = 4034 default_context_.transport_security_state(); 4035 bool sni_available = true; 4036 TransportSecurityState::DomainState domain_state; 4037 EXPECT_TRUE(security_state->GetDomainState( 4038 SpawnedTestServer::kLocalhost, sni_available, &domain_state)); 4039 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS, 4040 domain_state.upgrade_mode); 4041#if defined(OS_ANDROID) 4042 // Android's CertVerifyProc does not (yet) handle pins. 4043#else 4044 EXPECT_TRUE(domain_state.HasPublicKeyPins()); 4045#endif 4046 EXPECT_NE(domain_state.upgrade_expiry, 4047 domain_state.dynamic_spki_hashes_expiry); 4048 4049 // Even though there is an HSTS header asserting includeSubdomains, it is 4050 // the *second* such header, and we MUST process only the first. 4051 EXPECT_FALSE(domain_state.sts_include_subdomains); 4052 // includeSubdomains does not occur in the test HPKP header. 4053 EXPECT_FALSE(domain_state.pkp_include_subdomains); 4054} 4055 4056// Tests that when multiple HPKP headers are present, asserting different 4057// policies, that only the first such policy is processed. 4058TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) { 4059 SpawnedTestServer::SSLOptions ssl_options; 4060 SpawnedTestServer https_test_server( 4061 SpawnedTestServer::TYPE_HTTPS, 4062 ssl_options, 4063 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest"))); 4064 ASSERT_TRUE(https_test_server.Start()); 4065 4066 TestDelegate d; 4067 URLRequest request( 4068 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"), 4069 &d, 4070 &default_context_); 4071 request.Start(); 4072 base::RunLoop().Run(); 4073 4074 TransportSecurityState* security_state = 4075 default_context_.transport_security_state(); 4076 bool sni_available = true; 4077 TransportSecurityState::DomainState domain_state; 4078 EXPECT_TRUE(security_state->GetDomainState( 4079 SpawnedTestServer::kLocalhost, sni_available, &domain_state)); 4080 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS, 4081 domain_state.upgrade_mode); 4082#if defined(OS_ANDROID) 4083 // Android's CertVerifyProc does not (yet) handle pins. 4084#else 4085 EXPECT_TRUE(domain_state.HasPublicKeyPins()); 4086#endif 4087 EXPECT_NE(domain_state.upgrade_expiry, 4088 domain_state.dynamic_spki_hashes_expiry); 4089 4090 EXPECT_TRUE(domain_state.sts_include_subdomains); 4091 EXPECT_FALSE(domain_state.pkp_include_subdomains); 4092} 4093 4094TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) { 4095 ASSERT_TRUE(test_server_.Start()); 4096 4097 TestDelegate d; 4098 URLRequest req(test_server_.GetURL( 4099 "files/content-type-normalization.html"), &d, &default_context_); 4100 req.Start(); 4101 base::RunLoop().Run(); 4102 4103 std::string mime_type; 4104 req.GetMimeType(&mime_type); 4105 EXPECT_EQ("text/html", mime_type); 4106 4107 std::string charset; 4108 req.GetCharset(&charset); 4109 EXPECT_EQ("utf-8", charset); 4110 req.Cancel(); 4111} 4112 4113TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictRedirects) { 4114 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget(). 4115 GURL file_url("file:///foo.txt"); 4116 GURL data_url("data:,foo"); 4117 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current()); 4118 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url)); 4119 DataProtocolHandler data_protocol_handler; 4120 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url)); 4121 4122 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget(). 4123 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url)); 4124 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url)); 4125} 4126 4127TEST_F(URLRequestTestHTTP, RestrictFileRedirects) { 4128 ASSERT_TRUE(test_server_.Start()); 4129 4130 TestDelegate d; 4131 URLRequest req(test_server_.GetURL( 4132 "files/redirect-to-file.html"), &d, &default_context_); 4133 req.Start(); 4134 base::RunLoop().Run(); 4135 4136 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status()); 4137 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error()); 4138} 4139 4140TEST_F(URLRequestTestHTTP, RestrictDataRedirects) { 4141 ASSERT_TRUE(test_server_.Start()); 4142 4143 TestDelegate d; 4144 URLRequest req(test_server_.GetURL( 4145 "files/redirect-to-data.html"), &d, &default_context_); 4146 req.Start(); 4147 base::MessageLoop::current()->Run(); 4148 4149 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status()); 4150 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error()); 4151} 4152 4153TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) { 4154 ASSERT_TRUE(test_server_.Start()); 4155 4156 TestDelegate d; 4157 URLRequest req(test_server_.GetURL( 4158 "files/redirect-to-invalid-url.html"), &d, &default_context_); 4159 req.Start(); 4160 base::RunLoop().Run(); 4161 4162 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status()); 4163 EXPECT_EQ(ERR_INVALID_URL, req.status().error()); 4164} 4165 4166TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) { 4167 ASSERT_TRUE(test_server_.Start()); 4168 4169 TestDelegate d; 4170 URLRequest req( 4171 test_server_.GetURL("echoheader?Referer"), &d, &default_context_); 4172 req.SetReferrer("http://user:pass@foo.com/"); 4173 req.Start(); 4174 base::RunLoop().Run(); 4175 4176 EXPECT_EQ(std::string("http://foo.com/"), d.data_received()); 4177} 4178 4179TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) { 4180 ASSERT_TRUE(test_server_.Start()); 4181 4182 TestDelegate d; 4183 URLRequest req( 4184 test_server_.GetURL("echoheader?Referer"), &d, &default_context_); 4185 req.SetReferrer("http://foo.com/test#fragment"); 4186 req.Start(); 4187 base::RunLoop().Run(); 4188 4189 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received()); 4190} 4191 4192TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) { 4193 ASSERT_TRUE(test_server_.Start()); 4194 4195 TestDelegate d; 4196 URLRequest req( 4197 test_server_.GetURL("echoheader?Referer"), &d, &default_context_); 4198 req.SetReferrer("http://foo.com/test#fragment"); 4199 req.SetReferrer(""); 4200 req.Start(); 4201 base::RunLoop().Run(); 4202 4203 EXPECT_EQ(std::string("None"), d.data_received()); 4204} 4205 4206TEST_F(URLRequestTestHTTP, CancelRedirect) { 4207 ASSERT_TRUE(test_server_.Start()); 4208 4209 TestDelegate d; 4210 { 4211 d.set_cancel_in_received_redirect(true); 4212 URLRequest req( 4213 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_); 4214 req.Start(); 4215 base::RunLoop().Run(); 4216 4217 EXPECT_EQ(1, d.response_started_count()); 4218 EXPECT_EQ(0, d.bytes_received()); 4219 EXPECT_FALSE(d.received_data_before_response()); 4220 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status()); 4221 } 4222} 4223 4224TEST_F(URLRequestTestHTTP, DeferredRedirect) { 4225 ASSERT_TRUE(test_server_.Start()); 4226 4227 TestDelegate d; 4228 { 4229 d.set_quit_on_redirect(true); 4230 GURL test_url(test_server_.GetURL("files/redirect-test.html")); 4231 URLRequest req(test_url, &d, &default_context_); 4232 4233 req.Start(); 4234 base::RunLoop().Run(); 4235 4236 EXPECT_EQ(1, d.received_redirect_count()); 4237 4238 req.FollowDeferredRedirect(); 4239 base::RunLoop().Run(); 4240 4241 EXPECT_EQ(1, d.response_started_count()); 4242 EXPECT_FALSE(d.received_data_before_response()); 4243 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status()); 4244 4245 base::FilePath path; 4246 PathService::Get(base::DIR_SOURCE_ROOT, &path); 4247 path = path.Append(FILE_PATH_LITERAL("net")); 4248 path = path.Append(FILE_PATH_LITERAL("data")); 4249 path = path.Append(FILE_PATH_LITERAL("url_request_unittest")); 4250 path = path.Append(FILE_PATH_LITERAL("with-headers.html")); 4251 4252 std::string contents; 4253 EXPECT_TRUE(file_util::ReadFileToString(path, &contents)); 4254 EXPECT_EQ(contents, d.data_received()); 4255 } 4256} 4257 4258TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) { 4259 ASSERT_TRUE(test_server_.Start()); 4260 4261 TestDelegate d; 4262 { 4263 d.set_quit_on_redirect(true); 4264 GURL test_url(test_server_.GetURL("files/redirect-test.html")); 4265 URLRequest req(test_url, &d, &default_context_); 4266 4267 EXPECT_FALSE(d.have_full_request_headers()); 4268 4269 req.Start(); 4270 base::RunLoop().Run(); 4271 4272 EXPECT_EQ(1, d.received_redirect_count()); 4273 EXPECT_TRUE(d.have_full_request_headers()); 4274 CheckFullRequestHeaders(d.full_request_headers(), test_url); 4275 d.ClearFullRequestHeaders(); 4276 4277 req.FollowDeferredRedirect(); 4278 base::RunLoop().Run(); 4279 4280 GURL target_url(test_server_.GetURL("files/with-headers.html")); 4281 EXPECT_EQ(1, d.response_started_count()); 4282 EXPECT_TRUE(d.have_full_request_headers()); 4283 CheckFullRequestHeaders(d.full_request_headers(), target_url); 4284 EXPECT_FALSE(d.received_data_before_response()); 4285 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status()); 4286 4287 base::FilePath path; 4288 PathService::Get(base::DIR_SOURCE_ROOT, &path); 4289 path = path.Append(FILE_PATH_LITERAL("net")); 4290 path = path.Append(FILE_PATH_LITERAL("data")); 4291 path = path.Append(FILE_PATH_LITERAL("url_request_unittest")); 4292 path = path.Append(FILE_PATH_LITERAL("with-headers.html")); 4293 4294 std::string contents; 4295 EXPECT_TRUE(file_util::ReadFileToString(path, &contents)); 4296 EXPECT_EQ(contents, d.data_received()); 4297 } 4298} 4299 4300TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) { 4301 ASSERT_TRUE(test_server_.Start()); 4302 4303 TestDelegate d; 4304 { 4305 d.set_quit_on_redirect(true); 4306 URLRequest req( 4307 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_); 4308 req.Start(); 4309 base::RunLoop().Run(); 4310 4311 EXPECT_EQ(1, d.received_redirect_count()); 4312 4313 req.Cancel(); 4314 base::RunLoop().Run(); 4315 4316 EXPECT_EQ(1, d.response_started_count()); 4317 EXPECT_EQ(0, d.bytes_received()); 4318 EXPECT_FALSE(d.received_data_before_response()); 4319 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status()); 4320 } 4321} 4322 4323TEST_F(URLRequestTestHTTP, VaryHeader) { 4324 ASSERT_TRUE(test_server_.Start()); 4325 4326 // Populate the cache. 4327 { 4328 TestDelegate d; 4329 URLRequest req( 4330 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_); 4331 HttpRequestHeaders headers; 4332 headers.SetHeader("foo", "1"); 4333 req.SetExtraRequestHeaders(headers); 4334 req.Start(); 4335 base::RunLoop().Run(); 4336 4337 LoadTimingInfo load_timing_info; 4338 req.GetLoadTimingInfo(&load_timing_info); 4339 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES); 4340 } 4341 4342 // Expect a cache hit. 4343 { 4344 TestDelegate d; 4345 URLRequest req( 4346 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_); 4347 HttpRequestHeaders headers; 4348 headers.SetHeader("foo", "1"); 4349 req.SetExtraRequestHeaders(headers); 4350 req.Start(); 4351 base::RunLoop().Run(); 4352 4353 EXPECT_TRUE(req.was_cached()); 4354 4355 LoadTimingInfo load_timing_info; 4356 req.GetLoadTimingInfo(&load_timing_info); 4357 TestLoadTimingCacheHitNoNetwork(load_timing_info); 4358 } 4359 4360 // Expect a cache miss. 4361 { 4362 TestDelegate d; 4363 URLRequest req( 4364 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_); 4365 HttpRequestHeaders headers; 4366 headers.SetHeader("foo", "2"); 4367 req.SetExtraRequestHeaders(headers); 4368 req.Start(); 4369 base::RunLoop().Run(); 4370 4371 EXPECT_FALSE(req.was_cached()); 4372 4373 LoadTimingInfo load_timing_info; 4374 req.GetLoadTimingInfo(&load_timing_info); 4375 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES); 4376 } 4377} 4378 4379TEST_F(URLRequestTestHTTP, BasicAuth) { 4380 ASSERT_TRUE(test_server_.Start()); 4381 4382 // populate the cache 4383 { 4384 TestDelegate d; 4385 d.set_credentials(AuthCredentials(kUser, kSecret)); 4386 4387 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_); 4388 r.Start(); 4389 4390 base::RunLoop().Run(); 4391 4392 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos); 4393 } 4394 4395 // repeat request with end-to-end validation. since auth-basic results in a 4396 // cachable page, we expect this test to result in a 304. in which case, the 4397 // response should be fetched from the cache. 4398 { 4399 TestDelegate d; 4400 d.set_credentials(AuthCredentials(kUser, kSecret)); 4401 4402 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_); 4403 r.set_load_flags(LOAD_VALIDATE_CACHE); 4404 r.Start(); 4405 4406 base::RunLoop().Run(); 4407 4408 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos); 4409 4410 // Should be the same cached document. 4411 EXPECT_TRUE(r.was_cached()); 4412 } 4413} 4414 4415// Check that Set-Cookie headers in 401 responses are respected. 4416// http://crbug.com/6450 4417TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) { 4418 ASSERT_TRUE(test_server_.Start()); 4419 4420 GURL url_requiring_auth = 4421 test_server_.GetURL("auth-basic?set-cookie-if-challenged"); 4422 4423 // Request a page that will give a 401 containing a Set-Cookie header. 4424 // Verify that when the transaction is restarted, it includes the new cookie. 4425 { 4426 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 4427 TestURLRequestContext context(true); 4428 context.set_network_delegate(&network_delegate); 4429 context.Init(); 4430 4431 TestDelegate d; 4432 d.set_credentials(AuthCredentials(kUser, kSecret)); 4433 4434 URLRequest r(url_requiring_auth, &d, &context); 4435 r.Start(); 4436 4437 base::RunLoop().Run(); 4438 4439 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos); 4440 4441 // Make sure we sent the cookie in the restarted transaction. 4442 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true") 4443 != std::string::npos); 4444 } 4445 4446 // Same test as above, except this time the restart is initiated earlier 4447 // (without user intervention since identity is embedded in the URL). 4448 { 4449 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 4450 TestURLRequestContext context(true); 4451 context.set_network_delegate(&network_delegate); 4452 context.Init(); 4453 4454 TestDelegate d; 4455 4456 GURL::Replacements replacements; 4457 std::string username("user2"); 4458 std::string password("secret"); 4459 replacements.SetUsernameStr(username); 4460 replacements.SetPasswordStr(password); 4461 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements); 4462 4463 URLRequest r(url_with_identity, &d, &context); 4464 r.Start(); 4465 4466 base::RunLoop().Run(); 4467 4468 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos); 4469 4470 // Make sure we sent the cookie in the restarted transaction. 4471 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true") 4472 != std::string::npos); 4473 } 4474} 4475 4476// Tests that load timing works as expected with auth and the cache. 4477TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) { 4478 ASSERT_TRUE(test_server_.Start()); 4479 4480 // populate the cache 4481 { 4482 TestDelegate d; 4483 d.set_credentials(AuthCredentials(kUser, kSecret)); 4484 4485 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_); 4486 r.Start(); 4487 4488 base::RunLoop().Run(); 4489 4490 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos); 4491 4492 LoadTimingInfo load_timing_info_before_auth; 4493 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth( 4494 &load_timing_info_before_auth)); 4495 TestLoadTimingNotReused(load_timing_info_before_auth, 4496 CONNECT_TIMING_HAS_DNS_TIMES); 4497 4498 LoadTimingInfo load_timing_info; 4499 r.GetLoadTimingInfo(&load_timing_info); 4500 // The test server does not support keep alive sockets, so the second 4501 // request with auth should use a new socket. 4502 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES); 4503 EXPECT_NE(load_timing_info_before_auth.socket_log_id, 4504 load_timing_info.socket_log_id); 4505 EXPECT_LE(load_timing_info_before_auth.receive_headers_end, 4506 load_timing_info.connect_timing.connect_start); 4507 } 4508 4509 // Repeat request with end-to-end validation. Since auth-basic results in a 4510 // cachable page, we expect this test to result in a 304. In which case, the 4511 // response should be fetched from the cache. 4512 { 4513 TestDelegate d; 4514 d.set_credentials(AuthCredentials(kUser, kSecret)); 4515 4516 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_); 4517 r.set_load_flags(LOAD_VALIDATE_CACHE); 4518 r.Start(); 4519 4520 base::RunLoop().Run(); 4521 4522 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos); 4523 4524 // Should be the same cached document. 4525 EXPECT_TRUE(r.was_cached()); 4526 4527 // Since there was a request that went over the wire, the load timing 4528 // information should include connection times. 4529 LoadTimingInfo load_timing_info; 4530 r.GetLoadTimingInfo(&load_timing_info); 4531 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES); 4532 } 4533} 4534 4535// In this test, we do a POST which the server will 302 redirect. 4536// The subsequent transaction should use GET, and should not send the 4537// Content-Type header. 4538// http://code.google.com/p/chromium/issues/detail?id=843 4539TEST_F(URLRequestTestHTTP, Post302RedirectGet) { 4540 ASSERT_TRUE(test_server_.Start()); 4541 4542 const char kData[] = "hello world"; 4543 4544 TestDelegate d; 4545 URLRequest req( 4546 test_server_.GetURL("files/redirect-to-echoall"), &d, &default_context_); 4547 req.set_method("POST"); 4548 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData))); 4549 4550 // Set headers (some of which are specific to the POST). 4551 HttpRequestHeaders headers; 4552 headers.AddHeadersFromString( 4553 "Content-Type: multipart/form-data; " 4554 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n" 4555 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9," 4556 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n" 4557 "Accept-Language: en-US,en\r\n" 4558 "Accept-Charset: ISO-8859-1,*,utf-8\r\n" 4559 "Content-Length: 11\r\n" 4560 "Origin: http://localhost:1337/"); 4561 req.SetExtraRequestHeaders(headers); 4562 req.Start(); 4563 base::RunLoop().Run(); 4564 4565 std::string mime_type; 4566 req.GetMimeType(&mime_type); 4567 EXPECT_EQ("text/html", mime_type); 4568 4569 const std::string& data = d.data_received(); 4570 4571 // Check that the post-specific headers were stripped: 4572 EXPECT_FALSE(ContainsString(data, "Content-Length:")); 4573 EXPECT_FALSE(ContainsString(data, "Content-Type:")); 4574 EXPECT_FALSE(ContainsString(data, "Origin:")); 4575 4576 // These extra request headers should not have been stripped. 4577 EXPECT_TRUE(ContainsString(data, "Accept:")); 4578 EXPECT_TRUE(ContainsString(data, "Accept-Language:")); 4579 EXPECT_TRUE(ContainsString(data, "Accept-Charset:")); 4580} 4581 4582// The following tests check that we handle mutating the request method for 4583// HTTP redirects as expected. 4584// See http://crbug.com/56373 and http://crbug.com/102130. 4585 4586TEST_F(URLRequestTestHTTP, Redirect301Tests) { 4587 ASSERT_TRUE(test_server_.Start()); 4588 4589 const GURL url = test_server_.GetURL("files/redirect301-to-echo"); 4590 4591 HTTPRedirectMethodTest(url, "POST", "GET", true); 4592 HTTPRedirectMethodTest(url, "PUT", "PUT", true); 4593 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false); 4594} 4595 4596TEST_F(URLRequestTestHTTP, Redirect302Tests) { 4597 ASSERT_TRUE(test_server_.Start()); 4598 4599 const GURL url = test_server_.GetURL("files/redirect302-to-echo"); 4600 4601 HTTPRedirectMethodTest(url, "POST", "GET", true); 4602 HTTPRedirectMethodTest(url, "PUT", "PUT", true); 4603 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false); 4604} 4605 4606TEST_F(URLRequestTestHTTP, Redirect303Tests) { 4607 ASSERT_TRUE(test_server_.Start()); 4608 4609 const GURL url = test_server_.GetURL("files/redirect303-to-echo"); 4610 4611 HTTPRedirectMethodTest(url, "POST", "GET", true); 4612 HTTPRedirectMethodTest(url, "PUT", "GET", true); 4613 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false); 4614} 4615 4616TEST_F(URLRequestTestHTTP, Redirect307Tests) { 4617 ASSERT_TRUE(test_server_.Start()); 4618 4619 const GURL url = test_server_.GetURL("files/redirect307-to-echo"); 4620 4621 HTTPRedirectMethodTest(url, "POST", "POST", true); 4622 HTTPRedirectMethodTest(url, "PUT", "PUT", true); 4623 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false); 4624} 4625 4626TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) { 4627 ASSERT_TRUE(test_server_.Start()); 4628 4629 const char kData[] = "hello world"; 4630 4631 TestDelegate d; 4632 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_); 4633 req.set_method("POST"); 4634 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData))); 4635 HttpRequestHeaders headers; 4636 headers.SetHeader(HttpRequestHeaders::kContentLength, 4637 base::UintToString(arraysize(kData) - 1)); 4638 req.SetExtraRequestHeaders(headers); 4639 4640 URLRequestRedirectJob* job = new URLRequestRedirectJob( 4641 &req, &default_network_delegate_, test_server_.GetURL("echo"), 4642 URLRequestRedirectJob::REDIRECT_302_FOUND); 4643 AddTestInterceptor()->set_main_intercept_job(job); 4644 4645 req.Start(); 4646 base::RunLoop().Run(); 4647 EXPECT_EQ("GET", req.method()); 4648} 4649 4650TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) { 4651 ASSERT_TRUE(test_server_.Start()); 4652 4653 const char kData[] = "hello world"; 4654 4655 TestDelegate d; 4656 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_); 4657 req.set_method("POST"); 4658 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData))); 4659 HttpRequestHeaders headers; 4660 headers.SetHeader(HttpRequestHeaders::kContentLength, 4661 base::UintToString(arraysize(kData) - 1)); 4662 req.SetExtraRequestHeaders(headers); 4663 4664 URLRequestRedirectJob* job = new URLRequestRedirectJob( 4665 &req, &default_network_delegate_, test_server_.GetURL("echo"), 4666 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT); 4667 AddTestInterceptor()->set_main_intercept_job(job); 4668 4669 req.Start(); 4670 base::RunLoop().Run(); 4671 EXPECT_EQ("POST", req.method()); 4672 EXPECT_EQ(kData, d.data_received()); 4673} 4674 4675// Check that default A-L header is sent. 4676TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) { 4677 ASSERT_TRUE(test_server_.Start()); 4678 4679 StaticHttpUserAgentSettings settings("en", EmptyString()); 4680 TestNetworkDelegate network_delegate; // Must outlive URLRequests. 4681 TestURLRequestContext context(true); 4682 context.set_network_delegate(&network_delegate); 4683 context.set_http_user_agent_settings(&settings); 4684 context.Init(); 4685 4686 TestDelegate d; 4687 URLRequest req( 4688 test_server_.GetURL("echoheader?Accept-Language"), &d, &context); 4689 req.Start(); 4690 base::RunLoop().Run(); 4691 EXPECT_EQ("en", d.data_received()); 4692} 4693 4694// Check that an empty A-L header is not sent. http://crbug.com/77365. 4695TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) { 4696 ASSERT_TRUE(test_server_.Start()); 4697 4698 StaticHttpUserAgentSettings settings(EmptyString(), EmptyString()); 4699 TestNetworkDelegate network_delegate; // Must outlive URLRequests. 4700 TestURLRequestContext context(true); 4701 context.set_network_delegate(&network_delegate); 4702 context.Init(); 4703 // We override the language after initialization because empty entries 4704 // get overridden by Init(). 4705 context.set_http_user_agent_settings(&settings); 4706 4707 TestDelegate d; 4708 URLRequest req( 4709 test_server_.GetURL("echoheader?Accept-Language"), &d, &context); 4710 req.Start(); 4711 base::RunLoop().Run(); 4712 EXPECT_EQ("None", d.data_received()); 4713} 4714 4715// Check that if request overrides the A-L header, the default is not appended. 4716// See http://crbug.com/20894 4717TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) { 4718 ASSERT_TRUE(test_server_.Start()); 4719 4720 TestDelegate d; 4721 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"), 4722 &d, 4723 &default_context_); 4724 HttpRequestHeaders headers; 4725 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru"); 4726 req.SetExtraRequestHeaders(headers); 4727 req.Start(); 4728 base::RunLoop().Run(); 4729 EXPECT_EQ(std::string("ru"), d.data_received()); 4730} 4731 4732// Check that default A-E header is sent. 4733TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) { 4734 ASSERT_TRUE(test_server_.Start()); 4735 4736 TestDelegate d; 4737 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"), 4738 &d, 4739 &default_context_); 4740 HttpRequestHeaders headers; 4741 req.SetExtraRequestHeaders(headers); 4742 req.Start(); 4743 base::RunLoop().Run(); 4744 EXPECT_TRUE(ContainsString(d.data_received(), "gzip")); 4745} 4746 4747// Check that if request overrides the A-E header, the default is not appended. 4748// See http://crbug.com/47381 4749TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) { 4750 ASSERT_TRUE(test_server_.Start()); 4751 4752 TestDelegate d; 4753 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"), 4754 &d, 4755 &default_context_); 4756 HttpRequestHeaders headers; 4757 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity"); 4758 req.SetExtraRequestHeaders(headers); 4759 req.Start(); 4760 base::RunLoop().Run(); 4761 EXPECT_FALSE(ContainsString(d.data_received(), "gzip")); 4762 EXPECT_TRUE(ContainsString(d.data_received(), "identity")); 4763} 4764 4765// Check that setting the A-C header sends the proper header. 4766TEST_F(URLRequestTestHTTP, SetAcceptCharset) { 4767 ASSERT_TRUE(test_server_.Start()); 4768 4769 TestDelegate d; 4770 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"), 4771 &d, 4772 &default_context_); 4773 HttpRequestHeaders headers; 4774 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r"); 4775 req.SetExtraRequestHeaders(headers); 4776 req.Start(); 4777 base::RunLoop().Run(); 4778 EXPECT_EQ(std::string("koi-8r"), d.data_received()); 4779} 4780 4781// Check that default User-Agent header is sent. 4782TEST_F(URLRequestTestHTTP, DefaultUserAgent) { 4783 ASSERT_TRUE(test_server_.Start()); 4784 4785 TestDelegate d; 4786 URLRequest req(test_server_.GetURL("echoheader?User-Agent"), 4787 &d, 4788 &default_context_); 4789 req.Start(); 4790 base::RunLoop().Run(); 4791 EXPECT_EQ(req.context()->GetUserAgent(req.url()), d.data_received()); 4792} 4793 4794// Check that if request overrides the User-Agent header, 4795// the default is not appended. 4796TEST_F(URLRequestTestHTTP, OverrideUserAgent) { 4797 ASSERT_TRUE(test_server_.Start()); 4798 4799 TestDelegate d; 4800 URLRequest req(test_server_.GetURL("echoheader?User-Agent"), 4801 &d, 4802 &default_context_); 4803 HttpRequestHeaders headers; 4804 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)"); 4805 req.SetExtraRequestHeaders(headers); 4806 req.Start(); 4807 base::RunLoop().Run(); 4808 // If the net tests are being run with ChromeFrame then we need to allow for 4809 // the 'chromeframe' suffix which is added to the user agent before the 4810 // closing parentheses. 4811 EXPECT_TRUE(StartsWithASCII(d.data_received(), "Lynx (textmode", true)); 4812} 4813 4814// Check that a NULL HttpUserAgentSettings causes the corresponding empty 4815// User-Agent header to be sent but does not send the Accept-Language and 4816// Accept-Charset headers. 4817TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) { 4818 ASSERT_TRUE(test_server_.Start()); 4819 4820 TestNetworkDelegate network_delegate; // Must outlive URLRequests. 4821 TestURLRequestContext context(true); 4822 context.set_network_delegate(&network_delegate); 4823 context.Init(); 4824 // We override the HttpUserAgentSettings after initialization because empty 4825 // entries get overridden by Init(). 4826 context.set_http_user_agent_settings(NULL); 4827 4828 struct { 4829 const char* request; 4830 const char* expected_response; 4831 } tests[] = { { "echoheader?Accept-Language", "None" }, 4832 { "echoheader?Accept-Charset", "None" }, 4833 { "echoheader?User-Agent", "" } }; 4834 4835 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) { 4836 TestDelegate d; 4837 URLRequest req(test_server_.GetURL(tests[i].request), &d, &context); 4838 req.Start(); 4839 base::RunLoop().Run(); 4840 EXPECT_EQ(tests[i].expected_response, d.data_received()) 4841 << " Request = \"" << tests[i].request << "\""; 4842 } 4843} 4844 4845// Make sure that URLRequest passes on its priority updates to 4846// newly-created jobs after the first one. 4847TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) { 4848 ASSERT_TRUE(test_server_.Start()); 4849 4850 TestDelegate d; 4851 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_); 4852 EXPECT_EQ(DEFAULT_PRIORITY, req.priority()); 4853 4854 scoped_refptr<URLRequestRedirectJob> redirect_job = 4855 new URLRequestRedirectJob( 4856 &req, &default_network_delegate_, test_server_.GetURL("echo"), 4857 URLRequestRedirectJob::REDIRECT_302_FOUND); 4858 AddTestInterceptor()->set_main_intercept_job(redirect_job.get()); 4859 4860 req.SetPriority(LOW); 4861 req.Start(); 4862 EXPECT_TRUE(req.is_pending()); 4863 4864 scoped_refptr<URLRequestTestJob> job = 4865 new URLRequestTestJob(&req, &default_network_delegate_); 4866 AddTestInterceptor()->set_main_intercept_job(job.get()); 4867 4868 // Should trigger |job| to be started. 4869 base::RunLoop().Run(); 4870 EXPECT_EQ(LOW, job->priority()); 4871} 4872 4873class HTTPSRequestTest : public testing::Test { 4874 public: 4875 HTTPSRequestTest() : default_context_(true) { 4876 default_context_.set_network_delegate(&default_network_delegate_); 4877 default_context_.Init(); 4878 } 4879 virtual ~HTTPSRequestTest() {} 4880 4881 protected: 4882 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest. 4883 TestURLRequestContext default_context_; 4884}; 4885 4886TEST_F(HTTPSRequestTest, HTTPSGetTest) { 4887 SpawnedTestServer test_server( 4888 SpawnedTestServer::TYPE_HTTPS, 4889 SpawnedTestServer::kLocalhost, 4890 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 4891 ASSERT_TRUE(test_server.Start()); 4892 4893 TestDelegate d; 4894 { 4895 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_); 4896 r.Start(); 4897 EXPECT_TRUE(r.is_pending()); 4898 4899 base::RunLoop().Run(); 4900 4901 EXPECT_EQ(1, d.response_started_count()); 4902 EXPECT_FALSE(d.received_data_before_response()); 4903 EXPECT_NE(0, d.bytes_received()); 4904 CheckSSLInfo(r.ssl_info()); 4905 EXPECT_EQ(test_server.host_port_pair().host(), 4906 r.GetSocketAddress().host()); 4907 EXPECT_EQ(test_server.host_port_pair().port(), 4908 r.GetSocketAddress().port()); 4909 } 4910} 4911 4912TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) { 4913 SpawnedTestServer::SSLOptions ssl_options( 4914 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME); 4915 SpawnedTestServer test_server( 4916 SpawnedTestServer::TYPE_HTTPS, 4917 ssl_options, 4918 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 4919 ASSERT_TRUE(test_server.Start()); 4920 4921 bool err_allowed = true; 4922 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) { 4923 TestDelegate d; 4924 { 4925 d.set_allow_certificate_errors(err_allowed); 4926 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_); 4927 4928 r.Start(); 4929 EXPECT_TRUE(r.is_pending()); 4930 4931 base::RunLoop().Run(); 4932 4933 EXPECT_EQ(1, d.response_started_count()); 4934 EXPECT_FALSE(d.received_data_before_response()); 4935 EXPECT_TRUE(d.have_certificate_errors()); 4936 if (err_allowed) { 4937 EXPECT_NE(0, d.bytes_received()); 4938 CheckSSLInfo(r.ssl_info()); 4939 } else { 4940 EXPECT_EQ(0, d.bytes_received()); 4941 } 4942 } 4943 } 4944} 4945 4946TEST_F(HTTPSRequestTest, HTTPSExpiredTest) { 4947 SpawnedTestServer::SSLOptions ssl_options( 4948 SpawnedTestServer::SSLOptions::CERT_EXPIRED); 4949 SpawnedTestServer test_server( 4950 SpawnedTestServer::TYPE_HTTPS, 4951 ssl_options, 4952 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 4953 ASSERT_TRUE(test_server.Start()); 4954 4955 // Iterate from false to true, just so that we do the opposite of the 4956 // previous test in order to increase test coverage. 4957 bool err_allowed = false; 4958 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) { 4959 TestDelegate d; 4960 { 4961 d.set_allow_certificate_errors(err_allowed); 4962 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_); 4963 4964 r.Start(); 4965 EXPECT_TRUE(r.is_pending()); 4966 4967 base::RunLoop().Run(); 4968 4969 EXPECT_EQ(1, d.response_started_count()); 4970 EXPECT_FALSE(d.received_data_before_response()); 4971 EXPECT_TRUE(d.have_certificate_errors()); 4972 if (err_allowed) { 4973 EXPECT_NE(0, d.bytes_received()); 4974 CheckSSLInfo(r.ssl_info()); 4975 } else { 4976 EXPECT_EQ(0, d.bytes_received()); 4977 } 4978 } 4979 } 4980} 4981 4982// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more 4983// than necessary. 4984TEST_F(HTTPSRequestTest, TLSv1Fallback) { 4985 uint16 default_version_max = SSLConfigService::default_version_max(); 4986 // The OpenSSL library in use may not support TLS 1.1. 4987#if !defined(USE_OPENSSL) 4988 EXPECT_GT(default_version_max, SSL_PROTOCOL_VERSION_TLS1); 4989#endif 4990 if (default_version_max <= SSL_PROTOCOL_VERSION_TLS1) 4991 return; 4992 4993 SpawnedTestServer::SSLOptions ssl_options( 4994 SpawnedTestServer::SSLOptions::CERT_OK); 4995 ssl_options.tls_intolerant = 4996 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1; 4997 SpawnedTestServer test_server( 4998 SpawnedTestServer::TYPE_HTTPS, 4999 ssl_options, 5000 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5001 ASSERT_TRUE(test_server.Start()); 5002 5003 TestDelegate d; 5004 TestURLRequestContext context(true); 5005 context.Init(); 5006 d.set_allow_certificate_errors(true); 5007 URLRequest r(test_server.GetURL(std::string()), &d, &context); 5008 r.Start(); 5009 5010 base::RunLoop().Run(); 5011 5012 EXPECT_EQ(1, d.response_started_count()); 5013 EXPECT_NE(0, d.bytes_received()); 5014 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1), 5015 SSLConnectionStatusToVersion(r.ssl_info().connection_status)); 5016 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK); 5017} 5018 5019// This tests that a load of www.google.com with a certificate error sets 5020// the |certificate_errors_are_fatal| flag correctly. This flag will cause 5021// the interstitial to be fatal. 5022TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) { 5023 SpawnedTestServer::SSLOptions ssl_options( 5024 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME); 5025 SpawnedTestServer test_server( 5026 SpawnedTestServer::TYPE_HTTPS, 5027 ssl_options, 5028 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5029 ASSERT_TRUE(test_server.Start()); 5030 5031 // We require that the URL be www.google.com in order to pick up the 5032 // preloaded HSTS entries in the TransportSecurityState. This means that we 5033 // have to use a MockHostResolver in order to direct www.google.com to the 5034 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1. 5035 5036 MockHostResolver host_resolver; 5037 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 5038 TestURLRequestContext context(true); 5039 context.set_network_delegate(&network_delegate); 5040 context.set_host_resolver(&host_resolver); 5041 TransportSecurityState transport_security_state; 5042 context.set_transport_security_state(&transport_security_state); 5043 context.Init(); 5044 5045 TestDelegate d; 5046 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d", 5047 test_server.host_port_pair().port())), 5048 &d, 5049 &context); 5050 5051 r.Start(); 5052 EXPECT_TRUE(r.is_pending()); 5053 5054 base::RunLoop().Run(); 5055 5056 EXPECT_EQ(1, d.response_started_count()); 5057 EXPECT_FALSE(d.received_data_before_response()); 5058 EXPECT_TRUE(d.have_certificate_errors()); 5059 EXPECT_TRUE(d.certificate_errors_are_fatal()); 5060} 5061 5062// This tests that cached HTTPS page loads do not cause any updates to the 5063// TransportSecurityState. 5064TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) { 5065 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't 5066 // matter. It just has to be any error. 5067 SpawnedTestServer::SSLOptions ssl_options( 5068 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME); 5069 SpawnedTestServer test_server( 5070 SpawnedTestServer::TYPE_HTTPS, 5071 ssl_options, 5072 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5073 ASSERT_TRUE(test_server.Start()); 5074 5075 // We require that the URL be www.google.com in order to pick up the 5076 // preloaded and dynamic HSTS and public key pin entries in the 5077 // TransportSecurityState. This means that we have to use a 5078 // MockHostResolver in order to direct www.google.com to the testserver. 5079 // By default, MockHostResolver maps all hosts to 127.0.0.1. 5080 5081 MockHostResolver host_resolver; 5082 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 5083 TestURLRequestContext context(true); 5084 context.set_network_delegate(&network_delegate); 5085 context.set_host_resolver(&host_resolver); 5086 TransportSecurityState transport_security_state; 5087 TransportSecurityState::DomainState domain_state; 5088 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true, 5089 &domain_state)); 5090 context.set_transport_security_state(&transport_security_state); 5091 context.Init(); 5092 5093 TestDelegate d; 5094 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d", 5095 test_server.host_port_pair().port())), 5096 &d, 5097 &context); 5098 5099 r.Start(); 5100 EXPECT_TRUE(r.is_pending()); 5101 5102 base::RunLoop().Run(); 5103 5104 EXPECT_EQ(1, d.response_started_count()); 5105 EXPECT_FALSE(d.received_data_before_response()); 5106 EXPECT_TRUE(d.have_certificate_errors()); 5107 EXPECT_TRUE(d.certificate_errors_are_fatal()); 5108 5109 // Get a fresh copy of the state, and check that it hasn't been updated. 5110 TransportSecurityState::DomainState new_domain_state; 5111 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true, 5112 &new_domain_state)); 5113 EXPECT_EQ(new_domain_state.upgrade_mode, domain_state.upgrade_mode); 5114 EXPECT_EQ(new_domain_state.sts_include_subdomains, 5115 domain_state.sts_include_subdomains); 5116 EXPECT_EQ(new_domain_state.pkp_include_subdomains, 5117 domain_state.pkp_include_subdomains); 5118 EXPECT_TRUE(FingerprintsEqual(new_domain_state.static_spki_hashes, 5119 domain_state.static_spki_hashes)); 5120 EXPECT_TRUE(FingerprintsEqual(new_domain_state.dynamic_spki_hashes, 5121 domain_state.dynamic_spki_hashes)); 5122 EXPECT_TRUE(FingerprintsEqual(new_domain_state.bad_static_spki_hashes, 5123 domain_state.bad_static_spki_hashes)); 5124} 5125 5126// Make sure HSTS preserves a POST request's method and body. 5127TEST_F(HTTPSRequestTest, HSTSPreservesPosts) { 5128 static const char kData[] = "hello world"; 5129 5130 SpawnedTestServer::SSLOptions ssl_options( 5131 SpawnedTestServer::SSLOptions::CERT_OK); 5132 SpawnedTestServer test_server( 5133 SpawnedTestServer::TYPE_HTTPS, 5134 ssl_options, 5135 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5136 ASSERT_TRUE(test_server.Start()); 5137 5138 5139 // Per spec, TransportSecurityState expects a domain name, rather than an IP 5140 // address, so a MockHostResolver is needed to redirect www.somewhere.com to 5141 // the SpawnedTestServer. By default, MockHostResolver maps all hosts 5142 // to 127.0.0.1. 5143 MockHostResolver host_resolver; 5144 5145 // Force https for www.somewhere.com. 5146 TransportSecurityState transport_security_state; 5147 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000); 5148 bool include_subdomains = false; 5149 transport_security_state.AddHSTS("www.somewhere.com", expiry, 5150 include_subdomains); 5151 5152 TestNetworkDelegate network_delegate; // Must outlive URLRequest. 5153 5154 TestURLRequestContext context(true); 5155 context.set_host_resolver(&host_resolver); 5156 context.set_transport_security_state(&transport_security_state); 5157 context.set_network_delegate(&network_delegate); 5158 context.Init(); 5159 5160 TestDelegate d; 5161 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will 5162 // cause a certificate error. Ignore the error. 5163 d.set_allow_certificate_errors(true); 5164 5165 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo", 5166 test_server.host_port_pair().port())), 5167 &d, 5168 &context); 5169 req.set_method("POST"); 5170 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData))); 5171 5172 req.Start(); 5173 base::RunLoop().Run(); 5174 5175 EXPECT_EQ("https", req.url().scheme()); 5176 EXPECT_EQ("POST", req.method()); 5177 EXPECT_EQ(kData, d.data_received()); 5178 5179 LoadTimingInfo load_timing_info; 5180 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info); 5181 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits 5182 TestLoadTimingCacheHitNoNetwork(load_timing_info); 5183} 5184 5185TEST_F(HTTPSRequestTest, SSLv3Fallback) { 5186 SpawnedTestServer::SSLOptions ssl_options( 5187 SpawnedTestServer::SSLOptions::CERT_OK); 5188 ssl_options.tls_intolerant = 5189 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL; 5190 SpawnedTestServer test_server( 5191 SpawnedTestServer::TYPE_HTTPS, 5192 ssl_options, 5193 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5194 ASSERT_TRUE(test_server.Start()); 5195 5196 TestDelegate d; 5197 TestURLRequestContext context(true); 5198 context.Init(); 5199 d.set_allow_certificate_errors(true); 5200 URLRequest r(test_server.GetURL(std::string()), &d, &context); 5201 r.Start(); 5202 5203 base::RunLoop().Run(); 5204 5205 EXPECT_EQ(1, d.response_started_count()); 5206 EXPECT_NE(0, d.bytes_received()); 5207 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3), 5208 SSLConnectionStatusToVersion(r.ssl_info().connection_status)); 5209 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK); 5210} 5211 5212namespace { 5213 5214class SSLClientAuthTestDelegate : public TestDelegate { 5215 public: 5216 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) { 5217 } 5218 virtual void OnCertificateRequested( 5219 URLRequest* request, 5220 SSLCertRequestInfo* cert_request_info) OVERRIDE { 5221 on_certificate_requested_count_++; 5222 base::MessageLoop::current()->Quit(); 5223 } 5224 int on_certificate_requested_count() { 5225 return on_certificate_requested_count_; 5226 } 5227 private: 5228 int on_certificate_requested_count_; 5229}; 5230 5231} // namespace 5232 5233// TODO(davidben): Test the rest of the code. Specifically, 5234// - Filtering which certificates to select. 5235// - Sending a certificate back. 5236// - Getting a certificate request in an SSL renegotiation sending the 5237// HTTP request. 5238TEST_F(HTTPSRequestTest, ClientAuthTest) { 5239 SpawnedTestServer::SSLOptions ssl_options; 5240 ssl_options.request_client_certificate = true; 5241 SpawnedTestServer test_server( 5242 SpawnedTestServer::TYPE_HTTPS, 5243 ssl_options, 5244 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5245 ASSERT_TRUE(test_server.Start()); 5246 5247 SSLClientAuthTestDelegate d; 5248 { 5249 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_); 5250 5251 r.Start(); 5252 EXPECT_TRUE(r.is_pending()); 5253 5254 base::RunLoop().Run(); 5255 5256 EXPECT_EQ(1, d.on_certificate_requested_count()); 5257 EXPECT_FALSE(d.received_data_before_response()); 5258 EXPECT_EQ(0, d.bytes_received()); 5259 5260 // Send no certificate. 5261 // TODO(davidben): Get temporary client cert import (with keys) working on 5262 // all platforms so we can test sending a cert as well. 5263 r.ContinueWithCertificate(NULL); 5264 5265 base::RunLoop().Run(); 5266 5267 EXPECT_EQ(1, d.response_started_count()); 5268 EXPECT_FALSE(d.received_data_before_response()); 5269 EXPECT_NE(0, d.bytes_received()); 5270 } 5271} 5272 5273TEST_F(HTTPSRequestTest, ResumeTest) { 5274 // Test that we attempt a session resume when making two connections to the 5275 // same host. 5276 SpawnedTestServer::SSLOptions ssl_options; 5277 ssl_options.record_resume = true; 5278 SpawnedTestServer test_server( 5279 SpawnedTestServer::TYPE_HTTPS, 5280 ssl_options, 5281 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5282 ASSERT_TRUE(test_server.Start()); 5283 5284 SSLClientSocket::ClearSessionCache(); 5285 5286 { 5287 TestDelegate d; 5288 URLRequest r( 5289 test_server.GetURL("ssl-session-cache"), &d, &default_context_); 5290 5291 r.Start(); 5292 EXPECT_TRUE(r.is_pending()); 5293 5294 base::RunLoop().Run(); 5295 5296 EXPECT_EQ(1, d.response_started_count()); 5297 } 5298 5299 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())-> 5300 CloseAllConnections(); 5301 5302 { 5303 TestDelegate d; 5304 URLRequest r( 5305 test_server.GetURL("ssl-session-cache"), &d, &default_context_); 5306 5307 r.Start(); 5308 EXPECT_TRUE(r.is_pending()); 5309 5310 base::RunLoop().Run(); 5311 5312 // The response will look like; 5313 // insert abc 5314 // lookup abc 5315 // insert xyz 5316 // 5317 // With a newline at the end which makes the split think that there are 5318 // four lines. 5319 5320 EXPECT_EQ(1, d.response_started_count()); 5321 std::vector<std::string> lines; 5322 base::SplitString(d.data_received(), '\n', &lines); 5323 ASSERT_EQ(4u, lines.size()) << d.data_received(); 5324 5325 std::string session_id; 5326 5327 for (size_t i = 0; i < 2; i++) { 5328 std::vector<std::string> parts; 5329 base::SplitString(lines[i], '\t', &parts); 5330 ASSERT_EQ(2u, parts.size()); 5331 if (i == 0) { 5332 EXPECT_EQ("insert", parts[0]); 5333 session_id = parts[1]; 5334 } else { 5335 EXPECT_EQ("lookup", parts[0]); 5336 EXPECT_EQ(session_id, parts[1]); 5337 } 5338 } 5339 } 5340} 5341 5342TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) { 5343 // Test that sessions aren't resumed when the value of ssl_session_cache_shard 5344 // differs. 5345 SpawnedTestServer::SSLOptions ssl_options; 5346 ssl_options.record_resume = true; 5347 SpawnedTestServer test_server( 5348 SpawnedTestServer::TYPE_HTTPS, 5349 ssl_options, 5350 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5351 ASSERT_TRUE(test_server.Start()); 5352 5353 SSLClientSocket::ClearSessionCache(); 5354 5355 { 5356 TestDelegate d; 5357 URLRequest r( 5358 test_server.GetURL("ssl-session-cache"), &d, &default_context_); 5359 5360 r.Start(); 5361 EXPECT_TRUE(r.is_pending()); 5362 5363 base::RunLoop().Run(); 5364 5365 EXPECT_EQ(1, d.response_started_count()); 5366 } 5367 5368 // Now create a new HttpCache with a different ssl_session_cache_shard value. 5369 HttpNetworkSession::Params params; 5370 params.host_resolver = default_context_.host_resolver(); 5371 params.cert_verifier = default_context_.cert_verifier(); 5372 params.transport_security_state = default_context_.transport_security_state(); 5373 params.proxy_service = default_context_.proxy_service(); 5374 params.ssl_config_service = default_context_.ssl_config_service(); 5375 params.http_auth_handler_factory = 5376 default_context_.http_auth_handler_factory(); 5377 params.network_delegate = &default_network_delegate_; 5378 params.http_server_properties = default_context_.http_server_properties(); 5379 params.ssl_session_cache_shard = "alternate"; 5380 5381 scoped_ptr<net::HttpCache> cache(new net::HttpCache( 5382 new net::HttpNetworkSession(params), 5383 net::HttpCache::DefaultBackend::InMemory(0))); 5384 5385 default_context_.set_http_transaction_factory(cache.get()); 5386 5387 { 5388 TestDelegate d; 5389 URLRequest r( 5390 test_server.GetURL("ssl-session-cache"), &d, &default_context_); 5391 5392 r.Start(); 5393 EXPECT_TRUE(r.is_pending()); 5394 5395 base::RunLoop().Run(); 5396 5397 // The response will look like; 5398 // insert abc 5399 // insert xyz 5400 // 5401 // With a newline at the end which makes the split think that there are 5402 // three lines. 5403 5404 EXPECT_EQ(1, d.response_started_count()); 5405 std::vector<std::string> lines; 5406 base::SplitString(d.data_received(), '\n', &lines); 5407 ASSERT_EQ(3u, lines.size()); 5408 5409 std::string session_id; 5410 for (size_t i = 0; i < 2; i++) { 5411 std::vector<std::string> parts; 5412 base::SplitString(lines[i], '\t', &parts); 5413 ASSERT_EQ(2u, parts.size()); 5414 EXPECT_EQ("insert", parts[0]); 5415 if (i == 0) { 5416 session_id = parts[1]; 5417 } else { 5418 EXPECT_NE(session_id, parts[1]); 5419 } 5420 } 5421 } 5422} 5423 5424class TestSSLConfigService : public SSLConfigService { 5425 public: 5426 TestSSLConfigService(bool ev_enabled, 5427 bool online_rev_checking, 5428 bool rev_checking_required_local_anchors) 5429 : ev_enabled_(ev_enabled), 5430 online_rev_checking_(online_rev_checking), 5431 rev_checking_required_local_anchors_( 5432 rev_checking_required_local_anchors) {} 5433 5434 // SSLConfigService: 5435 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE { 5436 *config = SSLConfig(); 5437 config->rev_checking_enabled = online_rev_checking_; 5438 config->verify_ev_cert = ev_enabled_; 5439 config->rev_checking_required_local_anchors = 5440 rev_checking_required_local_anchors_; 5441 } 5442 5443 protected: 5444 virtual ~TestSSLConfigService() {} 5445 5446 private: 5447 const bool ev_enabled_; 5448 const bool online_rev_checking_; 5449 const bool rev_checking_required_local_anchors_; 5450}; 5451 5452// This the fingerprint of the "Testing CA" certificate used by the testserver. 5453// See net/data/ssl/certificates/ocsp-test-root.pem. 5454static const SHA1HashValue kOCSPTestCertFingerprint = 5455 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24, 5456 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } }; 5457 5458// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the 5459// testserver. 5460static const SHA256HashValue kOCSPTestCertSPKI = { { 5461 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e, 5462 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49, 5463 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74, 5464 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28, 5465} }; 5466 5467// This is the policy OID contained in the certificates that testserver 5468// generates. 5469static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1"; 5470 5471class HTTPSOCSPTest : public HTTPSRequestTest { 5472 public: 5473 HTTPSOCSPTest() 5474 : context_(true), 5475 ev_test_policy_( 5476 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(), 5477 kOCSPTestCertFingerprint, 5478 kOCSPTestCertPolicy)) { 5479 } 5480 5481 virtual void SetUp() OVERRIDE { 5482 SetupContext(&context_); 5483 context_.Init(); 5484 5485 scoped_refptr<net::X509Certificate> root_cert = 5486 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem"); 5487 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert); 5488 test_root_.reset(new ScopedTestRoot(root_cert.get())); 5489 5490#if defined(USE_NSS) || defined(OS_IOS) 5491 SetURLRequestContextForNSSHttpIO(&context_); 5492 EnsureNSSHttpIOInit(); 5493#endif 5494 } 5495 5496 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options, 5497 CertStatus* out_cert_status) { 5498 // We always overwrite out_cert_status. 5499 *out_cert_status = 0; 5500 SpawnedTestServer test_server( 5501 SpawnedTestServer::TYPE_HTTPS, 5502 ssl_options, 5503 base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))); 5504 ASSERT_TRUE(test_server.Start()); 5505 5506 TestDelegate d; 5507 d.set_allow_certificate_errors(true); 5508 URLRequest r(test_server.GetURL(std::string()), &d, &context_); 5509 r.Start(); 5510 5511 base::RunLoop().Run(); 5512 5513 EXPECT_EQ(1, d.response_started_count()); 5514 *out_cert_status = r.ssl_info().cert_status; 5515 } 5516 5517 virtual ~HTTPSOCSPTest() { 5518#if defined(USE_NSS) || defined(OS_IOS) 5519 ShutdownNSSHttpIO(); 5520#endif 5521 } 5522 5523 protected: 5524 // SetupContext configures the URLRequestContext that will be used for making 5525 // connetions to testserver. This can be overridden in test subclasses for 5526 // different behaviour. 5527 virtual void SetupContext(URLRequestContext* context) { 5528 context->set_ssl_config_service( 5529 new TestSSLConfigService(true /* check for EV */, 5530 true /* online revocation checking */, 5531 false /* require rev. checking for local 5532 anchors */)); 5533 } 5534 5535 scoped_ptr<ScopedTestRoot> test_root_; 5536 TestURLRequestContext context_; 5537 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_; 5538}; 5539 5540static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() { 5541#if defined(OS_WIN) 5542 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't 5543 // have that ability on other platforms. 5544 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION; 5545#else 5546 return 0; 5547#endif 5548} 5549 5550// SystemSupportsHardFailRevocationChecking returns true iff the current 5551// operating system supports revocation checking and can distinguish between 5552// situations where a given certificate lacks any revocation information (eg: 5553// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when 5554// revocation information cannot be obtained (eg: the CRL was unreachable). 5555// If it does not, then tests which rely on 'hard fail' behaviour should be 5556// skipped. 5557static bool SystemSupportsHardFailRevocationChecking() { 5558#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS) 5559 return true; 5560#else 5561 return false; 5562#endif 5563} 5564 5565// SystemUsesChromiumEVMetadata returns true iff the current operating system 5566// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then 5567// several tests are effected because our testing EV certificate won't be 5568// recognised as EV. 5569static bool SystemUsesChromiumEVMetadata() { 5570#if defined(USE_OPENSSL) 5571 // http://crbug.com/117478 - OpenSSL does not support EV validation. 5572 return false; 5573#elif defined(OS_MACOSX) && !defined(OS_IOS) 5574 // On OS X, we use the system to tell us whether a certificate is EV or not 5575 // and the system won't recognise our testing root. 5576 return false; 5577#else 5578 return true; 5579#endif 5580} 5581 5582static bool SystemSupportsOCSP() { 5583#if defined(USE_OPENSSL) 5584 // http://crbug.com/117478 - OpenSSL does not support OCSP. 5585 return false; 5586#elif defined(OS_WIN) 5587 return base::win::GetVersion() >= base::win::VERSION_VISTA; 5588#elif defined(OS_ANDROID) 5589 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported. 5590 return false; 5591#else 5592 return true; 5593#endif 5594} 5595 5596TEST_F(HTTPSOCSPTest, Valid) { 5597 if (!SystemSupportsOCSP()) { 5598 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5599 return; 5600 } 5601 5602 SpawnedTestServer::SSLOptions ssl_options( 5603 SpawnedTestServer::SSLOptions::CERT_AUTO); 5604 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK; 5605 5606 CertStatus cert_status; 5607 DoConnection(ssl_options, &cert_status); 5608 5609 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS); 5610 5611 EXPECT_EQ(SystemUsesChromiumEVMetadata(), 5612 static_cast<bool>(cert_status & CERT_STATUS_IS_EV)); 5613 5614 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED); 5615} 5616 5617TEST_F(HTTPSOCSPTest, Revoked) { 5618 if (!SystemSupportsOCSP()) { 5619 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5620 return; 5621 } 5622 5623 SpawnedTestServer::SSLOptions ssl_options( 5624 SpawnedTestServer::SSLOptions::CERT_AUTO); 5625 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED; 5626 5627 CertStatus cert_status; 5628 DoConnection(ssl_options, &cert_status); 5629 5630#if !(defined(OS_MACOSX) && !defined(OS_IOS)) 5631 // Doesn't pass on OS X yet for reasons that need to be investigated. 5632 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS); 5633#endif 5634 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5635 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED); 5636} 5637 5638TEST_F(HTTPSOCSPTest, Invalid) { 5639 if (!SystemSupportsOCSP()) { 5640 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5641 return; 5642 } 5643 5644 SpawnedTestServer::SSLOptions ssl_options( 5645 SpawnedTestServer::SSLOptions::CERT_AUTO); 5646 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID; 5647 5648 CertStatus cert_status; 5649 DoConnection(ssl_options, &cert_status); 5650 5651 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(), 5652 cert_status & CERT_STATUS_ALL_ERRORS); 5653 5654 // Without a positive OCSP response, we shouldn't show the EV status. 5655 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5656 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED); 5657} 5658 5659class HTTPSHardFailTest : public HTTPSOCSPTest { 5660 protected: 5661 virtual void SetupContext(URLRequestContext* context) OVERRIDE { 5662 context->set_ssl_config_service( 5663 new TestSSLConfigService(false /* check for EV */, 5664 false /* online revocation checking */, 5665 true /* require rev. checking for local 5666 anchors */)); 5667 } 5668}; 5669 5670 5671TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) { 5672 if (!SystemSupportsOCSP()) { 5673 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5674 return; 5675 } 5676 5677 if (!SystemSupportsHardFailRevocationChecking()) { 5678 LOG(WARNING) << "Skipping test because system doesn't support hard fail " 5679 << "revocation checking"; 5680 return; 5681 } 5682 5683 SpawnedTestServer::SSLOptions ssl_options( 5684 SpawnedTestServer::SSLOptions::CERT_AUTO); 5685 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID; 5686 5687 CertStatus cert_status; 5688 DoConnection(ssl_options, &cert_status); 5689 5690 EXPECT_EQ(CERT_STATUS_REVOKED, 5691 cert_status & CERT_STATUS_REVOKED); 5692 5693 // Without a positive OCSP response, we shouldn't show the EV status. 5694 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED); 5695} 5696 5697class HTTPSEVCRLSetTest : public HTTPSOCSPTest { 5698 protected: 5699 virtual void SetupContext(URLRequestContext* context) OVERRIDE { 5700 context->set_ssl_config_service( 5701 new TestSSLConfigService(true /* check for EV */, 5702 false /* online revocation checking */, 5703 false /* require rev. checking for local 5704 anchors */)); 5705 } 5706}; 5707 5708TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) { 5709 if (!SystemSupportsOCSP()) { 5710 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5711 return; 5712 } 5713 5714 SpawnedTestServer::SSLOptions ssl_options( 5715 SpawnedTestServer::SSLOptions::CERT_AUTO); 5716 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID; 5717 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>()); 5718 5719 CertStatus cert_status; 5720 DoConnection(ssl_options, &cert_status); 5721 5722 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(), 5723 cert_status & CERT_STATUS_ALL_ERRORS); 5724 5725 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5726 EXPECT_EQ(SystemUsesChromiumEVMetadata(), 5727 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED)); 5728} 5729 5730TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) { 5731 if (!SystemSupportsOCSP()) { 5732 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5733 return; 5734 } 5735 5736 SpawnedTestServer::SSLOptions ssl_options( 5737 SpawnedTestServer::SSLOptions::CERT_AUTO); 5738 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK; 5739 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>()); 5740 5741 CertStatus cert_status; 5742 DoConnection(ssl_options, &cert_status); 5743 5744 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS); 5745 5746 EXPECT_EQ(SystemUsesChromiumEVMetadata(), 5747 static_cast<bool>(cert_status & CERT_STATUS_IS_EV)); 5748 EXPECT_EQ(SystemUsesChromiumEVMetadata(), 5749 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED)); 5750} 5751 5752TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) { 5753 if (!SystemSupportsOCSP()) { 5754 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5755 return; 5756 } 5757 5758 SpawnedTestServer::SSLOptions ssl_options( 5759 SpawnedTestServer::SSLOptions::CERT_AUTO); 5760 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID; 5761 SSLConfigService::SetCRLSet( 5762 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting())); 5763 5764 CertStatus cert_status; 5765 DoConnection(ssl_options, &cert_status); 5766 5767 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(), 5768 cert_status & CERT_STATUS_ALL_ERRORS); 5769 5770 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5771 EXPECT_EQ(SystemUsesChromiumEVMetadata(), 5772 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED)); 5773} 5774 5775TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) { 5776 if (!SystemSupportsOCSP()) { 5777 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5778 return; 5779 } 5780 5781 SpawnedTestServer::SSLOptions ssl_options( 5782 SpawnedTestServer::SSLOptions::CERT_AUTO); 5783 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID; 5784 SSLConfigService::SetCRLSet( 5785 scoped_refptr<CRLSet>(CRLSet::ForTesting( 5786 false, &kOCSPTestCertSPKI, ""))); 5787 5788 CertStatus cert_status; 5789 DoConnection(ssl_options, &cert_status); 5790 5791 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a 5792 // revocation check for EV. 5793 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS); 5794 EXPECT_EQ(SystemUsesChromiumEVMetadata(), 5795 static_cast<bool>(cert_status & CERT_STATUS_IS_EV)); 5796 EXPECT_FALSE( 5797 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED)); 5798} 5799 5800TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) { 5801 if (!SystemSupportsOCSP()) { 5802 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5803 return; 5804 } 5805 5806 SpawnedTestServer::SSLOptions ssl_options( 5807 SpawnedTestServer::SSLOptions::CERT_AUTO); 5808 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID; 5809 SSLConfigService::SetCRLSet( 5810 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting())); 5811 5812 CertStatus cert_status = 0; 5813 DoConnection(ssl_options, &cert_status); 5814 5815 // Even with a fresh CRLSet, we should still do online revocation checks when 5816 // the certificate chain isn't covered by the CRLSet, which it isn't in this 5817 // test. 5818 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(), 5819 cert_status & CERT_STATUS_ALL_ERRORS); 5820 5821 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5822 EXPECT_EQ(SystemUsesChromiumEVMetadata(), 5823 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED)); 5824} 5825 5826TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) { 5827 // Test that when EV verification is requested, but online revocation 5828 // checking is disabled, and the leaf certificate is not in fact EV, that 5829 // no revocation checking actually happens. 5830 if (!SystemSupportsOCSP()) { 5831 LOG(WARNING) << "Skipping test because system doesn't support OCSP"; 5832 return; 5833 } 5834 5835 // Unmark the certificate's OID as EV, which should disable revocation 5836 // checking (as per the user preference) 5837 ev_test_policy_.reset(); 5838 5839 SpawnedTestServer::SSLOptions ssl_options( 5840 SpawnedTestServer::SSLOptions::CERT_AUTO); 5841 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED; 5842 SSLConfigService::SetCRLSet( 5843 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting())); 5844 5845 CertStatus cert_status; 5846 DoConnection(ssl_options, &cert_status); 5847 5848 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS); 5849 5850 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5851 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED); 5852} 5853 5854class HTTPSCRLSetTest : public HTTPSOCSPTest { 5855 protected: 5856 virtual void SetupContext(URLRequestContext* context) OVERRIDE { 5857 context->set_ssl_config_service( 5858 new TestSSLConfigService(false /* check for EV */, 5859 false /* online revocation checking */, 5860 false /* require rev. checking for local 5861 anchors */)); 5862 } 5863}; 5864 5865TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) { 5866 SpawnedTestServer::SSLOptions ssl_options( 5867 SpawnedTestServer::SSLOptions::CERT_AUTO); 5868 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID; 5869 SSLConfigService::SetCRLSet( 5870 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting())); 5871 5872 CertStatus cert_status; 5873 DoConnection(ssl_options, &cert_status); 5874 5875 // If we're not trying EV verification then, even if the CRLSet has expired, 5876 // we don't fall back to online revocation checks. 5877 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS); 5878 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5879 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED); 5880} 5881 5882TEST_F(HTTPSCRLSetTest, CRLSetRevoked) { 5883#if defined(USE_OPENSSL) 5884 LOG(WARNING) << "Skipping test because system doesn't support CRLSets"; 5885 return; 5886#endif 5887 5888 SpawnedTestServer::SSLOptions ssl_options( 5889 SpawnedTestServer::SSLOptions::CERT_AUTO); 5890 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK; 5891 ssl_options.cert_serial = 10; 5892 SSLConfigService::SetCRLSet( 5893 scoped_refptr<CRLSet>(CRLSet::ForTesting( 5894 false, &kOCSPTestCertSPKI, "\x0a"))); 5895 5896 CertStatus cert_status = 0; 5897 DoConnection(ssl_options, &cert_status); 5898 5899 // If the certificate is recorded as revoked in the CRLSet, that should be 5900 // reflected without online revocation checking. 5901 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS); 5902 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV); 5903 EXPECT_FALSE( 5904 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED)); 5905} 5906#endif // !defined(OS_IOS) 5907 5908#if !defined(DISABLE_FTP_SUPPORT) 5909class URLRequestTestFTP : public URLRequestTest { 5910 public: 5911 URLRequestTestFTP() 5912 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost, 5913 base::FilePath()) { 5914 } 5915 5916 protected: 5917 SpawnedTestServer test_server_; 5918}; 5919 5920// Make sure an FTP request using an unsafe ports fails. 5921TEST_F(URLRequestTestFTP, UnsafePort) { 5922 ASSERT_TRUE(test_server_.Start()); 5923 5924 URLRequestJobFactoryImpl job_factory; 5925 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver()); 5926 5927 GURL url("ftp://127.0.0.1:7"); 5928 job_factory.SetProtocolHandler( 5929 "ftp", 5930 new FtpProtocolHandler(&ftp_transaction_factory)); 5931 default_context_.set_job_factory(&job_factory); 5932 5933 TestDelegate d; 5934 { 5935 URLRequest r(url, &d, &default_context_); 5936 r.Start(); 5937 EXPECT_TRUE(r.is_pending()); 5938 5939 base::RunLoop().Run(); 5940 5941 EXPECT_FALSE(r.is_pending()); 5942 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status()); 5943 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error()); 5944 } 5945} 5946 5947// Flaky, see http://crbug.com/25045. 5948TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) { 5949 ASSERT_TRUE(test_server_.Start()); 5950 5951 TestDelegate d; 5952 { 5953 URLRequest r(test_server_.GetURL("/"), &d, &default_context_); 5954 r.Start(); 5955 EXPECT_TRUE(r.is_pending()); 5956 5957 base::RunLoop().Run(); 5958 5959 EXPECT_FALSE(r.is_pending()); 5960 EXPECT_EQ(1, d.response_started_count()); 5961 EXPECT_FALSE(d.received_data_before_response()); 5962 EXPECT_LT(0, d.bytes_received()); 5963 EXPECT_EQ(test_server_.host_port_pair().host(), 5964 r.GetSocketAddress().host()); 5965 EXPECT_EQ(test_server_.host_port_pair().port(), 5966 r.GetSocketAddress().port()); 5967 } 5968} 5969 5970// Flaky, see http://crbug.com/25045. 5971TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) { 5972 ASSERT_TRUE(test_server_.Start()); 5973 5974 base::FilePath app_path; 5975 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 5976 app_path = app_path.AppendASCII("LICENSE"); 5977 TestDelegate d; 5978 { 5979 URLRequest r(test_server_.GetURL("/LICENSE"), &d, &default_context_); 5980 r.Start(); 5981 EXPECT_TRUE(r.is_pending()); 5982 5983 base::RunLoop().Run(); 5984 5985 int64 file_size = 0; 5986 file_util::GetFileSize(app_path, &file_size); 5987 5988 EXPECT_FALSE(r.is_pending()); 5989 EXPECT_EQ(1, d.response_started_count()); 5990 EXPECT_FALSE(d.received_data_before_response()); 5991 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size)); 5992 EXPECT_EQ(test_server_.host_port_pair().host(), 5993 r.GetSocketAddress().host()); 5994 EXPECT_EQ(test_server_.host_port_pair().port(), 5995 r.GetSocketAddress().port()); 5996 } 5997} 5998 5999// Flaky, see http://crbug.com/25045. 6000TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) { 6001 ASSERT_TRUE(test_server_.Start()); 6002 6003 base::FilePath app_path; 6004 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 6005 app_path = app_path.AppendASCII("LICENSE"); 6006 TestDelegate d; 6007 { 6008 URLRequest r( 6009 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"), 6010 &d, 6011 &default_context_); 6012 r.Start(); 6013 EXPECT_TRUE(r.is_pending()); 6014 6015 base::RunLoop().Run(); 6016 6017 int64 file_size = 0; 6018 file_util::GetFileSize(app_path, &file_size); 6019 6020 EXPECT_FALSE(r.is_pending()); 6021 EXPECT_EQ(test_server_.host_port_pair().host(), 6022 r.GetSocketAddress().host()); 6023 EXPECT_EQ(test_server_.host_port_pair().port(), 6024 r.GetSocketAddress().port()); 6025 EXPECT_EQ(1, d.response_started_count()); 6026 EXPECT_FALSE(d.received_data_before_response()); 6027 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size)); 6028 6029 LoadTimingInfo load_timing_info; 6030 r.GetLoadTimingInfo(&load_timing_info); 6031 TestLoadTimingNoHttpResponse(load_timing_info); 6032 } 6033} 6034 6035// Flaky, see http://crbug.com/25045. 6036TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) { 6037 ASSERT_TRUE(test_server_.Start()); 6038 6039 base::FilePath app_path; 6040 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 6041 app_path = app_path.AppendASCII("LICENSE"); 6042 TestDelegate d; 6043 { 6044 URLRequest r( 6045 test_server_.GetURLWithUserAndPassword("/LICENSE", 6046 "chrome", 6047 "wrong_password"), 6048 &d, 6049 &default_context_); 6050 r.Start(); 6051 EXPECT_TRUE(r.is_pending()); 6052 6053 base::RunLoop().Run(); 6054 6055 int64 file_size = 0; 6056 file_util::GetFileSize(app_path, &file_size); 6057 6058 EXPECT_FALSE(r.is_pending()); 6059 EXPECT_EQ(1, d.response_started_count()); 6060 EXPECT_FALSE(d.received_data_before_response()); 6061 EXPECT_EQ(d.bytes_received(), 0); 6062 } 6063} 6064 6065// Flaky, see http://crbug.com/25045. 6066TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) { 6067 ASSERT_TRUE(test_server_.Start()); 6068 6069 base::FilePath app_path; 6070 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 6071 app_path = app_path.AppendASCII("LICENSE"); 6072 TestDelegate d; 6073 // Set correct login credentials. The delegate will be asked for them when 6074 // the initial login with wrong credentials will fail. 6075 d.set_credentials(AuthCredentials(kChrome, kChrome)); 6076 { 6077 URLRequest r( 6078 test_server_.GetURLWithUserAndPassword("/LICENSE", 6079 "chrome", 6080 "wrong_password"), 6081 &d, 6082 &default_context_); 6083 r.Start(); 6084 EXPECT_TRUE(r.is_pending()); 6085 6086 base::RunLoop().Run(); 6087 6088 int64 file_size = 0; 6089 file_util::GetFileSize(app_path, &file_size); 6090 6091 EXPECT_FALSE(r.is_pending()); 6092 EXPECT_EQ(1, d.response_started_count()); 6093 EXPECT_FALSE(d.received_data_before_response()); 6094 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size)); 6095 } 6096} 6097 6098// Flaky, see http://crbug.com/25045. 6099TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) { 6100 ASSERT_TRUE(test_server_.Start()); 6101 6102 base::FilePath app_path; 6103 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 6104 app_path = app_path.AppendASCII("LICENSE"); 6105 TestDelegate d; 6106 { 6107 URLRequest r( 6108 test_server_.GetURLWithUserAndPassword("/LICENSE", 6109 "wrong_user", 6110 "chrome"), 6111 &d, 6112 &default_context_); 6113 r.Start(); 6114 EXPECT_TRUE(r.is_pending()); 6115 6116 base::RunLoop().Run(); 6117 6118 int64 file_size = 0; 6119 file_util::GetFileSize(app_path, &file_size); 6120 6121 EXPECT_FALSE(r.is_pending()); 6122 EXPECT_EQ(1, d.response_started_count()); 6123 EXPECT_FALSE(d.received_data_before_response()); 6124 EXPECT_EQ(d.bytes_received(), 0); 6125 } 6126} 6127 6128// Flaky, see http://crbug.com/25045. 6129TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) { 6130 ASSERT_TRUE(test_server_.Start()); 6131 6132 base::FilePath app_path; 6133 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 6134 app_path = app_path.AppendASCII("LICENSE"); 6135 TestDelegate d; 6136 // Set correct login credentials. The delegate will be asked for them when 6137 // the initial login with wrong credentials will fail. 6138 d.set_credentials(AuthCredentials(kChrome, kChrome)); 6139 { 6140 URLRequest r( 6141 test_server_.GetURLWithUserAndPassword("/LICENSE", 6142 "wrong_user", 6143 "chrome"), 6144 &d, 6145 &default_context_); 6146 r.Start(); 6147 EXPECT_TRUE(r.is_pending()); 6148 6149 base::RunLoop().Run(); 6150 6151 int64 file_size = 0; 6152 file_util::GetFileSize(app_path, &file_size); 6153 6154 EXPECT_FALSE(r.is_pending()); 6155 EXPECT_EQ(1, d.response_started_count()); 6156 EXPECT_FALSE(d.received_data_before_response()); 6157 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size)); 6158 } 6159} 6160 6161// Flaky, see http://crbug.com/25045. 6162TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) { 6163 ASSERT_TRUE(test_server_.Start()); 6164 6165 base::FilePath app_path; 6166 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 6167 app_path = app_path.AppendASCII("LICENSE"); 6168 6169 scoped_ptr<TestDelegate> d(new TestDelegate); 6170 { 6171 // Pass correct login identity in the URL. 6172 URLRequest r( 6173 test_server_.GetURLWithUserAndPassword("/LICENSE", 6174 "chrome", 6175 "chrome"), 6176 d.get(), 6177 &default_context_); 6178 r.Start(); 6179 EXPECT_TRUE(r.is_pending()); 6180 6181 base::RunLoop().Run(); 6182 6183 int64 file_size = 0; 6184 file_util::GetFileSize(app_path, &file_size); 6185 6186 EXPECT_FALSE(r.is_pending()); 6187 EXPECT_EQ(1, d->response_started_count()); 6188 EXPECT_FALSE(d->received_data_before_response()); 6189 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size)); 6190 } 6191 6192 d.reset(new TestDelegate); 6193 { 6194 // This request should use cached identity from previous request. 6195 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_); 6196 r.Start(); 6197 EXPECT_TRUE(r.is_pending()); 6198 6199 base::RunLoop().Run(); 6200 6201 int64 file_size = 0; 6202 file_util::GetFileSize(app_path, &file_size); 6203 6204 EXPECT_FALSE(r.is_pending()); 6205 EXPECT_EQ(1, d->response_started_count()); 6206 EXPECT_FALSE(d->received_data_before_response()); 6207 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size)); 6208 } 6209} 6210 6211// Flaky, see http://crbug.com/25045. 6212TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) { 6213 ASSERT_TRUE(test_server_.Start()); 6214 6215 base::FilePath app_path; 6216 PathService::Get(base::DIR_SOURCE_ROOT, &app_path); 6217 app_path = app_path.AppendASCII("LICENSE"); 6218 6219 scoped_ptr<TestDelegate> d(new TestDelegate); 6220 // Set correct login credentials. The delegate will be asked for them when 6221 // the initial login with wrong credentials will fail. 6222 d->set_credentials(AuthCredentials(kChrome, kChrome)); 6223 { 6224 URLRequest r( 6225 test_server_.GetURLWithUserAndPassword("/LICENSE", 6226 "chrome", 6227 "wrong_password"), 6228 d.get(), 6229 &default_context_); 6230 r.Start(); 6231 EXPECT_TRUE(r.is_pending()); 6232 6233 base::RunLoop().Run(); 6234 6235 int64 file_size = 0; 6236 file_util::GetFileSize(app_path, &file_size); 6237 6238 EXPECT_FALSE(r.is_pending()); 6239 EXPECT_EQ(1, d->response_started_count()); 6240 EXPECT_FALSE(d->received_data_before_response()); 6241 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size)); 6242 } 6243 6244 // Use a new delegate without explicit credentials. The cached ones should be 6245 // used. 6246 d.reset(new TestDelegate); 6247 { 6248 // Don't pass wrong credentials in the URL, they would override valid cached 6249 // ones. 6250 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_); 6251 r.Start(); 6252 EXPECT_TRUE(r.is_pending()); 6253 6254 base::RunLoop().Run(); 6255 6256 int64 file_size = 0; 6257 file_util::GetFileSize(app_path, &file_size); 6258 6259 EXPECT_FALSE(r.is_pending()); 6260 EXPECT_EQ(1, d->response_started_count()); 6261 EXPECT_FALSE(d->received_data_before_response()); 6262 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size)); 6263 } 6264} 6265#endif // !defined(DISABLE_FTP_SUPPORT) 6266 6267} // namespace net 6268