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