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