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