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