blob: 269e86c99929a0d1de60832673b08a6768088814 [file] [log] [blame]
[email protected]9045b8822012-01-13 20:35:351// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
[email protected]ea224582008-12-07 20:25:465#include "build/build_config.h"
6
[email protected]9396b252008-09-29 17:29:387#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:068#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:069#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3810#endif
11
initial.commit586acc5fe2008-07-26 22:42:5212#include <algorithm>
13#include <string>
14
[email protected]aad63572011-05-24 20:14:3915#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3816#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5817#include "base/compiler_specific.h"
[email protected]399b8702009-05-01 20:34:0218#include "base/file_util.h"
[email protected]34b2b002009-11-20 06:53:2819#include "base/format_macros.h"
[email protected]084262c2011-12-01 21:12:4720#include "base/memory/weak_ptr.h"
initial.commit586acc5fe2008-07-26 22:42:5221#include "base/message_loop.h"
22#include "base/path_service.h"
23#include "base/process_util.h"
[email protected]528c56d2010-07-30 19:28:4424#include "base/string_number_conversions.h"
[email protected]d8eb84242010-09-25 02:25:0625#include "base/string_piece.h"
[email protected]ebbad602011-01-21 23:30:4726#include "base/string_util.h"
[email protected]d8eb84242010-09-25 02:25:0627#include "base/stringprintf.h"
[email protected]d778e0422013-03-06 18:10:2228#include "base/strings/string_split.h"
[email protected]be1ce6a72010-08-03 14:35:2229#include "base/utf_string_conversions.h"
[email protected]58e32bb2013-01-21 18:23:2530#include "net/base/capturing_net_log.h"
[email protected]dffe8242012-03-20 15:14:2731#include "net/base/cert_test_util.h"
32#include "net/base/ev_root_ca_metadata.h"
initial.commit586acc5fe2008-07-26 22:42:5233#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2534#include "net/base/load_timing_info.h"
35#include "net/base/load_timing_info_test_util.h"
[email protected]8202d0c2011-02-23 08:31:1436#include "net/base/mock_host_resolver.h"
[email protected]d8eb84242010-09-25 02:25:0637#include "net/base/net_errors.h"
[email protected]9e743cd2010-03-16 07:03:5338#include "net/base/net_log.h"
39#include "net/base/net_log_unittest.h"
initial.commit586acc5fe2008-07-26 22:42:5240#include "net/base/net_module.h"
41#include "net/base/net_util.h"
[email protected]42fdb452012-11-01 12:44:4042#include "net/base/test_data_directory.h"
[email protected]dffe8242012-03-20 15:14:2743#include "net/base/test_root_certs.h"
[email protected]f288ef02012-12-15 20:28:2844#include "net/base/upload_bytes_element_reader.h"
45#include "net/base/upload_data_stream.h"
46#include "net/base/upload_file_element_reader.h"
[email protected]aa84a7e2012-03-15 21:29:0647#include "net/cookies/cookie_monster.h"
48#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5249#include "net/disk_cache/disk_cache.h"
[email protected]ba2f3342009-07-30 18:08:4250#include "net/ftp/ftp_network_layer.h"
initial.commit586acc5fe2008-07-26 22:42:5251#include "net/http/http_cache.h"
52#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1953#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2554#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2155#include "net/http/http_response_headers.h"
[email protected]dffe8242012-03-20 15:14:2756#include "net/ocsp/nss_ocsp.h"
[email protected]63de95b2008-12-10 04:11:2757#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1958#include "net/socket/ssl_client_socket.h"
[email protected]536fd0b2013-03-14 17:41:5759#include "net/ssl/ssl_connection_status_flags.h"
[email protected]1b9565c2010-07-21 01:19:3160#include "net/test/test_server.h"
[email protected]d2a133182012-08-05 16:44:0861#include "net/url_request/ftp_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4362#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5263#include "net/url_request/url_request.h"
[email protected]7886a8c2009-08-21 04:11:0964#include "net/url_request/url_request_file_dir_job.h"
[email protected]bcb84f8b2009-08-31 16:20:1465#include "net/url_request/url_request_http_job.h"
[email protected]9d5730b2012-08-24 17:42:4966#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5167#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4768#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4469#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5270#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1571#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5272
[email protected]dffe8242012-03-20 15:14:2773#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:4874#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:2775#include "base/win/windows_version.h"
76#endif
77
[email protected]e1acf6f2008-10-27 20:43:3378using base::Time;
79
[email protected]7461a402011-03-24 23:19:5180namespace net {
81
initial.commit586acc5fe2008-07-26 22:42:5282namespace {
83
[email protected]13c8a092010-07-29 06:15:4484const string16 kChrome(ASCIIToUTF16("chrome"));
85const string16 kSecret(ASCIIToUTF16("secret"));
86const string16 kUser(ASCIIToUTF16("user"));
87
[email protected]58e32bb2013-01-21 18:23:2588// Tests load timing information in the case a fresh connection was used.
89// These tests use the TestServer, which doesn't support keep-alive sockets,
90// so there are no tests here that reuse sockets.
91void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
92 int connect_timing_flags) {
93 EXPECT_FALSE(load_timing_info.socket_reused);
94 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
95
96 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
97 EXPECT_FALSE(load_timing_info.request_start.is_null());
98
99 EXPECT_LE(load_timing_info.request_start,
100 load_timing_info.connect_timing.connect_start);
101 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
102 connect_timing_flags);
103 EXPECT_LE(load_timing_info.connect_timing.connect_end,
104 load_timing_info.send_start);
105 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
106 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
107
108 // Not set by these tests.
109 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
110 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
111}
112
113// Tests load timing in the case that there is no underlying connection. This
114// can be used to test in the case of cached responses, errors, or non-HTTP
115// requests.
116void TestLoadTimingNoHttpConnection(
117 const net::LoadTimingInfo& load_timing_info) {
118 EXPECT_FALSE(load_timing_info.socket_reused);
119 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
120
121 // Only the request times should be non-null.
122 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
123 EXPECT_FALSE(load_timing_info.request_start.is_null());
124
125 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
126
127 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
128 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
129 EXPECT_TRUE(load_timing_info.send_start.is_null());
130 EXPECT_TRUE(load_timing_info.send_end.is_null());
131 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
132}
133
[email protected]8a16266e2009-09-10 21:08:39134base::StringPiece TestNetResourceProvider(int key) {
initial.commit586acc5fe2008-07-26 22:42:52135 return "header";
136}
137
[email protected]71c64f62008-11-15 04:36:51138// Do a case-insensitive search through |haystack| for |needle|.
139bool ContainsString(const std::string& haystack, const char* needle) {
140 std::string::const_iterator it =
141 std::search(haystack.begin(),
142 haystack.end(),
143 needle,
144 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35145 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51146 return it != haystack.end();
147}
148
[email protected]661376a2009-04-29 02:04:23149void FillBuffer(char* buffer, size_t len) {
150 static bool called = false;
151 if (!called) {
152 called = true;
153 int seed = static_cast<int>(Time::Now().ToInternalValue());
154 srand(seed);
155 }
156
157 for (size_t i = 0; i < len; i++) {
158 buffer[i] = static_cast<char>(rand());
159 if (!buffer[i])
160 buffer[i] = 'g';
161 }
162}
163
[email protected]f288ef02012-12-15 20:28:28164UploadDataStream* CreateSimpleUploadData(const char* data) {
165 scoped_ptr<UploadElementReader> reader(
166 new UploadBytesElementReader(data, strlen(data)));
167 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23168}
169
[email protected]96adadb2010-08-28 01:16:17170// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51171void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]89af3d92010-10-15 20:31:37172 // Allow ChromeFrame fake SSLInfo to get through.
[email protected]c679be22010-08-29 15:20:05173 if (ssl_info.cert.get() &&
[email protected]89af3d92010-10-15 20:31:37174 ssl_info.cert.get()->issuer().GetDisplayName() == "Chrome Internal") {
175 // -1 means unknown.
176 EXPECT_EQ(ssl_info.security_bits, -1);
[email protected]c679be22010-08-29 15:20:05177 return;
[email protected]89af3d92010-10-15 20:31:37178 }
179
[email protected]96adadb2010-08-28 01:16:17180 // -1 means unknown. 0 means no encryption.
181 EXPECT_GT(ssl_info.security_bits, 0);
182
183 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
[email protected]7461a402011-03-24 23:19:51184 int cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17185 ssl_info.connection_status);
186 EXPECT_NE(0, cipher_suite);
187}
188
[email protected]ede03212012-09-07 12:52:26189bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27190 size_t size = a.size();
191
192 if (size != b.size())
193 return false;
194
195 for (size_t i = 0; i < size; ++i) {
196 if (!a[i].Equals(b[i]))
197 return false;
198 }
199
200 return true;
201}
202
[email protected]dc5a5cf2012-09-26 02:49:30203// A network delegate that allows the user to choose a subset of request stages
204// to block in. When blocking, the delegate can do one of the following:
205// * synchronously return a pre-specified error code, or
206// * asynchronously return that value via an automatically called callback,
207// or
208// * block and wait for the user to do a callback.
209// Additionally, the user may also specify a redirect URL -- then each request
210// with the current URL different from the redirect target will be redirected
211// to that target, in the on-before-URL-request stage, independent of whether
212// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12213class BlockingNetworkDelegate : public TestNetworkDelegate {
214 public:
[email protected]dc5a5cf2012-09-26 02:49:30215 // Stages in which the delegate can block.
216 enum Stage {
[email protected]9045b8822012-01-13 20:35:35217 NOT_BLOCKED = 0,
218 ON_BEFORE_URL_REQUEST = 1 << 0,
219 ON_BEFORE_SEND_HEADERS = 1 << 1,
220 ON_HEADERS_RECEIVED = 1 << 2,
221 ON_AUTH_REQUIRED = 1 << 3
222 };
223
[email protected]dc5a5cf2012-09-26 02:49:30224 // Behavior during blocked stages. During other stages, just
225 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
226 enum BlockMode {
227 SYNCHRONOUS, // No callback, returns specified return values.
228 AUTO_CALLBACK, // |this| posts a task to run the callback using the
229 // specified return codes.
230 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
231 // |auth_retval_| are ignored. In every blocking stage the
232 // message loop is quit.
233 };
234
235 // Creates a delegate which does not block at all.
236 explicit BlockingNetworkDelegate(BlockMode block_mode);
237
238 // For users to trigger a callback returning |response|.
239 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
240 // Only call if |block_mode_| == USER_CALLBACK.
241 void DoCallback(int response);
242 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
243
244 // Setters.
245 void set_retval(int retval) {
246 ASSERT_NE(USER_CALLBACK, block_mode_);
247 ASSERT_NE(ERR_IO_PENDING, retval);
248 ASSERT_NE(OK, retval);
249 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35250 }
251
[email protected]dc5a5cf2012-09-26 02:49:30252 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
253 // |auth_credentials_| will be passed with the response.
254 void set_auth_retval(AuthRequiredResponse auth_retval) {
255 ASSERT_NE(USER_CALLBACK, block_mode_);
256 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
257 auth_retval_ = auth_retval;
258 }
259 void set_auth_credentials(const AuthCredentials& auth_credentials) {
260 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35261 }
262
[email protected]dc5a5cf2012-09-26 02:49:30263 void set_redirect_url(const GURL& url) {
264 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35265 }
266
[email protected]dc5a5cf2012-09-26 02:49:30267 void set_block_on(int block_on) {
268 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35269 }
270
[email protected]dc5a5cf2012-09-26 02:49:30271 // Allows the user to check in which state did we block.
272 Stage stage_blocked_for_callback() const {
273 EXPECT_EQ(USER_CALLBACK, block_mode_);
274 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35275 }
276
277 private:
[email protected]dc5a5cf2012-09-26 02:49:30278 void RunCallback(int response, const CompletionCallback& callback);
279 void RunAuthCallback(AuthRequiredResponse response,
280 const AuthCallback& callback);
281
[email protected]9045b8822012-01-13 20:35:35282 // TestNetworkDelegate implementation.
283 virtual int OnBeforeURLRequest(URLRequest* request,
284 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30285 GURL* new_url) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35286
287 virtual int OnBeforeSendHeaders(URLRequest* request,
288 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30289 HttpRequestHeaders* headers) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35290
291 virtual int OnHeadersReceived(
292 URLRequest* request,
293 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32294 const HttpResponseHeaders* original_response_headers,
[email protected]dc5a5cf2012-09-26 02:49:30295 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35296
297 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
298 URLRequest* request,
299 const AuthChallengeInfo& auth_info,
300 const AuthCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30301 AuthCredentials* credentials) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35302
[email protected]dc5a5cf2012-09-26 02:49:30303 // Resets the callbacks and |stage_blocked_for_callback_|.
304 void Reset();
[email protected]9045b8822012-01-13 20:35:35305
[email protected]dc5a5cf2012-09-26 02:49:30306 // Checks whether we should block in |stage|. If yes, returns an error code
307 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
308 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
309
310 // Configuration parameters, can be adjusted by public methods:
311 const BlockMode block_mode_;
312
313 // Values returned on blocking stages when mode is SYNCHRONOUS or
314 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
315 int retval_; // To be returned in non-auth stages.
316 AuthRequiredResponse auth_retval_;
317
318 GURL redirect_url_; // Used if non-empty.
319 int block_on_; // Bit mask: in which stages to block.
320
321 // |auth_credentials_| will be copied to |*target_auth_credential_| on
322 // callback.
323 AuthCredentials auth_credentials_;
324 AuthCredentials* target_auth_credentials_;
325
326 // Internal variables, not set by not the user:
327 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
328 // USER_CALLBACK).
329 Stage stage_blocked_for_callback_;
330
331 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35332 CompletionCallback callback_;
333 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30334
335 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
336
337 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35338};
339
[email protected]dc5a5cf2012-09-26 02:49:30340BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
341 : block_mode_(block_mode),
342 retval_(OK),
343 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
344 block_on_(0),
345 target_auth_credentials_(NULL),
346 stage_blocked_for_callback_(NOT_BLOCKED),
347 ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
348}
349
350void BlockingNetworkDelegate::DoCallback(int response) {
351 ASSERT_EQ(USER_CALLBACK, block_mode_);
352 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
353 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
354 CompletionCallback callback = callback_;
355 Reset();
356 RunCallback(response, callback);
357}
358
359void BlockingNetworkDelegate::DoAuthCallback(
360 NetworkDelegate::AuthRequiredResponse response) {
361 ASSERT_EQ(USER_CALLBACK, block_mode_);
362 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
363 AuthCallback auth_callback = auth_callback_;
364 Reset();
365 RunAuthCallback(response, auth_callback);
366}
367
368void BlockingNetworkDelegate::RunCallback(int response,
369 const CompletionCallback& callback) {
370 callback.Run(response);
371}
372
373void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
374 const AuthCallback& callback) {
375 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
376 ASSERT_TRUE(target_auth_credentials_ != NULL);
377 *target_auth_credentials_ = auth_credentials_;
378 }
379 callback.Run(response);
380}
381
382int BlockingNetworkDelegate::OnBeforeURLRequest(
383 URLRequest* request,
384 const CompletionCallback& callback,
385 GURL* new_url) {
386 if (redirect_url_ == request->url())
387 return OK; // We've already seen this request and redirected elsewhere.
388
389 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
390
391 if (!redirect_url_.is_empty())
392 *new_url = redirect_url_;
393
394 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
395}
396
397int BlockingNetworkDelegate::OnBeforeSendHeaders(
398 URLRequest* request,
399 const CompletionCallback& callback,
400 HttpRequestHeaders* headers) {
401 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
402
403 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
404}
405
406int BlockingNetworkDelegate::OnHeadersReceived(
407 URLRequest* request,
408 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32409 const HttpResponseHeaders* original_response_headers,
[email protected]dc5a5cf2012-09-26 02:49:30410 scoped_refptr<HttpResponseHeaders>* override_response_headers) {
411 TestNetworkDelegate::OnHeadersReceived(
412 request, callback, original_response_headers,
413 override_response_headers);
414
415 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
416}
417
418NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
419 URLRequest* request,
420 const AuthChallengeInfo& auth_info,
421 const AuthCallback& callback,
422 AuthCredentials* credentials) {
423 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
424 credentials);
425 // Check that the user has provided callback for the previous blocked stage.
426 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
427
428 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
429 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
430 }
431
432 target_auth_credentials_ = credentials;
433
434 switch (block_mode_) {
435 case SYNCHRONOUS:
436 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
437 *target_auth_credentials_ = auth_credentials_;
438 return auth_retval_;
439
440 case AUTO_CALLBACK:
441 MessageLoop::current()->PostTask(
442 FROM_HERE,
443 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
444 weak_factory_.GetWeakPtr(), auth_retval_, callback));
445 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
446
447 case USER_CALLBACK:
448 auth_callback_ = callback;
449 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
450 MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
451 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
452 }
453 NOTREACHED();
454 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
455}
456
457void BlockingNetworkDelegate::Reset() {
458 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
459 stage_blocked_for_callback_ = NOT_BLOCKED;
460 callback_.Reset();
461 auth_callback_.Reset();
462}
463
464int BlockingNetworkDelegate::MaybeBlockStage(
465 BlockingNetworkDelegate::Stage stage,
466 const CompletionCallback& callback) {
467 // Check that the user has provided callback for the previous blocked stage.
468 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
469
470 if ((block_on_ & stage) == 0) {
471 return OK;
472 }
473
474 switch (block_mode_) {
475 case SYNCHRONOUS:
476 EXPECT_NE(OK, retval_);
477 return retval_;
478
479 case AUTO_CALLBACK:
480 MessageLoop::current()->PostTask(
481 FROM_HERE,
482 base::Bind(&BlockingNetworkDelegate::RunCallback,
483 weak_factory_.GetWeakPtr(), retval_, callback));
484 return ERR_IO_PENDING;
485
486 case USER_CALLBACK:
487 callback_ = callback;
488 stage_blocked_for_callback_ = stage;
489 MessageLoop::current()->PostTask(FROM_HERE, MessageLoop::QuitClosure());
490 return ERR_IO_PENDING;
491 }
492 NOTREACHED();
493 return 0;
494}
495
[email protected]d5a4dd62012-05-23 01:41:04496class TestURLRequestContextWithProxy : public TestURLRequestContext {
497 public:
498 // Does not own |delegate|.
499 TestURLRequestContextWithProxy(const std::string& proxy,
500 NetworkDelegate* delegate)
501 : TestURLRequestContext(true) {
502 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
503 set_network_delegate(delegate);
504 Init();
505 }
506 virtual ~TestURLRequestContextWithProxy() {}
507};
508
509} // namespace
510
[email protected]a592c0432012-12-01 18:10:29511// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48512class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00513 public:
[email protected]ef2bf422012-05-11 03:27:09514 URLRequestTest() : default_context_(true) {
515 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25516 default_context_.set_net_log(&net_log_);
[email protected]ef2bf422012-05-11 03:27:09517 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:50518 }
[email protected]f53b4802012-12-20 17:04:23519 virtual ~URLRequestTest() {}
[email protected]87a09a92011-07-14 15:50:50520
[email protected]3c5ca8c2011-09-29 01:14:51521 // Adds the TestJobInterceptor to the default context.
522 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23523 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
524 job_factory_.reset(new URLRequestJobFactoryImpl);
525 job_factory_->SetProtocolHandler("http", protocol_handler_);
526 default_context_.set_job_factory(job_factory_.get());
527 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51528 }
529
[email protected]87a09a92011-07-14 15:50:50530 protected:
[email protected]58e32bb2013-01-21 18:23:25531 CapturingNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24532 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]f53b4802012-12-20 17:04:23533 scoped_ptr<URLRequestJobFactoryImpl> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09534 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48535};
536
[email protected]316c1e5e2012-09-12 15:17:44537TEST_F(URLRequestTest, AboutBlankTest) {
538 TestDelegate d;
539 {
540 URLRequest r(GURL("about:blank"), &d, &default_context_);
541
542 r.Start();
543 EXPECT_TRUE(r.is_pending());
544
545 MessageLoop::current()->Run();
546
547 EXPECT_TRUE(!r.is_pending());
548 EXPECT_FALSE(d.received_data_before_response());
549 EXPECT_EQ(d.bytes_received(), 0);
550 EXPECT_EQ("", r.GetSocketAddress().host());
551 EXPECT_EQ(0, r.GetSocketAddress().port());
552 }
553}
554
555TEST_F(URLRequestTest, DataURLImageTest) {
556 TestDelegate d;
557 {
558 // Use our nice little Chrome logo.
559 URLRequest r(GURL(
560 "data:image/png;base64,"
561 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
562 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
563 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
564 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
565 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
566 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
567 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
568 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
569 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
570 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
571 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
572 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
573 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
574 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
575 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
576 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
577 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
578 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
579 &d,
580 &default_context_);
581
582 r.Start();
583 EXPECT_TRUE(r.is_pending());
584
585 MessageLoop::current()->Run();
586
587 EXPECT_TRUE(!r.is_pending());
588 EXPECT_FALSE(d.received_data_before_response());
589 EXPECT_EQ(d.bytes_received(), 911);
590 EXPECT_EQ("", r.GetSocketAddress().host());
591 EXPECT_EQ(0, r.GetSocketAddress().port());
592 }
593}
594
595TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15596 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44597 PathService::Get(base::FILE_EXE, &app_path);
598 GURL app_url = FilePathToFileURL(app_path);
599
600 TestDelegate d;
601 {
602 URLRequest r(app_url, &d, &default_context_);
603
604 r.Start();
605 EXPECT_TRUE(r.is_pending());
606
607 MessageLoop::current()->Run();
608
609 int64 file_size = -1;
610 EXPECT_TRUE(file_util::GetFileSize(app_path, &file_size));
611
612 EXPECT_TRUE(!r.is_pending());
613 EXPECT_EQ(1, d.response_started_count());
614 EXPECT_FALSE(d.received_data_before_response());
615 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
616 EXPECT_EQ("", r.GetSocketAddress().host());
617 EXPECT_EQ(0, r.GetSocketAddress().port());
618 }
619}
620
[email protected]ba40bb762012-12-17 07:11:04621TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15622 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04623 PathService::Get(base::FILE_EXE, &app_path);
624 GURL app_url = FilePathToFileURL(app_path);
625
626 TestDelegate d;
627 {
628 URLRequest r(app_url, &d, &default_context_);
629
630 r.Start();
631 EXPECT_TRUE(r.is_pending());
632 r.Cancel();
633 }
634 // Async cancelation should be safe even when URLRequest has been already
635 // destroyed.
636 MessageLoop::current()->RunUntilIdle();
637}
638
[email protected]316c1e5e2012-09-12 15:17:44639TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
640 const size_t buffer_size = 4000;
641 scoped_array<char> buffer(new char[buffer_size]);
642 FillBuffer(buffer.get(), buffer_size);
643
[email protected]6cdfd7f2013-02-08 20:40:15644 base::FilePath temp_path;
[email protected]316c1e5e2012-09-12 15:17:44645 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path));
646 GURL temp_url = FilePathToFileURL(temp_path);
647 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
648
649 int64 file_size;
650 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size));
651
652 const size_t first_byte_position = 500;
653 const size_t last_byte_position = buffer_size - first_byte_position;
654 const size_t content_length = last_byte_position - first_byte_position + 1;
655 std::string partial_buffer_string(buffer.get() + first_byte_position,
656 buffer.get() + last_byte_position + 1);
657
658 TestDelegate d;
659 {
660 URLRequest r(temp_url, &d, &default_context_);
661
662 HttpRequestHeaders headers;
663 headers.SetHeader(HttpRequestHeaders::kRange,
664 base::StringPrintf(
665 "bytes=%" PRIuS "-%" PRIuS,
666 first_byte_position, last_byte_position));
667 r.SetExtraRequestHeaders(headers);
668 r.Start();
669 EXPECT_TRUE(r.is_pending());
670
671 MessageLoop::current()->Run();
672 EXPECT_TRUE(!r.is_pending());
673 EXPECT_EQ(1, d.response_started_count());
674 EXPECT_FALSE(d.received_data_before_response());
675 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
676 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
677 EXPECT_TRUE(partial_buffer_string == d.data_received());
678 }
679
680 EXPECT_TRUE(file_util::Delete(temp_path, false));
681}
682
683TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
684 const size_t buffer_size = 4000;
685 scoped_array<char> buffer(new char[buffer_size]);
686 FillBuffer(buffer.get(), buffer_size);
687
[email protected]6cdfd7f2013-02-08 20:40:15688 base::FilePath temp_path;
[email protected]316c1e5e2012-09-12 15:17:44689 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path));
690 GURL temp_url = FilePathToFileURL(temp_path);
691 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
692
693 int64 file_size;
694 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size));
695
696 const size_t first_byte_position = 500;
697 const size_t last_byte_position = buffer_size - 1;
698 const size_t content_length = last_byte_position - first_byte_position + 1;
699 std::string partial_buffer_string(buffer.get() + first_byte_position,
700 buffer.get() + last_byte_position + 1);
701
702 TestDelegate d;
703 {
704 URLRequest r(temp_url, &d, &default_context_);
705
706 HttpRequestHeaders headers;
707 headers.SetHeader(HttpRequestHeaders::kRange,
708 base::StringPrintf("bytes=%" PRIuS "-",
709 first_byte_position));
710 r.SetExtraRequestHeaders(headers);
711 r.Start();
712 EXPECT_TRUE(r.is_pending());
713
714 MessageLoop::current()->Run();
715 EXPECT_TRUE(!r.is_pending());
716 EXPECT_EQ(1, d.response_started_count());
717 EXPECT_FALSE(d.received_data_before_response());
718 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
719 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
720 EXPECT_TRUE(partial_buffer_string == d.data_received());
721 }
722
723 EXPECT_TRUE(file_util::Delete(temp_path, false));
724}
725
726TEST_F(URLRequestTest, FileTestMultipleRanges) {
727 const size_t buffer_size = 400000;
728 scoped_array<char> buffer(new char[buffer_size]);
729 FillBuffer(buffer.get(), buffer_size);
730
[email protected]6cdfd7f2013-02-08 20:40:15731 base::FilePath temp_path;
[email protected]316c1e5e2012-09-12 15:17:44732 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path));
733 GURL temp_url = FilePathToFileURL(temp_path);
734 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
735
736 int64 file_size;
737 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size));
738
739 TestDelegate d;
740 {
741 URLRequest r(temp_url, &d, &default_context_);
742
743 HttpRequestHeaders headers;
744 headers.SetHeader(HttpRequestHeaders::kRange,
745 "bytes=0-0,10-200,200-300");
746 r.SetExtraRequestHeaders(headers);
747 r.Start();
748 EXPECT_TRUE(r.is_pending());
749
750 MessageLoop::current()->Run();
751 EXPECT_TRUE(d.request_failed());
752 }
753
754 EXPECT_TRUE(file_util::Delete(temp_path, false));
755}
756
757TEST_F(URLRequestTest, InvalidUrlTest) {
758 TestDelegate d;
759 {
760 URLRequest r(GURL("invalid url"), &d, &default_context_);
761
762 r.Start();
763 EXPECT_TRUE(r.is_pending());
764
765 MessageLoop::current()->Run();
766 EXPECT_TRUE(d.request_failed());
767 }
768}
769
770#if defined(OS_WIN)
771TEST_F(URLRequestTest, ResolveShortcutTest) {
[email protected]6cdfd7f2013-02-08 20:40:15772 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44773 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
774 app_path = app_path.AppendASCII("net");
775 app_path = app_path.AppendASCII("data");
776 app_path = app_path.AppendASCII("url_request_unittest");
777 app_path = app_path.AppendASCII("with-headers.html");
778
779 std::wstring lnk_path = app_path.value() + L".lnk";
780
[email protected]451fd902012-10-03 17:14:48781 base::win::ScopedCOMInitializer com_initializer;
[email protected]00d60fa2012-10-01 18:20:17782
[email protected]316c1e5e2012-09-12 15:17:44783 // Temporarily create a shortcut for test
[email protected]00d60fa2012-10-01 18:20:17784 IShellLink* shell = NULL;
785 ASSERT_TRUE(SUCCEEDED(CoCreateInstance(
786 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink,
787 reinterpret_cast<LPVOID*>(&shell))));
788 IPersistFile* persist = NULL;
789 ASSERT_TRUE(SUCCEEDED(shell->QueryInterface(
790 IID_IPersistFile, reinterpret_cast<LPVOID*>(&persist))));
791 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
792 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
793 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
[email protected]316c1e5e2012-09-12 15:17:44794 if (persist)
795 persist->Release();
796 if (shell)
797 shell->Release();
798
799 TestDelegate d;
800 {
[email protected]6cdfd7f2013-02-08 20:40:15801 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)), &d,
802 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44803
804 r.Start();
805 EXPECT_TRUE(r.is_pending());
806
807 MessageLoop::current()->Run();
808
809 WIN32_FILE_ATTRIBUTE_DATA data;
810 GetFileAttributesEx(app_path.value().c_str(),
811 GetFileExInfoStandard, &data);
812 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
813 FILE_SHARE_READ, NULL, OPEN_EXISTING,
814 FILE_ATTRIBUTE_NORMAL, NULL);
815 EXPECT_NE(INVALID_HANDLE_VALUE, file);
816 scoped_array<char> buffer(new char[data.nFileSizeLow]);
817 DWORD read_size;
818 BOOL result;
819 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
820 &read_size, NULL);
821 std::string content(buffer.get(), read_size);
822 CloseHandle(file);
823
824 EXPECT_TRUE(!r.is_pending());
825 EXPECT_EQ(1, d.received_redirect_count());
826 EXPECT_EQ(content, d.data_received());
827 }
828
829 // Clean the shortcut
830 DeleteFile(lnk_path.c_str());
[email protected]316c1e5e2012-09-12 15:17:44831}
832#endif // defined(OS_WIN)
833
834TEST_F(URLRequestTest, FileDirCancelTest) {
835 // Put in mock resource provider.
836 NetModule::SetResourceProvider(TestNetResourceProvider);
837
838 TestDelegate d;
839 {
[email protected]6cdfd7f2013-02-08 20:40:15840 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44841 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
842 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
843 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
844
845 URLRequest req(FilePathToFileURL(file_path), &d, &default_context_);
846 req.Start();
847 EXPECT_TRUE(req.is_pending());
848
849 d.set_cancel_in_received_data_pending(true);
850
851 MessageLoop::current()->Run();
852 }
853
854 // Take out mock resource provider.
855 NetModule::SetResourceProvider(NULL);
856}
857
858TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
859 // There is an implicit redirect when loading a file path that matches a
860 // directory and does not end with a slash. Ensure that following such
861 // redirects does not crash. See http://crbug.com/18686.
862
[email protected]6cdfd7f2013-02-08 20:40:15863 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:44864 PathService::Get(base::DIR_SOURCE_ROOT, &path);
865 path = path.Append(FILE_PATH_LITERAL("net"));
866 path = path.Append(FILE_PATH_LITERAL("data"));
867 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
868
869 TestDelegate d;
870 URLRequest req(FilePathToFileURL(path), &d, &default_context_);
871 req.Start();
872 MessageLoop::current()->Run();
873
874 ASSERT_EQ(1, d.received_redirect_count());
875 ASSERT_LT(0, d.bytes_received());
876 ASSERT_FALSE(d.request_failed());
877 ASSERT_TRUE(req.status().is_success());
878}
879
880#if defined(OS_WIN)
881// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
882TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
883 TestDelegate d;
884 URLRequest req(GURL("file:///"), &d, &default_context_);
885 req.Start();
886 MessageLoop::current()->Run();
887
888 ASSERT_EQ(1, d.received_redirect_count());
889 ASSERT_FALSE(req.status().is_success());
890}
891#endif
892
893// Custom URLRequestJobs for use with interceptor tests
894class RestartTestJob : public URLRequestTestJob {
895 public:
896 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
897 : URLRequestTestJob(request, network_delegate, true) {}
898 protected:
[email protected]46fadfd2013-02-06 09:40:16899 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:44900 this->NotifyRestartRequired();
901 }
902 private:
[email protected]46fadfd2013-02-06 09:40:16903 virtual ~RestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:44904};
905
906class CancelTestJob : public URLRequestTestJob {
907 public:
908 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
909 : URLRequestTestJob(request, network_delegate, true) {}
910 protected:
[email protected]46fadfd2013-02-06 09:40:16911 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:44912 request_->Cancel();
913 }
914 private:
[email protected]46fadfd2013-02-06 09:40:16915 virtual ~CancelTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:44916};
917
918class CancelThenRestartTestJob : public URLRequestTestJob {
919 public:
920 explicit CancelThenRestartTestJob(URLRequest* request,
921 NetworkDelegate* network_delegate)
922 : URLRequestTestJob(request, network_delegate, true) {
923 }
924 protected:
[email protected]46fadfd2013-02-06 09:40:16925 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:44926 request_->Cancel();
927 this->NotifyRestartRequired();
928 }
929 private:
[email protected]46fadfd2013-02-06 09:40:16930 virtual ~CancelThenRestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:44931};
932
933// An Interceptor for use with interceptor tests
934class TestInterceptor : URLRequest::Interceptor {
935 public:
936 TestInterceptor()
937 : intercept_main_request_(false), restart_main_request_(false),
938 cancel_main_request_(false), cancel_then_restart_main_request_(false),
939 simulate_main_network_error_(false),
940 intercept_redirect_(false), cancel_redirect_request_(false),
941 intercept_final_response_(false), cancel_final_request_(false),
942 did_intercept_main_(false), did_restart_main_(false),
943 did_cancel_main_(false), did_cancel_then_restart_main_(false),
944 did_simulate_error_main_(false),
945 did_intercept_redirect_(false), did_cancel_redirect_(false),
946 did_intercept_final_(false), did_cancel_final_(false) {
947 URLRequest::Deprecated::RegisterRequestInterceptor(this);
948 }
949
[email protected]46fadfd2013-02-06 09:40:16950 virtual ~TestInterceptor() {
[email protected]316c1e5e2012-09-12 15:17:44951 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
952 }
953
[email protected]46fadfd2013-02-06 09:40:16954 virtual URLRequestJob* MaybeIntercept(
955 URLRequest* request,
956 NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:44957 if (restart_main_request_) {
958 restart_main_request_ = false;
959 did_restart_main_ = true;
960 return new RestartTestJob(request, network_delegate);
961 }
962 if (cancel_main_request_) {
963 cancel_main_request_ = false;
964 did_cancel_main_ = true;
965 return new CancelTestJob(request, network_delegate);
966 }
967 if (cancel_then_restart_main_request_) {
968 cancel_then_restart_main_request_ = false;
969 did_cancel_then_restart_main_ = true;
970 return new CancelThenRestartTestJob(request, network_delegate);
971 }
972 if (simulate_main_network_error_) {
973 simulate_main_network_error_ = false;
974 did_simulate_error_main_ = true;
975 // will error since the requeted url is not one of its canned urls
976 return new URLRequestTestJob(request, network_delegate, true);
977 }
978 if (!intercept_main_request_)
979 return NULL;
980 intercept_main_request_ = false;
981 did_intercept_main_ = true;
982 return new URLRequestTestJob(request,
983 network_delegate,
984 main_headers_,
985 main_data_,
986 true);
987 }
988
989 virtual URLRequestJob* MaybeInterceptRedirect(
990 URLRequest* request,
991 NetworkDelegate* network_delegate,
[email protected]46fadfd2013-02-06 09:40:16992 const GURL& location) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:44993 if (cancel_redirect_request_) {
994 cancel_redirect_request_ = false;
995 did_cancel_redirect_ = true;
996 return new CancelTestJob(request, network_delegate);
997 }
998 if (!intercept_redirect_)
999 return NULL;
1000 intercept_redirect_ = false;
1001 did_intercept_redirect_ = true;
1002 return new URLRequestTestJob(request,
1003 network_delegate,
1004 redirect_headers_,
1005 redirect_data_,
1006 true);
1007 }
1008
1009 virtual URLRequestJob* MaybeInterceptResponse(
[email protected]46fadfd2013-02-06 09:40:161010 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441011 if (cancel_final_request_) {
1012 cancel_final_request_ = false;
1013 did_cancel_final_ = true;
1014 return new CancelTestJob(request, network_delegate);
1015 }
1016 if (!intercept_final_response_)
1017 return NULL;
1018 intercept_final_response_ = false;
1019 did_intercept_final_ = true;
1020 return new URLRequestTestJob(request,
1021 network_delegate,
1022 final_headers_,
1023 final_data_,
1024 true);
1025 }
1026
1027 // Whether to intercept the main request, and if so the response to return.
1028 bool intercept_main_request_;
1029 std::string main_headers_;
1030 std::string main_data_;
1031
1032 // Other actions we take at MaybeIntercept time
1033 bool restart_main_request_;
1034 bool cancel_main_request_;
1035 bool cancel_then_restart_main_request_;
1036 bool simulate_main_network_error_;
1037
1038 // Whether to intercept redirects, and if so the response to return.
1039 bool intercept_redirect_;
1040 std::string redirect_headers_;
1041 std::string redirect_data_;
1042
1043 // Other actions we can take at MaybeInterceptRedirect time
1044 bool cancel_redirect_request_;
1045
1046 // Whether to intercept final response, and if so the response to return.
1047 bool intercept_final_response_;
1048 std::string final_headers_;
1049 std::string final_data_;
1050
1051 // Other actions we can take at MaybeInterceptResponse time
1052 bool cancel_final_request_;
1053
1054 // If we did something or not
1055 bool did_intercept_main_;
1056 bool did_restart_main_;
1057 bool did_cancel_main_;
1058 bool did_cancel_then_restart_main_;
1059 bool did_simulate_error_main_;
1060 bool did_intercept_redirect_;
1061 bool did_cancel_redirect_;
1062 bool did_intercept_final_;
1063 bool did_cancel_final_;
1064
1065 // Static getters for canned response header and data strings
1066
1067 static std::string ok_data() {
1068 return URLRequestTestJob::test_data_1();
1069 }
1070
1071 static std::string ok_headers() {
1072 return URLRequestTestJob::test_headers();
1073 }
1074
1075 static std::string redirect_data() {
1076 return std::string();
1077 }
1078
1079 static std::string redirect_headers() {
1080 return URLRequestTestJob::test_redirect_headers();
1081 }
1082
1083 static std::string error_data() {
1084 return std::string("ohhh nooooo mr. bill!");
1085 }
1086
1087 static std::string error_headers() {
1088 return URLRequestTestJob::test_error_headers();
1089 }
1090};
1091
1092TEST_F(URLRequestTest, Intercept) {
1093 TestInterceptor interceptor;
1094
1095 // intercept the main request and respond with a simple response
1096 interceptor.intercept_main_request_ = true;
1097 interceptor.main_headers_ = TestInterceptor::ok_headers();
1098 interceptor.main_data_ = TestInterceptor::ok_data();
1099
1100 TestDelegate d;
1101 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1102 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1103 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1104 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1105 req.SetUserData(NULL, user_data0);
1106 req.SetUserData(&user_data1, user_data1);
1107 req.SetUserData(&user_data2, user_data2);
1108 req.set_method("GET");
1109 req.Start();
1110 MessageLoop::current()->Run();
1111
1112 // Make sure we can retrieve our specific user data
1113 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1114 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1115 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1116
1117 // Check the interceptor got called as expected
1118 EXPECT_TRUE(interceptor.did_intercept_main_);
1119
1120 // Check we got one good response
1121 EXPECT_TRUE(req.status().is_success());
1122 EXPECT_EQ(200, req.response_headers()->response_code());
1123 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1124 EXPECT_EQ(1, d.response_started_count());
1125 EXPECT_EQ(0, d.received_redirect_count());
1126}
1127
1128TEST_F(URLRequestTest, InterceptRedirect) {
1129 TestInterceptor interceptor;
1130
1131 // intercept the main request and respond with a redirect
1132 interceptor.intercept_main_request_ = true;
1133 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1134 interceptor.main_data_ = TestInterceptor::redirect_data();
1135
1136 // intercept that redirect and respond a final OK response
1137 interceptor.intercept_redirect_ = true;
1138 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1139 interceptor.redirect_data_ = TestInterceptor::ok_data();
1140
1141 TestDelegate d;
1142 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1143 req.set_method("GET");
1144 req.Start();
1145 MessageLoop::current()->Run();
1146
1147 // Check the interceptor got called as expected
1148 EXPECT_TRUE(interceptor.did_intercept_main_);
1149 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1150
1151 // Check we got one good response
1152 EXPECT_TRUE(req.status().is_success());
1153 if (req.status().is_success()) {
1154 EXPECT_EQ(200, req.response_headers()->response_code());
1155 }
1156 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1157 EXPECT_EQ(1, d.response_started_count());
1158 EXPECT_EQ(0, d.received_redirect_count());
1159}
1160
1161TEST_F(URLRequestTest, InterceptServerError) {
1162 TestInterceptor interceptor;
1163
1164 // intercept the main request to generate a server error response
1165 interceptor.intercept_main_request_ = true;
1166 interceptor.main_headers_ = TestInterceptor::error_headers();
1167 interceptor.main_data_ = TestInterceptor::error_data();
1168
1169 // intercept that error and respond with an OK response
1170 interceptor.intercept_final_response_ = true;
1171 interceptor.final_headers_ = TestInterceptor::ok_headers();
1172 interceptor.final_data_ = TestInterceptor::ok_data();
1173
1174 TestDelegate d;
1175 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1176 req.set_method("GET");
1177 req.Start();
1178 MessageLoop::current()->Run();
1179
1180 // Check the interceptor got called as expected
1181 EXPECT_TRUE(interceptor.did_intercept_main_);
1182 EXPECT_TRUE(interceptor.did_intercept_final_);
1183
1184 // Check we got one good response
1185 EXPECT_TRUE(req.status().is_success());
1186 EXPECT_EQ(200, req.response_headers()->response_code());
1187 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1188 EXPECT_EQ(1, d.response_started_count());
1189 EXPECT_EQ(0, d.received_redirect_count());
1190}
1191
1192TEST_F(URLRequestTest, InterceptNetworkError) {
1193 TestInterceptor interceptor;
1194
1195 // intercept the main request to simulate a network error
1196 interceptor.simulate_main_network_error_ = true;
1197
1198 // intercept that error and respond with an OK response
1199 interceptor.intercept_final_response_ = true;
1200 interceptor.final_headers_ = TestInterceptor::ok_headers();
1201 interceptor.final_data_ = TestInterceptor::ok_data();
1202
1203 TestDelegate d;
1204 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1205 req.set_method("GET");
1206 req.Start();
1207 MessageLoop::current()->Run();
1208
1209 // Check the interceptor got called as expected
1210 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1211 EXPECT_TRUE(interceptor.did_intercept_final_);
1212
1213 // Check we received one good response
1214 EXPECT_TRUE(req.status().is_success());
1215 EXPECT_EQ(200, req.response_headers()->response_code());
1216 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1217 EXPECT_EQ(1, d.response_started_count());
1218 EXPECT_EQ(0, d.received_redirect_count());
1219}
1220
1221TEST_F(URLRequestTest, InterceptRestartRequired) {
1222 TestInterceptor interceptor;
1223
1224 // restart the main request
1225 interceptor.restart_main_request_ = true;
1226
1227 // then intercept the new main request and respond with an OK response
1228 interceptor.intercept_main_request_ = true;
1229 interceptor.main_headers_ = TestInterceptor::ok_headers();
1230 interceptor.main_data_ = TestInterceptor::ok_data();
1231
1232 TestDelegate d;
1233 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1234 req.set_method("GET");
1235 req.Start();
1236 MessageLoop::current()->Run();
1237
1238 // Check the interceptor got called as expected
1239 EXPECT_TRUE(interceptor.did_restart_main_);
1240 EXPECT_TRUE(interceptor.did_intercept_main_);
1241
1242 // Check we received one good response
1243 EXPECT_TRUE(req.status().is_success());
1244 if (req.status().is_success()) {
1245 EXPECT_EQ(200, req.response_headers()->response_code());
1246 }
1247 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1248 EXPECT_EQ(1, d.response_started_count());
1249 EXPECT_EQ(0, d.received_redirect_count());
1250}
1251
1252TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1253 TestInterceptor interceptor;
1254
1255 // intercept the main request and cancel from within the restarted job
1256 interceptor.cancel_main_request_ = true;
1257
1258 // setup to intercept final response and override it with an OK response
1259 interceptor.intercept_final_response_ = true;
1260 interceptor.final_headers_ = TestInterceptor::ok_headers();
1261 interceptor.final_data_ = TestInterceptor::ok_data();
1262
1263 TestDelegate d;
1264 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1265 req.set_method("GET");
1266 req.Start();
1267 MessageLoop::current()->Run();
1268
1269 // Check the interceptor got called as expected
1270 EXPECT_TRUE(interceptor.did_cancel_main_);
1271 EXPECT_FALSE(interceptor.did_intercept_final_);
1272
1273 // Check we see a canceled request
1274 EXPECT_FALSE(req.status().is_success());
1275 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1276}
1277
1278TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1279 TestInterceptor interceptor;
1280
1281 // intercept the main request and respond with a redirect
1282 interceptor.intercept_main_request_ = true;
1283 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1284 interceptor.main_data_ = TestInterceptor::redirect_data();
1285
1286 // intercept the redirect and cancel from within that job
1287 interceptor.cancel_redirect_request_ = true;
1288
1289 // setup to intercept final response and override it with an OK response
1290 interceptor.intercept_final_response_ = true;
1291 interceptor.final_headers_ = TestInterceptor::ok_headers();
1292 interceptor.final_data_ = TestInterceptor::ok_data();
1293
1294 TestDelegate d;
1295 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1296 req.set_method("GET");
1297 req.Start();
1298 MessageLoop::current()->Run();
1299
1300 // Check the interceptor got called as expected
1301 EXPECT_TRUE(interceptor.did_intercept_main_);
1302 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1303 EXPECT_FALSE(interceptor.did_intercept_final_);
1304
1305 // Check we see a canceled request
1306 EXPECT_FALSE(req.status().is_success());
1307 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1308}
1309
1310TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1311 TestInterceptor interceptor;
1312
1313 // intercept the main request to simulate a network error
1314 interceptor.simulate_main_network_error_ = true;
1315
1316 // setup to intercept final response and cancel from within that job
1317 interceptor.cancel_final_request_ = true;
1318
1319 TestDelegate d;
1320 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1321 req.set_method("GET");
1322 req.Start();
1323 MessageLoop::current()->Run();
1324
1325 // Check the interceptor got called as expected
1326 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1327 EXPECT_TRUE(interceptor.did_cancel_final_);
1328
1329 // Check we see a canceled request
1330 EXPECT_FALSE(req.status().is_success());
1331 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1332}
1333
1334TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1335 TestInterceptor interceptor;
1336
1337 // intercept the main request and cancel then restart from within that job
1338 interceptor.cancel_then_restart_main_request_ = true;
1339
1340 // setup to intercept final response and override it with an OK response
1341 interceptor.intercept_final_response_ = true;
1342 interceptor.final_headers_ = TestInterceptor::ok_headers();
1343 interceptor.final_data_ = TestInterceptor::ok_data();
1344
1345 TestDelegate d;
1346 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1347 req.set_method("GET");
1348 req.Start();
1349 MessageLoop::current()->Run();
1350
1351 // Check the interceptor got called as expected
1352 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1353 EXPECT_FALSE(interceptor.did_intercept_final_);
1354
1355 // Check we see a canceled request
1356 EXPECT_FALSE(req.status().is_success());
1357 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1358}
1359
1360// Check that two different URL requests have different identifiers.
1361TEST_F(URLRequestTest, Identifiers) {
1362 TestDelegate d;
1363 TestURLRequestContext context;
[email protected]cc05edc2013-03-08 18:04:411364 TestURLRequest req(GURL("http://example.com"), &d, &context, NULL);
1365 TestURLRequest other_req(GURL("http://example.com"), &d, &context, NULL);
[email protected]316c1e5e2012-09-12 15:17:441366
1367 ASSERT_NE(req.identifier(), other_req.identifier());
1368}
1369
1370// Check that a failure to connect to the proxy is reported to the network
1371// delegate.
1372TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1373 MockHostResolver host_resolver;
1374 host_resolver.rules()->AddSimulatedFailure("*");
1375
[email protected]ceefd7fd2012-11-29 00:36:241376 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:441377 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1378
1379 TestDelegate d;
1380 URLRequest req(GURL("http://example.com"), &d, &context);
1381 req.set_method("GET");
1382
1383 req.Start();
1384 MessageLoop::current()->Run();
1385
1386 // Check we see a failed request.
1387 EXPECT_FALSE(req.status().is_success());
1388 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1389 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1390
1391 EXPECT_EQ(1, network_delegate.error_count());
1392 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1393 EXPECT_EQ(1, network_delegate.completed_requests());
1394}
1395
1396// Make sure that net::NetworkDelegate::NotifyCompleted is called if
1397// content is empty.
1398TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1399 TestDelegate d;
1400 URLRequest req(GURL("data:,"), &d, &default_context_);
1401 req.Start();
1402 MessageLoop::current()->Run();
1403 EXPECT_EQ("", d.data_received());
1404 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1405}
1406
1407// TODO(droger): Support TestServer on iOS (see http://crbug.com/148666).
1408#if !defined(OS_IOS)
1409// A subclass of TestServer that uses a statically-configured hostname. This is
1410// to work around mysterious failures in chrome_frame_net_tests. See:
1411// http://crbug.com/114369
1412class LocalHttpTestServer : public TestServer {
1413 public:
[email protected]6cdfd7f2013-02-08 20:40:151414 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]316c1e5e2012-09-12 15:17:441415 : TestServer(TestServer::TYPE_HTTP,
1416 ScopedCustomUrlRequestTestHttpHost::value(),
1417 document_root) {}
1418 LocalHttpTestServer()
1419 : TestServer(TestServer::TYPE_HTTP,
1420 ScopedCustomUrlRequestTestHttpHost::value(),
[email protected]6cdfd7f2013-02-08 20:40:151421 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:441422};
1423
[email protected]f2f31b32013-01-16 23:24:091424TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:441425 LocalHttpTestServer test_server;
1426 ASSERT_TRUE(test_server.Start());
1427
1428 TestURLRequestContext context;
1429 scoped_refptr<DelayedCookieMonster> delayed_cm =
1430 new DelayedCookieMonster();
1431 scoped_refptr<CookieStore> cookie_store = delayed_cm;
1432 context.set_cookie_store(delayed_cm);
1433
1434 // Set up a cookie.
1435 {
1436 TestNetworkDelegate network_delegate;
1437 context.set_network_delegate(&network_delegate);
1438 TestDelegate d;
1439 URLRequest req(
1440 test_server.GetURL("set-cookie?CookieToNotSend=1"), &d, &context);
1441 req.Start();
1442 MessageLoop::current()->Run();
1443 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1444 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1445 EXPECT_EQ(1, network_delegate.set_cookie_count());
1446 }
1447
1448 // Verify that the cookie is set.
1449 {
1450 TestNetworkDelegate network_delegate;
1451 context.set_network_delegate(&network_delegate);
1452 TestDelegate d;
1453 URLRequest req(test_server.GetURL("echoheader?Cookie"), &d, &context);
1454 req.Start();
1455 MessageLoop::current()->Run();
1456
1457 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
1458 != std::string::npos);
1459 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1460 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1461 }
1462}
1463
[email protected]f2f31b32013-01-16 23:24:091464TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:441465 LocalHttpTestServer test_server;
1466 ASSERT_TRUE(test_server.Start());
1467
1468 // Set up a cookie.
1469 {
1470 TestNetworkDelegate network_delegate;
1471 default_context_.set_network_delegate(&network_delegate);
1472 TestDelegate d;
1473 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1474 &d,
1475 &default_context_);
1476 req.Start();
1477 MessageLoop::current()->Run();
1478 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1479 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1480 }
1481
1482 // Verify that the cookie is set.
1483 {
1484 TestNetworkDelegate network_delegate;
1485 default_context_.set_network_delegate(&network_delegate);
1486 TestDelegate d;
1487 URLRequest req(
1488 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1489 req.Start();
1490 MessageLoop::current()->Run();
1491
1492 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
1493 != std::string::npos);
1494 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1495 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1496 }
1497
1498 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
1499 {
1500 TestNetworkDelegate network_delegate;
1501 default_context_.set_network_delegate(&network_delegate);
1502 TestDelegate d;
1503 URLRequest req(
1504 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1505 req.set_load_flags(LOAD_DO_NOT_SEND_COOKIES);
1506 req.Start();
1507 MessageLoop::current()->Run();
1508
1509 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
1510 == std::string::npos);
1511
1512 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
1513 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1514 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1515 }
1516}
1517
1518TEST_F(URLRequestTest, DoNotSaveCookies) {
1519 LocalHttpTestServer test_server;
1520 ASSERT_TRUE(test_server.Start());
1521
1522 // Set up a cookie.
1523 {
1524 TestNetworkDelegate network_delegate;
1525 default_context_.set_network_delegate(&network_delegate);
1526 TestDelegate d;
1527 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
1528 &d,
1529 &default_context_);
1530 req.Start();
1531 MessageLoop::current()->Run();
1532
1533 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1534 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1535 EXPECT_EQ(1, network_delegate.set_cookie_count());
1536 }
1537
1538 // Try to set-up another cookie and update the previous cookie.
1539 {
1540 TestNetworkDelegate network_delegate;
1541 default_context_.set_network_delegate(&network_delegate);
1542 TestDelegate d;
1543 URLRequest req(
1544 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
1545 &d,
1546 &default_context_);
1547 req.set_load_flags(LOAD_DO_NOT_SAVE_COOKIES);
1548 req.Start();
1549
1550 MessageLoop::current()->Run();
1551
1552 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
1553 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1554 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1555 EXPECT_EQ(0, network_delegate.set_cookie_count());
1556 }
1557
1558 // Verify the cookies weren't saved or updated.
1559 {
1560 TestNetworkDelegate network_delegate;
1561 default_context_.set_network_delegate(&network_delegate);
1562 TestDelegate d;
1563 URLRequest req(
1564 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1565 req.Start();
1566 MessageLoop::current()->Run();
1567
1568 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
1569 == std::string::npos);
1570 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
1571 != std::string::npos);
1572
1573 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1574 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1575 EXPECT_EQ(0, network_delegate.set_cookie_count());
1576 }
1577}
1578
1579TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
1580 LocalHttpTestServer test_server;
1581 ASSERT_TRUE(test_server.Start());
1582
1583 // Set up a cookie.
1584 {
1585 TestNetworkDelegate network_delegate;
1586 default_context_.set_network_delegate(&network_delegate);
1587 TestDelegate d;
1588 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1589 &d,
1590 &default_context_);
1591 req.Start();
1592 MessageLoop::current()->Run();
1593
1594 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1595 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1596 }
1597
1598 // Verify that the cookie is set.
1599 {
1600 TestNetworkDelegate network_delegate;
1601 default_context_.set_network_delegate(&network_delegate);
1602 TestDelegate d;
1603 URLRequest req(
1604 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1605 req.Start();
1606 MessageLoop::current()->Run();
1607
1608 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
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 // Verify that the cookie isn't sent.
1616 {
1617 TestNetworkDelegate network_delegate;
1618 default_context_.set_network_delegate(&network_delegate);
1619 TestDelegate d;
1620 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
1621 URLRequest req(
1622 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1623 req.Start();
1624 MessageLoop::current()->Run();
1625
1626 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
1627 == std::string::npos);
1628
1629 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
1630 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1631 }
1632}
1633
1634TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
1635 LocalHttpTestServer test_server;
1636 ASSERT_TRUE(test_server.Start());
1637
1638 // Set up a cookie.
1639 {
1640 TestNetworkDelegate network_delegate;
1641 default_context_.set_network_delegate(&network_delegate);
1642 TestDelegate d;
1643 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
1644 &d,
1645 &default_context_);
1646 req.Start();
1647 MessageLoop::current()->Run();
1648
1649 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1650 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1651 }
1652
1653 // Try to set-up another cookie and update the previous cookie.
1654 {
1655 TestNetworkDelegate network_delegate;
1656 default_context_.set_network_delegate(&network_delegate);
1657 TestDelegate d;
1658 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
1659 URLRequest req(
1660 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
1661 &d,
1662 &default_context_);
1663 req.Start();
1664
1665 MessageLoop::current()->Run();
1666
1667 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1668 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
1669 }
1670
1671 // Verify the cookies weren't saved or updated.
1672 {
1673 TestNetworkDelegate network_delegate;
1674 default_context_.set_network_delegate(&network_delegate);
1675 TestDelegate d;
1676 URLRequest req(
1677 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1678 req.Start();
1679 MessageLoop::current()->Run();
1680
1681 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
1682 == std::string::npos);
1683 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
1684 != std::string::npos);
1685
1686 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1687 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1688 }
1689}
1690
1691TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
1692 LocalHttpTestServer test_server;
1693 ASSERT_TRUE(test_server.Start());
1694
1695 // Set up an empty cookie.
1696 {
1697 TestNetworkDelegate network_delegate;
1698 default_context_.set_network_delegate(&network_delegate);
1699 TestDelegate d;
1700 URLRequest req(test_server.GetURL("set-cookie"), &d, &default_context_);
1701 req.Start();
1702 MessageLoop::current()->Run();
1703
1704 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1705 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1706 EXPECT_EQ(0, network_delegate.set_cookie_count());
1707 }
1708}
1709
1710TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
1711 LocalHttpTestServer test_server;
1712 ASSERT_TRUE(test_server.Start());
1713
1714 // Set up a cookie.
1715 {
1716 TestNetworkDelegate network_delegate;
1717 default_context_.set_network_delegate(&network_delegate);
1718 TestDelegate d;
1719 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1720 &d,
1721 &default_context_);
1722 req.Start();
1723 MessageLoop::current()->Run();
1724
1725 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1726 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1727 }
1728
1729 // Verify that the cookie is set.
1730 {
1731 TestNetworkDelegate network_delegate;
1732 default_context_.set_network_delegate(&network_delegate);
1733 TestDelegate d;
1734 URLRequest req(
1735 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1736 req.Start();
1737 MessageLoop::current()->Run();
1738
1739 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
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 // Verify that the cookie isn't sent.
1747 {
1748 TestNetworkDelegate network_delegate;
1749 default_context_.set_network_delegate(&network_delegate);
1750 TestDelegate d;
1751 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
1752 URLRequest req(
1753 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1754 req.Start();
1755 MessageLoop::current()->Run();
1756
1757 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
1758 == std::string::npos);
1759
1760 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
1761 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1762 }
1763}
1764
1765TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
1766 LocalHttpTestServer test_server;
1767 ASSERT_TRUE(test_server.Start());
1768
1769 // Set up a cookie.
1770 {
1771 TestNetworkDelegate network_delegate;
1772 default_context_.set_network_delegate(&network_delegate);
1773 TestDelegate d;
1774 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
1775 &d,
1776 &default_context_);
1777 req.Start();
1778 MessageLoop::current()->Run();
1779
1780 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1781 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1782 }
1783
1784 // Try to set-up another cookie and update the previous cookie.
1785 {
1786 TestNetworkDelegate network_delegate;
1787 default_context_.set_network_delegate(&network_delegate);
1788 TestDelegate d;
1789 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
1790 URLRequest req(
1791 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
1792 &d,
1793 &default_context_);
1794 req.Start();
1795
1796 MessageLoop::current()->Run();
1797
1798 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1799 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
1800 }
1801
1802 // Verify the cookies weren't saved or updated.
1803 {
1804 TestNetworkDelegate network_delegate;
1805 default_context_.set_network_delegate(&network_delegate);
1806 TestDelegate d;
1807 URLRequest req(
1808 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1809 req.Start();
1810 MessageLoop::current()->Run();
1811
1812 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
1813 == std::string::npos);
1814 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
1815 != std::string::npos);
1816
1817 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1818 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1819 }
1820}
1821
[email protected]5095cd72012-11-01 10:29:161822// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
1823// value for the |fixed_date| argument given to the constructor.
1824class FixedDateNetworkDelegate : public TestNetworkDelegate {
1825 public:
1826 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
1827 : fixed_date_(fixed_date) {}
1828 virtual ~FixedDateNetworkDelegate() {}
1829
1830 // net::NetworkDelegate implementation
1831 virtual int OnHeadersReceived(
1832 net::URLRequest* request,
1833 const net::CompletionCallback& callback,
1834 const net::HttpResponseHeaders* original_response_headers,
1835 scoped_refptr<net::HttpResponseHeaders>* override_response_headers)
1836 OVERRIDE;
1837
1838 private:
1839 std::string fixed_date_;
1840
1841 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
1842};
1843
1844int FixedDateNetworkDelegate::OnHeadersReceived(
1845 net::URLRequest* request,
1846 const net::CompletionCallback& callback,
1847 const net::HttpResponseHeaders* original_response_headers,
1848 scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
1849 net::HttpResponseHeaders* new_response_headers =
1850 new net::HttpResponseHeaders(original_response_headers->raw_headers());
1851
1852 new_response_headers->RemoveHeader("Date");
1853 new_response_headers->AddHeader("Date: " + fixed_date_);
1854
1855 *override_response_headers = new_response_headers;
1856 return TestNetworkDelegate::OnHeadersReceived(request,
1857 callback,
1858 original_response_headers,
1859 override_response_headers);
1860}
1861
1862// Test that cookie expiration times are adjusted for server/client clock
1863// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
1864// headers by defaulting to GMT. (crbug.com/135131)
1865TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
1866 LocalHttpTestServer test_server;
1867 ASSERT_TRUE(test_server.Start());
1868
1869 // Set up an expired cookie.
1870 {
1871 TestNetworkDelegate network_delegate;
1872 default_context_.set_network_delegate(&network_delegate);
1873 TestDelegate d;
1874 URLRequest req(test_server.GetURL(
1875 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
1876 &d,
1877 &default_context_);
1878 req.Start();
1879 MessageLoop::current()->Run();
1880 }
1881 // Verify that the cookie is not set.
1882 {
1883 TestNetworkDelegate network_delegate;
1884 default_context_.set_network_delegate(&network_delegate);
1885 TestDelegate d;
1886 URLRequest req(
1887 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1888 req.Start();
1889 MessageLoop::current()->Run();
1890
1891 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
1892 }
1893 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
1894 {
1895 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
1896 default_context_.set_network_delegate(&network_delegate);
1897 TestDelegate d;
1898 URLRequest req(test_server.GetURL(
1899 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
1900 &d,
1901 &default_context_);
1902 req.Start();
1903 MessageLoop::current()->Run();
1904 }
1905 // Verify that the cookie is set.
1906 {
1907 TestNetworkDelegate network_delegate;
1908 default_context_.set_network_delegate(&network_delegate);
1909 TestDelegate d;
1910 URLRequest req(
1911 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1912 req.Start();
1913 MessageLoop::current()->Run();
1914
1915 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
1916 }
1917}
1918
1919
[email protected]316c1e5e2012-09-12 15:17:441920// Check that it is impossible to change the referrer in the extra headers of
1921// an URLRequest.
1922TEST_F(URLRequestTest, DoNotOverrideReferrer) {
1923 LocalHttpTestServer test_server;
1924 ASSERT_TRUE(test_server.Start());
1925
1926 // If extra headers contain referer and the request contains a referer,
1927 // only the latter shall be respected.
1928 {
1929 TestDelegate d;
1930 URLRequest req(
1931 test_server.GetURL("echoheader?Referer"), &d, &default_context_);
1932 req.set_referrer("http://foo.com/");
1933
1934 HttpRequestHeaders headers;
1935 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
1936 req.SetExtraRequestHeaders(headers);
1937
1938 req.Start();
1939 MessageLoop::current()->Run();
1940
1941 EXPECT_EQ("http://foo.com/", d.data_received());
1942 }
1943
1944 // If extra headers contain a referer but the request does not, no referer
1945 // shall be sent in the header.
1946 {
1947 TestDelegate d;
1948 URLRequest req(
1949 test_server.GetURL("echoheader?Referer"), &d, &default_context_);
1950
1951 HttpRequestHeaders headers;
1952 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
1953 req.SetExtraRequestHeaders(headers);
1954 req.set_load_flags(LOAD_VALIDATE_CACHE);
1955
1956 req.Start();
1957 MessageLoop::current()->Run();
1958
1959 EXPECT_EQ("None", d.data_received());
1960 }
1961}
1962
[email protected]b89290212009-08-14 22:37:351963class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:111964 public:
1965 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:151966 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:111967 "net/data/url_request_unittest"))) {
1968 }
1969
[email protected]b89290212009-08-14 22:37:351970 protected:
[email protected]21184962011-10-26 00:50:301971 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
1972 // |request_method| is the method to use for the initial request.
1973 // |redirect_method| is the method that is expected to be used for the second
1974 // request, after redirection.
1975 // If |include_data| is true, data is uploaded with the request. The
1976 // response body is expected to match it exactly, if and only if
1977 // |request_method| == |redirect_method|.
1978 void HTTPRedirectMethodTest(const GURL& redirect_url,
1979 const std::string& request_method,
1980 const std::string& redirect_method,
1981 bool include_data) {
1982 static const char kData[] = "hello world";
1983 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:131984 URLRequest req(redirect_url, &d, &default_context_);
[email protected]21184962011-10-26 00:50:301985 req.set_method(request_method);
1986 if (include_data) {
[email protected]f288ef02012-12-15 20:28:281987 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]21184962011-10-26 00:50:301988 HttpRequestHeaders headers;
1989 headers.SetHeader(HttpRequestHeaders::kContentLength,
1990 base::UintToString(arraysize(kData) - 1));
1991 req.SetExtraRequestHeaders(headers);
1992 }
1993 req.Start();
1994 MessageLoop::current()->Run();
1995 EXPECT_EQ(redirect_method, req.method());
1996 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
1997 EXPECT_EQ(OK, req.status().error());
1998 if (include_data) {
1999 if (request_method == redirect_method) {
2000 EXPECT_EQ(kData, d.data_received());
2001 } else {
2002 EXPECT_NE(kData, d.data_received());
2003 }
2004 }
2005 if (HasFailure())
2006 LOG(WARNING) << "Request method was: " << request_method;
2007 }
2008
[email protected]762d2db2010-01-11 19:03:012009 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012010 const int kMsgSize = 20000; // multiple of 10
2011 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482012 char* uploadBytes = new char[kMsgSize+1];
2013 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012014 char marker = 'a';
2015 for (int idx = 0; idx < kMsgSize/10; idx++) {
2016 memcpy(ptr, "----------", 10);
2017 ptr += 10;
2018 if (idx % 100 == 0) {
2019 ptr--;
2020 *ptr++ = marker;
2021 if (++marker > 'z')
2022 marker = 'a';
2023 }
2024 }
2025 uploadBytes[kMsgSize] = '\0';
2026
[email protected]762d2db2010-01-11 19:03:012027 for (int i = 0; i < kIterations; ++i) {
2028 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:132029 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
[email protected]762d2db2010-01-11 19:03:012030 r.set_method(method.c_str());
2031
[email protected]f288ef02012-12-15 20:28:282032 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
[email protected]762d2db2010-01-11 19:03:012033
2034 r.Start();
2035 EXPECT_TRUE(r.is_pending());
2036
2037 MessageLoop::current()->Run();
2038
[email protected]329b68b2012-11-14 17:54:272039 ASSERT_EQ(1, d.response_started_count())
2040 << "request failed: " << r.status().status()
2041 << ", os error: " << r.status().error();
[email protected]762d2db2010-01-11 19:03:012042
2043 EXPECT_FALSE(d.received_data_before_response());
2044 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012045 }
2046 delete[] uploadBytes;
2047 }
2048
[email protected]ef2bf422012-05-11 03:27:092049 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222050 r->AppendChunkToUpload("a", 1, false);
2051 r->AppendChunkToUpload("bcd", 3, false);
2052 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2053 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2054 r->AppendChunkToUpload("0", 1, false);
2055 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112056 }
2057
[email protected]ef2bf422012-05-11 03:27:092058 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112059 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272060 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112061 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2062
[email protected]329b68b2012-11-14 17:54:272063 ASSERT_EQ(1, d->response_started_count())
2064 << "request failed: " << r->status().status()
2065 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112066
2067 EXPECT_FALSE(d->received_data_before_response());
2068
[email protected]329b68b2012-11-14 17:54:272069 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2070 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112071 }
2072
[email protected]ede03212012-09-07 12:52:262073 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342074 TestDelegate d;
2075 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2076 base::IntToString(num_cookies)),
[email protected]94e2bbe2012-06-22 15:26:132077 &d,
2078 &default_context_);
[email protected]263163f2012-06-14 22:40:342079
2080 r.Start();
2081 EXPECT_TRUE(r.is_pending());
2082
2083 MessageLoop::current()->Run();
2084
2085 bool is_success = r.status().is_success();
2086
[email protected]ede03212012-09-07 12:52:262087 if (!is_success) {
[email protected]263163f2012-06-14 22:40:342088 // Requests handled by ChromeFrame send a less precise error message,
2089 // ERR_CONNECTION_ABORTED.
2090 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG ||
2091 r.status().error() == ERR_CONNECTION_ABORTED);
2092 // The test server appears to be unable to handle subsequent requests
2093 // after this error is triggered. Force it to restart.
2094 EXPECT_TRUE(test_server_.Stop());
2095 EXPECT_TRUE(test_server_.Start());
2096 }
2097
2098 return is_success;
2099 }
2100
[email protected]1700c6a2012-02-22 18:07:072101 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352102};
2103
[email protected]95409e12010-08-17 20:07:112104// In this unit test, we're using the HTTPTestServer as a proxy server and
2105// issuing a CONNECT request with the magic host name "www.redirect.com".
2106// The HTTPTestServer will return a 302 response, which we should not
2107// follow.
[email protected]f2f31b32013-01-16 23:24:092108TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112109 ASSERT_TRUE(test_server_.Start());
2110
[email protected]ceefd7fd2012-11-29 00:36:242111 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042112 TestURLRequestContextWithProxy context(
2113 test_server_.host_port_pair().ToString(),
2114 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502115
[email protected]d1ec59082009-02-11 02:48:152116 TestDelegate d;
2117 {
[email protected]94e2bbe2012-06-22 15:26:132118 URLRequest r(GURL("https://www.redirect.com/"), &d, &context);
[email protected]d1ec59082009-02-11 02:48:152119 r.Start();
2120 EXPECT_TRUE(r.is_pending());
2121
2122 MessageLoop::current()->Run();
2123
[email protected]7461a402011-03-24 23:19:512124 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052125 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:082126 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152127 // We should not have followed the redirect.
2128 EXPECT_EQ(0, d.received_redirect_count());
2129 }
2130}
2131
[email protected]8202d0c2011-02-23 08:31:142132// This is the same as the previous test, but checks that the network delegate
2133// registers the error.
[email protected]c044616e2013-02-20 02:01:262134TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142135 ASSERT_TRUE(test_server_.Start());
2136
[email protected]ceefd7fd2012-11-29 00:36:242137 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042138 TestURLRequestContextWithProxy context(
2139 test_server_.host_port_pair().ToString(),
2140 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502141
[email protected]8202d0c2011-02-23 08:31:142142 TestDelegate d;
2143 {
[email protected]94e2bbe2012-06-22 15:26:132144 URLRequest r(GURL("https://www.redirect.com/"), &d, &context);
[email protected]8202d0c2011-02-23 08:31:142145 r.Start();
2146 EXPECT_TRUE(r.is_pending());
2147
2148 MessageLoop::current()->Run();
2149
[email protected]7461a402011-03-24 23:19:512150 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052151 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]8202d0c2011-02-23 08:31:142152 EXPECT_EQ(1, d.response_started_count());
2153 // We should not have followed the redirect.
2154 EXPECT_EQ(0, d.received_redirect_count());
2155
2156 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052157 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142158 }
2159}
2160
[email protected]dc5a5cf2012-09-26 02:49:302161// Tests that we can block and asynchronously return OK in various stages.
2162TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2163 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2164 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2165 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2166 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2167 };
2168 static const size_t blocking_stages_length = arraysize(blocking_stages);
2169
2170 ASSERT_TRUE(test_server_.Start());
2171
2172 TestDelegate d;
2173 BlockingNetworkDelegate network_delegate(
2174 BlockingNetworkDelegate::USER_CALLBACK);
2175 network_delegate.set_block_on(
2176 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2177 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2178 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2179
2180 TestURLRequestContext context(true);
2181 context.set_network_delegate(&network_delegate);
2182 context.Init();
2183
2184 {
2185 URLRequest r(test_server_.GetURL("empty.html"), &d, &context);
2186
2187 r.Start();
2188 for (size_t i = 0; i < blocking_stages_length; ++i) {
2189 MessageLoop::current()->Run();
2190 EXPECT_EQ(blocking_stages[i],
2191 network_delegate.stage_blocked_for_callback());
2192 network_delegate.DoCallback(OK);
2193 }
2194 MessageLoop::current()->Run();
2195 EXPECT_EQ(200, r.GetResponseCode());
2196 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2197 EXPECT_EQ(1, network_delegate.created_requests());
2198 EXPECT_EQ(0, network_delegate.destroyed_requests());
2199 }
2200 EXPECT_EQ(1, network_delegate.destroyed_requests());
2201}
2202
[email protected]4c76d7c2011-04-15 19:14:122203// Tests that the network delegate can block and cancel a request.
2204TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2205 ASSERT_TRUE(test_server_.Start());
2206
2207 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302208 BlockingNetworkDelegate network_delegate(
2209 BlockingNetworkDelegate::AUTO_CALLBACK);
2210 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2211 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:122212
[email protected]d5a4dd62012-05-23 01:41:042213 TestURLRequestContextWithProxy context(
2214 test_server_.host_port_pair().ToString(),
2215 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502216
[email protected]4c76d7c2011-04-15 19:14:122217 {
[email protected]94e2bbe2012-06-22 15:26:132218 URLRequest r(test_server_.GetURL(""), &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122219
2220 r.Start();
2221 MessageLoop::current()->Run();
2222
2223 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052224 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122225 EXPECT_EQ(1, network_delegate.created_requests());
2226 EXPECT_EQ(0, network_delegate.destroyed_requests());
2227 }
2228 EXPECT_EQ(1, network_delegate.destroyed_requests());
2229}
2230
[email protected]b4438d32012-09-27 06:15:302231// Helper function for NetworkDelegateCancelRequestAsynchronously and
2232// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2233// delegate operating in |block_mode| and a request for |url|. It blocks the
2234// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2235void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2236 BlockingNetworkDelegate::Stage stage,
2237 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:362238 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:302239 BlockingNetworkDelegate network_delegate(block_mode);
2240 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2241 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:362242
[email protected]b4438d32012-09-27 06:15:302243 TestURLRequestContext context(true);
2244 context.set_network_delegate(&network_delegate);
2245 context.Init();
[email protected]3cd384c602011-08-31 16:12:362246
2247 {
[email protected]b4438d32012-09-27 06:15:302248 URLRequest r(url, &d, &context);
[email protected]3cd384c602011-08-31 16:12:362249
2250 r.Start();
2251 MessageLoop::current()->Run();
2252
2253 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]b4438d32012-09-27 06:15:302254 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
[email protected]3cd384c602011-08-31 16:12:362255 EXPECT_EQ(1, network_delegate.created_requests());
2256 EXPECT_EQ(0, network_delegate.destroyed_requests());
2257 }
2258 EXPECT_EQ(1, network_delegate.destroyed_requests());
2259}
2260
[email protected]b4438d32012-09-27 06:15:302261// The following 3 tests check that the network delegate can cancel a request
2262// synchronously in various stages of the request.
2263TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2264 ASSERT_TRUE(test_server_.Start());
2265 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2266 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2267 test_server_.GetURL(""));
2268}
2269
2270TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2271 ASSERT_TRUE(test_server_.Start());
2272 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2273 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2274 test_server_.GetURL(""));
2275}
2276
2277TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2278 ASSERT_TRUE(test_server_.Start());
2279 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2280 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2281 test_server_.GetURL(""));
2282}
2283
2284// The following 3 tests check that the network delegate can cancel a request
2285// asynchronously in various stages of the request.
2286TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2287 ASSERT_TRUE(test_server_.Start());
2288 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2289 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2290 test_server_.GetURL(""));
2291}
2292
2293TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2294 ASSERT_TRUE(test_server_.Start());
2295 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2296 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2297 test_server_.GetURL(""));
2298}
2299
2300TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2301 ASSERT_TRUE(test_server_.Start());
2302 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2303 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2304 test_server_.GetURL(""));
2305}
2306
[email protected]4c76d7c2011-04-15 19:14:122307// Tests that the network delegate can block and redirect a request to a new
2308// URL.
2309TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2310 ASSERT_TRUE(test_server_.Start());
2311
2312 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302313 BlockingNetworkDelegate network_delegate(
2314 BlockingNetworkDelegate::AUTO_CALLBACK);
2315 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:122316 GURL redirect_url(test_server_.GetURL("simple.html"));
2317 network_delegate.set_redirect_url(redirect_url);
2318
[email protected]d5a4dd62012-05-23 01:41:042319 TestURLRequestContextWithProxy context(
2320 test_server_.host_port_pair().ToString(),
2321 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502322
[email protected]4c76d7c2011-04-15 19:14:122323 {
[email protected]8f1ac082011-04-19 21:14:132324 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132325 URLRequest r(original_url, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122326
2327 r.Start();
2328 MessageLoop::current()->Run();
2329
2330 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052331 EXPECT_EQ(0, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122332 EXPECT_EQ(redirect_url, r.url());
[email protected]8f1ac082011-04-19 21:14:132333 EXPECT_EQ(original_url, r.original_url());
2334 EXPECT_EQ(2U, r.url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:122335 EXPECT_EQ(1, network_delegate.created_requests());
2336 EXPECT_EQ(0, network_delegate.destroyed_requests());
2337 }
2338 EXPECT_EQ(1, network_delegate.destroyed_requests());
2339}
2340
[email protected]b813ed72012-04-05 08:21:362341// Tests that the network delegate can block and redirect a request to a new
2342// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2343TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2344 ASSERT_TRUE(test_server_.Start());
2345
2346 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302347 BlockingNetworkDelegate network_delegate(
2348 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:362349 GURL redirect_url(test_server_.GetURL("simple.html"));
2350 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:362351
[email protected]d5a4dd62012-05-23 01:41:042352 TestURLRequestContextWithProxy context(
2353 test_server_.host_port_pair().ToString(),
2354 &network_delegate);
[email protected]b813ed72012-04-05 08:21:362355
2356 {
2357 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132358 URLRequest r(original_url, &d, &context);
[email protected]b813ed72012-04-05 08:21:362359
2360 r.Start();
2361 MessageLoop::current()->Run();
2362
2363 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2364 EXPECT_EQ(0, r.status().error());
2365 EXPECT_EQ(redirect_url, r.url());
2366 EXPECT_EQ(original_url, r.original_url());
2367 EXPECT_EQ(2U, r.url_chain().size());
2368 EXPECT_EQ(1, network_delegate.created_requests());
2369 EXPECT_EQ(0, network_delegate.destroyed_requests());
2370 }
2371 EXPECT_EQ(1, network_delegate.destroyed_requests());
2372}
2373
[email protected]3c5ca8c2011-09-29 01:14:512374// Tests that redirects caused by the network delegate preserve POST data.
2375TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2376 ASSERT_TRUE(test_server_.Start());
2377
2378 const char kData[] = "hello world";
2379
2380 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302381 BlockingNetworkDelegate network_delegate(
2382 BlockingNetworkDelegate::AUTO_CALLBACK);
2383 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:512384 GURL redirect_url(test_server_.GetURL("echo"));
2385 network_delegate.set_redirect_url(redirect_url);
2386
[email protected]ef2bf422012-05-11 03:27:092387 TestURLRequestContext context(true);
2388 context.set_network_delegate(&network_delegate);
2389 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:512390
2391 {
2392 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132393 URLRequest r(original_url, &d, &context);
[email protected]3c5ca8c2011-09-29 01:14:512394 r.set_method("POST");
[email protected]f288ef02012-12-15 20:28:282395 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]3c5ca8c2011-09-29 01:14:512396 HttpRequestHeaders headers;
2397 headers.SetHeader(HttpRequestHeaders::kContentLength,
2398 base::UintToString(arraysize(kData) - 1));
2399 r.SetExtraRequestHeaders(headers);
[email protected]3c5ca8c2011-09-29 01:14:512400 r.Start();
2401 MessageLoop::current()->Run();
2402
2403 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2404 EXPECT_EQ(0, r.status().error());
2405 EXPECT_EQ(redirect_url, r.url());
2406 EXPECT_EQ(original_url, r.original_url());
2407 EXPECT_EQ(2U, r.url_chain().size());
2408 EXPECT_EQ(1, network_delegate.created_requests());
2409 EXPECT_EQ(0, network_delegate.destroyed_requests());
2410 EXPECT_EQ("POST", r.method());
2411 EXPECT_EQ(kData, d.data_received());
2412 }
2413 EXPECT_EQ(1, network_delegate.destroyed_requests());
2414}
2415
[email protected]c2911d72011-10-03 22:16:362416// Tests that the network delegate can synchronously complete OnAuthRequired
2417// by taking no action. This indicates that the NetworkDelegate does not want to
2418// handle the challenge, and is passing the buck along to the
2419// URLRequest::Delegate.
2420TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
2421 ASSERT_TRUE(test_server_.Start());
2422
2423 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302424 BlockingNetworkDelegate network_delegate(
2425 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:362426
[email protected]ef2bf422012-05-11 03:27:092427 TestURLRequestContext context(true);
2428 context.set_network_delegate(&network_delegate);
2429 context.Init();
[email protected]c2911d72011-10-03 22:16:362430
[email protected]f3cf9802011-10-28 18:44:582431 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:362432
2433 {
2434 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132435 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362436 r.Start();
2437 MessageLoop::current()->Run();
2438
2439 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2440 EXPECT_EQ(0, r.status().error());
2441 EXPECT_EQ(200, r.GetResponseCode());
2442 EXPECT_TRUE(d.auth_required_called());
2443 EXPECT_EQ(1, network_delegate.created_requests());
2444 EXPECT_EQ(0, network_delegate.destroyed_requests());
2445 }
2446 EXPECT_EQ(1, network_delegate.destroyed_requests());
2447}
2448
2449// Tests that the network delegate can synchronously complete OnAuthRequired
2450// by setting credentials.
2451TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
2452 ASSERT_TRUE(test_server_.Start());
2453
2454 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302455 BlockingNetworkDelegate network_delegate(
2456 BlockingNetworkDelegate::SYNCHRONOUS);
2457 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362458 network_delegate.set_auth_retval(
2459 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
2460
[email protected]f3cf9802011-10-28 18:44:582461 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:362462
[email protected]ef2bf422012-05-11 03:27:092463 TestURLRequestContext context(true);
2464 context.set_network_delegate(&network_delegate);
2465 context.Init();
[email protected]c2911d72011-10-03 22:16:362466
2467 {
2468 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132469 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362470 r.Start();
2471 MessageLoop::current()->Run();
2472
2473 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2474 EXPECT_EQ(0, r.status().error());
2475 EXPECT_EQ(200, r.GetResponseCode());
2476 EXPECT_FALSE(d.auth_required_called());
2477 EXPECT_EQ(1, network_delegate.created_requests());
2478 EXPECT_EQ(0, network_delegate.destroyed_requests());
2479 }
2480 EXPECT_EQ(1, network_delegate.destroyed_requests());
2481}
2482
2483// Tests that the network delegate can synchronously complete OnAuthRequired
2484// by cancelling authentication.
2485TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
2486 ASSERT_TRUE(test_server_.Start());
2487
2488 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302489 BlockingNetworkDelegate network_delegate(
2490 BlockingNetworkDelegate::SYNCHRONOUS);
2491 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362492 network_delegate.set_auth_retval(
2493 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
2494
[email protected]ef2bf422012-05-11 03:27:092495 TestURLRequestContext context(true);
2496 context.set_network_delegate(&network_delegate);
2497 context.Init();
[email protected]c2911d72011-10-03 22:16:362498
2499 {
2500 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132501 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362502 r.Start();
2503 MessageLoop::current()->Run();
2504
2505 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2506 EXPECT_EQ(OK, r.status().error());
2507 EXPECT_EQ(401, r.GetResponseCode());
2508 EXPECT_FALSE(d.auth_required_called());
2509 EXPECT_EQ(1, network_delegate.created_requests());
2510 EXPECT_EQ(0, network_delegate.destroyed_requests());
2511 }
2512 EXPECT_EQ(1, network_delegate.destroyed_requests());
2513}
2514
2515// Tests that the network delegate can asynchronously complete OnAuthRequired
2516// by taking no action. This indicates that the NetworkDelegate does not want
2517// to handle the challenge, and is passing the buck along to the
2518// URLRequest::Delegate.
2519TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
2520 ASSERT_TRUE(test_server_.Start());
2521
2522 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302523 BlockingNetworkDelegate network_delegate(
2524 BlockingNetworkDelegate::AUTO_CALLBACK);
2525 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362526
[email protected]ef2bf422012-05-11 03:27:092527 TestURLRequestContext context(true);
2528 context.set_network_delegate(&network_delegate);
2529 context.Init();
[email protected]c2911d72011-10-03 22:16:362530
[email protected]f3cf9802011-10-28 18:44:582531 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:362532
2533 {
2534 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132535 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362536 r.Start();
2537 MessageLoop::current()->Run();
2538
2539 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2540 EXPECT_EQ(0, r.status().error());
2541 EXPECT_EQ(200, r.GetResponseCode());
2542 EXPECT_TRUE(d.auth_required_called());
2543 EXPECT_EQ(1, network_delegate.created_requests());
2544 EXPECT_EQ(0, network_delegate.destroyed_requests());
2545 }
2546 EXPECT_EQ(1, network_delegate.destroyed_requests());
2547}
2548
2549// Tests that the network delegate can asynchronously complete OnAuthRequired
2550// by setting credentials.
2551TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
2552 ASSERT_TRUE(test_server_.Start());
2553
2554 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302555 BlockingNetworkDelegate network_delegate(
2556 BlockingNetworkDelegate::AUTO_CALLBACK);
2557 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362558 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:362559 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
2560
[email protected]f3cf9802011-10-28 18:44:582561 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:362562 network_delegate.set_auth_credentials(auth_credentials);
2563
[email protected]ef2bf422012-05-11 03:27:092564 TestURLRequestContext context(true);
2565 context.set_network_delegate(&network_delegate);
2566 context.Init();
[email protected]c2911d72011-10-03 22:16:362567
2568 {
2569 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132570 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362571 r.Start();
2572 MessageLoop::current()->Run();
2573
2574 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2575 EXPECT_EQ(0, r.status().error());
2576
2577 EXPECT_EQ(200, r.GetResponseCode());
2578 EXPECT_FALSE(d.auth_required_called());
2579 EXPECT_EQ(1, network_delegate.created_requests());
2580 EXPECT_EQ(0, network_delegate.destroyed_requests());
2581 }
2582 EXPECT_EQ(1, network_delegate.destroyed_requests());
2583}
2584
2585// Tests that the network delegate can asynchronously complete OnAuthRequired
2586// by cancelling authentication.
2587TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
2588 ASSERT_TRUE(test_server_.Start());
2589
2590 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302591 BlockingNetworkDelegate network_delegate(
2592 BlockingNetworkDelegate::AUTO_CALLBACK);
2593 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362594 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:362595 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
2596
[email protected]ef2bf422012-05-11 03:27:092597 TestURLRequestContext context(true);
2598 context.set_network_delegate(&network_delegate);
2599 context.Init();
[email protected]c2911d72011-10-03 22:16:362600
2601 {
2602 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132603 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362604 r.Start();
2605 MessageLoop::current()->Run();
2606
2607 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2608 EXPECT_EQ(OK, r.status().error());
2609 EXPECT_EQ(401, r.GetResponseCode());
2610 EXPECT_FALSE(d.auth_required_called());
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
[email protected]9045b8822012-01-13 20:35:352617// Tests that we can handle when a network request was canceled while we were
2618// waiting for the network delegate.
2619// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
2620TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
2621 ASSERT_TRUE(test_server_.Start());
2622
2623 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302624 BlockingNetworkDelegate network_delegate(
2625 BlockingNetworkDelegate::USER_CALLBACK);
2626 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:352627
[email protected]ef2bf422012-05-11 03:27:092628 TestURLRequestContext context(true);
2629 context.set_network_delegate(&network_delegate);
2630 context.Init();
[email protected]9045b8822012-01-13 20:35:352631
2632 {
[email protected]94e2bbe2012-06-22 15:26:132633 URLRequest r(test_server_.GetURL(""), &d, &context);
[email protected]9045b8822012-01-13 20:35:352634
2635 r.Start();
[email protected]dc5a5cf2012-09-26 02:49:302636 MessageLoop::current()->Run();
2637 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2638 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:352639 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 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
2655TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
2656 ASSERT_TRUE(test_server_.Start());
2657
2658 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302659 BlockingNetworkDelegate network_delegate(
2660 BlockingNetworkDelegate::USER_CALLBACK);
2661 network_delegate.set_block_on(
2662 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:352663
[email protected]ef2bf422012-05-11 03:27:092664 TestURLRequestContext context(true);
2665 context.set_network_delegate(&network_delegate);
2666 context.Init();
[email protected]9045b8822012-01-13 20:35:352667
2668 {
[email protected]94e2bbe2012-06-22 15:26:132669 URLRequest r(test_server_.GetURL(""), &d, &context);
[email protected]9045b8822012-01-13 20:35:352670
2671 r.Start();
[email protected]dc5a5cf2012-09-26 02:49:302672 MessageLoop::current()->Run();
2673 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2674 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:352675 EXPECT_EQ(0, network_delegate.completed_requests());
2676 // Cancel before callback.
2677 r.Cancel();
2678 // Ensure that network delegate is notified.
2679 EXPECT_EQ(1, network_delegate.completed_requests());
2680 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
2681 EXPECT_EQ(ERR_ABORTED, r.status().error());
2682 EXPECT_EQ(1, network_delegate.created_requests());
2683 EXPECT_EQ(0, network_delegate.destroyed_requests());
2684 }
2685 EXPECT_EQ(1, network_delegate.destroyed_requests());
2686}
2687
2688// Tests that we can handle when a network request was canceled while we were
2689// waiting for the network delegate.
2690// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
2691TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
2692 ASSERT_TRUE(test_server_.Start());
2693
2694 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302695 BlockingNetworkDelegate network_delegate(
2696 BlockingNetworkDelegate::USER_CALLBACK);
2697 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:352698
[email protected]ef2bf422012-05-11 03:27:092699 TestURLRequestContext context(true);
2700 context.set_network_delegate(&network_delegate);
2701 context.Init();
[email protected]9045b8822012-01-13 20:35:352702
2703 {
[email protected]94e2bbe2012-06-22 15:26:132704 URLRequest r(test_server_.GetURL(""), &d, &context);
[email protected]9045b8822012-01-13 20:35:352705
2706 r.Start();
[email protected]dc5a5cf2012-09-26 02:49:302707 MessageLoop::current()->Run();
2708 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2709 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:352710 EXPECT_EQ(0, network_delegate.completed_requests());
2711 // Cancel before callback.
2712 r.Cancel();
2713 // Ensure that network delegate is notified.
2714 EXPECT_EQ(1, network_delegate.completed_requests());
2715 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
2716 EXPECT_EQ(ERR_ABORTED, r.status().error());
2717 EXPECT_EQ(1, network_delegate.created_requests());
2718 EXPECT_EQ(0, network_delegate.destroyed_requests());
2719 }
2720 EXPECT_EQ(1, network_delegate.destroyed_requests());
2721}
2722
2723// Tests that we can handle when a network request was canceled while we were
2724// waiting for the network delegate.
2725// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:022726TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:352727 ASSERT_TRUE(test_server_.Start());
2728
2729 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302730 BlockingNetworkDelegate network_delegate(
2731 BlockingNetworkDelegate::USER_CALLBACK);
2732 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:352733
[email protected]ef2bf422012-05-11 03:27:092734 TestURLRequestContext context(true);
2735 context.set_network_delegate(&network_delegate);
2736 context.Init();
[email protected]9045b8822012-01-13 20:35:352737
2738 {
[email protected]94e2bbe2012-06-22 15:26:132739 URLRequest r(test_server_.GetURL("auth-basic"), &d, &context);
[email protected]9045b8822012-01-13 20:35:352740
2741 r.Start();
[email protected]dc5a5cf2012-09-26 02:49:302742 MessageLoop::current()->Run();
2743 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
2744 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:352745 EXPECT_EQ(0, network_delegate.completed_requests());
2746 // Cancel before callback.
2747 r.Cancel();
2748 // Ensure that network delegate is notified.
2749 EXPECT_EQ(1, network_delegate.completed_requests());
2750 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
2751 EXPECT_EQ(ERR_ABORTED, r.status().error());
2752 EXPECT_EQ(1, network_delegate.created_requests());
2753 EXPECT_EQ(0, network_delegate.destroyed_requests());
2754 }
2755 EXPECT_EQ(1, network_delegate.destroyed_requests());
2756}
2757
[email protected]95409e12010-08-17 20:07:112758// In this unit test, we're using the HTTPTestServer as a proxy server and
2759// issuing a CONNECT request with the magic host name "www.server-auth.com".
2760// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:352761TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:112762 ASSERT_TRUE(test_server_.Start());
2763
[email protected]ceefd7fd2012-11-29 00:36:242764 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042765 TestURLRequestContextWithProxy context(
2766 test_server_.host_port_pair().ToString(),
2767 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502768
[email protected]dc651782009-02-14 01:45:082769 TestDelegate d;
2770 {
[email protected]94e2bbe2012-06-22 15:26:132771 URLRequest r(GURL("https://www.server-auth.com/"), &d, &context);
[email protected]dc651782009-02-14 01:45:082772
2773 r.Start();
2774 EXPECT_TRUE(r.is_pending());
2775
2776 MessageLoop::current()->Run();
2777
[email protected]7461a402011-03-24 23:19:512778 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052779 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:082780 }
2781}
2782
[email protected]b89290212009-08-14 22:37:352783TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:112784 ASSERT_TRUE(test_server_.Start());
2785
initial.commit586acc5fe2008-07-26 22:42:522786 TestDelegate d;
2787 {
[email protected]94e2bbe2012-06-22 15:26:132788 URLRequest r(test_server_.GetURL(""), &d, &default_context_);
initial.commit586acc5fe2008-07-26 22:42:522789
2790 r.Start();
2791 EXPECT_TRUE(r.is_pending());
2792
2793 MessageLoop::current()->Run();
2794
2795 EXPECT_EQ(1, d.response_started_count());
2796 EXPECT_FALSE(d.received_data_before_response());
2797 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:192798 EXPECT_EQ(test_server_.host_port_pair().host(),
2799 r.GetSocketAddress().host());
2800 EXPECT_EQ(test_server_.host_port_pair().port(),
2801 r.GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:162802
[email protected]9e743cd2010-03-16 07:03:532803 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:522804 }
initial.commit586acc5fe2008-07-26 22:42:522805}
2806
[email protected]263163f2012-06-14 22:40:342807// This test has the server send a large number of cookies to the client.
2808// To ensure that no number of cookies causes a crash, a galloping binary
2809// search is used to estimate that maximum number of cookies that are accepted
2810// by the browser. Beyond the maximum number, the request will fail with
2811// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:302812#if defined(OS_WIN)
2813// http://crbug.com/177916
2814#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
2815#else
2816#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
2817#endif // defined(OS_WIN)
2818TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:342819 ASSERT_TRUE(test_server_.Start());
2820
2821 int lower_bound = 0;
2822 int upper_bound = 1;
2823
2824 // Double the number of cookies until the response header limits are
2825 // exceeded.
2826 while (DoManyCookiesRequest(upper_bound)) {
2827 lower_bound = upper_bound;
2828 upper_bound *= 2;
2829 ASSERT_LT(upper_bound, 1000000);
2830 }
2831
2832 int tolerance = upper_bound * 0.005;
2833 if (tolerance < 2)
2834 tolerance = 2;
2835
2836 // Perform a binary search to find the highest possible number of cookies,
2837 // within the desired tolerance.
2838 while (upper_bound - lower_bound >= tolerance) {
2839 int num_cookies = (lower_bound + upper_bound) / 2;
2840
2841 if (DoManyCookiesRequest(num_cookies))
2842 lower_bound = num_cookies;
2843 else
2844 upper_bound = num_cookies;
2845 }
2846 // Success: the test did not crash.
2847}
2848
[email protected]b89290212009-08-14 22:37:352849TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:112850 ASSERT_TRUE(test_server_.Start());
2851
initial.commit586acc5fe2008-07-26 22:42:522852 TestDelegate d;
2853 {
[email protected]94e2bbe2012-06-22 15:26:132854 URLRequest r(test_server_.GetURL(""), &d, &default_context_);
initial.commit586acc5fe2008-07-26 22:42:522855
2856 r.Start();
2857 EXPECT_TRUE(r.is_pending());
2858
2859 MessageLoop::current()->Run();
2860
2861 EXPECT_EQ(1, d.response_started_count());
2862 EXPECT_FALSE(d.received_data_before_response());
2863 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:192864 EXPECT_EQ(test_server_.host_port_pair().host(),
2865 r.GetSocketAddress().host());
2866 EXPECT_EQ(test_server_.host_port_pair().port(),
2867 r.GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:522868 }
[email protected]5d7b373e2009-09-02 07:19:032869}
2870
[email protected]58e32bb2013-01-21 18:23:252871TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
2872 ASSERT_TRUE(test_server_.Start());
2873
2874 TestDelegate d;
2875 {
2876 URLRequest r(test_server_.GetURL(""), &d, &default_context_);
2877
2878 r.Start();
2879 EXPECT_TRUE(r.is_pending());
2880
2881 MessageLoop::current()->Run();
2882
2883 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:172884 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:252885 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
2886
2887 EXPECT_EQ(1, d.response_started_count());
2888 EXPECT_FALSE(d.received_data_before_response());
2889 EXPECT_NE(0, d.bytes_received());
2890 EXPECT_EQ(test_server_.host_port_pair().host(),
2891 r.GetSocketAddress().host());
2892 EXPECT_EQ(test_server_.host_port_pair().port(),
2893 r.GetSocketAddress().port());
2894 }
2895}
2896
[email protected]aad63572011-05-24 20:14:392897TEST_F(URLRequestTestHTTP, GetZippedTest) {
2898 ASSERT_TRUE(test_server_.Start());
2899
2900 // Parameter that specifies the Content-Length field in the response:
2901 // C - Compressed length.
2902 // U - Uncompressed length.
2903 // L - Large length (larger than both C & U).
2904 // M - Medium length (between C & U).
2905 // S - Small length (smaller than both C & U).
2906 const char test_parameters[] = "CULMS";
2907 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
2908 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:442909 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:392910 // S has too little data, but we seem to accept it.
2911 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:372912 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:392913
2914 for (int i = 0; i < num_tests ; i++) {
2915 TestDelegate d;
2916 {
2917 std::string test_file =
2918 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
2919 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:392920
[email protected]ceefd7fd2012-11-29 00:36:242921 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:092922 TestURLRequestContext context(true);
2923 context.set_network_delegate(&network_delegate);
2924 context.Init();
[email protected]87a09a92011-07-14 15:50:502925
[email protected]94e2bbe2012-06-22 15:26:132926 URLRequest r(test_server_.GetURL(test_file), &d, &context);
[email protected]aad63572011-05-24 20:14:392927 r.Start();
2928 EXPECT_TRUE(r.is_pending());
2929
2930 MessageLoop::current()->Run();
2931
2932 EXPECT_EQ(1, d.response_started_count());
2933 EXPECT_FALSE(d.received_data_before_response());
2934 VLOG(1) << " Received " << d.bytes_received() << " bytes"
2935 << " status = " << r.status().status()
[email protected]d0cc35b2011-09-08 12:02:052936 << " error = " << r.status().error();
[email protected]aad63572011-05-24 20:14:392937 if (test_expect_success[i]) {
2938 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
2939 << " Parameter = \"" << test_file << "\"";
2940 } else {
2941 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]5543cbb2012-04-20 16:35:232942 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
[email protected]aad63572011-05-24 20:14:392943 << " Parameter = \"" << test_file << "\"";
2944 }
2945 }
2946 }
2947}
2948
[email protected]c044616e2013-02-20 02:01:262949TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
[email protected]95409e12010-08-17 20:07:112950 ASSERT_TRUE(test_server_.Start());
2951
[email protected]6cdfd7f2013-02-08 20:40:152952 TestServer https_test_server(
2953 TestServer::TYPE_HTTPS, TestServer::kLocalhost,
2954 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:112955 ASSERT_TRUE(https_test_server.Start());
[email protected]7844480a2009-12-16 21:18:582956
2957 // An https server is sent a request with an https referer,
2958 // and responds with a redirect to an http url. The http
2959 // server should not be sent the referer.
[email protected]95409e12010-08-17 20:07:112960 GURL http_destination = test_server_.GetURL("");
[email protected]7844480a2009-12-16 21:18:582961 TestDelegate d;
[email protected]ef2bf422012-05-11 03:27:092962 URLRequest req(https_test_server.GetURL(
[email protected]94e2bbe2012-06-22 15:26:132963 "server-redirect?" + http_destination.spec()), &d, &default_context_);
[email protected]7844480a2009-12-16 21:18:582964 req.set_referrer("https://www.referrer.com/");
2965 req.Start();
2966 MessageLoop::current()->Run();
2967
2968 EXPECT_EQ(1, d.response_started_count());
2969 EXPECT_EQ(1, d.received_redirect_count());
2970 EXPECT_EQ(http_destination, req.url());
2971 EXPECT_EQ(std::string(), req.referrer());
2972}
2973
[email protected]58e32bb2013-01-21 18:23:252974TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
2975 ASSERT_TRUE(test_server_.Start());
2976
2977 GURL destination_url = test_server_.GetURL("");
2978 GURL original_url = test_server_.GetURL(
2979 "server-redirect?" + destination_url.spec());
2980 TestDelegate d;
2981 URLRequest req(original_url, &d, &default_context_);
2982 req.Start();
2983 MessageLoop::current()->Run();
2984
2985 EXPECT_EQ(1, d.response_started_count());
2986 EXPECT_EQ(1, d.received_redirect_count());
2987 EXPECT_EQ(destination_url, req.url());
2988 EXPECT_EQ(original_url, req.original_url());
2989 ASSERT_EQ(2U, req.url_chain().size());
2990 EXPECT_EQ(original_url, req.url_chain()[0]);
2991 EXPECT_EQ(destination_url, req.url_chain()[1]);
2992
2993 LoadTimingInfo load_timing_info_before_redirect;
2994 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
2995 &load_timing_info_before_redirect));
2996 TestLoadTimingNotReused(load_timing_info_before_redirect,
2997 CONNECT_TIMING_HAS_DNS_TIMES);
2998
2999 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173000 req.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253001 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3002
3003 // Check that a new socket was used on redirect, since the server does not
3004 // supposed keep-alive sockets, and that the times before the redirect are
3005 // before the ones recorded for the second request.
3006 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3007 load_timing_info.socket_log_id);
3008 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3009 load_timing_info.connect_timing.connect_start);
3010}
3011
[email protected]8f1ac082011-04-19 21:14:133012TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3013 ASSERT_TRUE(test_server_.Start());
3014
3015 GURL destination_url = test_server_.GetURL("");
3016 GURL middle_redirect_url = test_server_.GetURL(
3017 "server-redirect?" + destination_url.spec());
3018 GURL original_url = test_server_.GetURL(
3019 "server-redirect?" + middle_redirect_url.spec());
3020 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:133021 URLRequest req(original_url, &d, &default_context_);
[email protected]8f1ac082011-04-19 21:14:133022 req.Start();
3023 MessageLoop::current()->Run();
3024
3025 EXPECT_EQ(1, d.response_started_count());
3026 EXPECT_EQ(2, d.received_redirect_count());
3027 EXPECT_EQ(destination_url, req.url());
3028 EXPECT_EQ(original_url, req.original_url());
3029 ASSERT_EQ(3U, req.url_chain().size());
3030 EXPECT_EQ(original_url, req.url_chain()[0]);
3031 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3032 EXPECT_EQ(destination_url, req.url_chain()[2]);
3033}
3034
[email protected]847c0fa92012-11-06 16:37:423035namespace {
3036
3037const char kExtraHeader[] = "Allow-Snafu";
3038const char kExtraValue[] = "fubar";
3039
3040class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:163041 virtual void OnReceivedRedirect(net::URLRequest* request,
3042 const GURL& new_url,
3043 bool* defer_redirect) OVERRIDE {
[email protected]847c0fa92012-11-06 16:37:423044 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
3045 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
3046 }
3047};
3048
3049} // namespace
3050
3051TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
3052 ASSERT_TRUE(test_server_.Start());
3053
3054 GURL destination_url = test_server_.GetURL(
3055 "echoheader?" + std::string(kExtraHeader));
3056 GURL original_url = test_server_.GetURL(
3057 "server-redirect?" + destination_url.spec());
3058 RedirectWithAdditionalHeadersDelegate d;
3059 URLRequest req(original_url, &d, &default_context_);
3060 req.Start();
3061 MessageLoop::current()->Run();
3062
3063 std::string value;
3064 const HttpRequestHeaders& headers = req.extra_request_headers();
3065 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
3066 EXPECT_EQ(kExtraValue, value);
3067 EXPECT_FALSE(req.is_pending());
3068 EXPECT_FALSE(req.is_redirecting());
3069 EXPECT_EQ(kExtraValue, d.data_received());
3070}
3071
[email protected]251a1b92012-11-13 11:01:093072namespace {
3073
3074const char kExtraHeaderToRemove[] = "To-Be-Removed";
3075
3076class RedirectWithHeaderRemovalDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:163077 virtual void OnReceivedRedirect(net::URLRequest* request,
[email protected]251a1b92012-11-13 11:01:093078 const GURL& new_url,
[email protected]46fadfd2013-02-06 09:40:163079 bool* defer_redirect) OVERRIDE {
[email protected]251a1b92012-11-13 11:01:093080 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
3081 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
3082 }
3083};
3084
3085} // namespace
3086
3087TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
3088 ASSERT_TRUE(test_server_.Start());
3089
3090 GURL destination_url = test_server_.GetURL(
3091 "echoheader?" + std::string(kExtraHeaderToRemove));
3092 GURL original_url = test_server_.GetURL(
3093 "server-redirect?" + destination_url.spec());
3094 RedirectWithHeaderRemovalDelegate d;
3095 URLRequest req(original_url, &d, &default_context_);
3096 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
3097 req.Start();
3098 MessageLoop::current()->Run();
3099
3100 std::string value;
3101 const HttpRequestHeaders& headers = req.extra_request_headers();
3102 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
3103 EXPECT_FALSE(req.is_pending());
3104 EXPECT_FALSE(req.is_redirecting());
3105 EXPECT_EQ("None", d.data_received());
3106}
3107
[email protected]316c1e5e2012-09-12 15:17:443108TEST_F(URLRequestTestHTTP, CancelTest) {
3109 TestDelegate d;
3110 {
3111 URLRequest r(GURL("http://www.google.com/"), &d, &default_context_);
3112
3113 r.Start();
3114 EXPECT_TRUE(r.is_pending());
3115
3116 r.Cancel();
3117
3118 MessageLoop::current()->Run();
3119
3120 // We expect to receive OnResponseStarted even though the request has been
3121 // cancelled.
3122 EXPECT_EQ(1, d.response_started_count());
3123 EXPECT_EQ(0, d.bytes_received());
3124 EXPECT_FALSE(d.received_data_before_response());
3125 }
3126}
3127
3128TEST_F(URLRequestTestHTTP, CancelTest2) {
3129 ASSERT_TRUE(test_server_.Start());
3130
3131 TestDelegate d;
3132 {
3133 URLRequest r(test_server_.GetURL(""), &d, &default_context_);
3134
3135 d.set_cancel_in_response_started(true);
3136
3137 r.Start();
3138 EXPECT_TRUE(r.is_pending());
3139
3140 MessageLoop::current()->Run();
3141
3142 EXPECT_EQ(1, d.response_started_count());
3143 EXPECT_EQ(0, d.bytes_received());
3144 EXPECT_FALSE(d.received_data_before_response());
3145 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3146 }
3147}
3148
3149TEST_F(URLRequestTestHTTP, CancelTest3) {
3150 ASSERT_TRUE(test_server_.Start());
3151
3152 TestDelegate d;
3153 {
3154 URLRequest r(test_server_.GetURL(""), &d, &default_context_);
3155
3156 d.set_cancel_in_received_data(true);
3157
3158 r.Start();
3159 EXPECT_TRUE(r.is_pending());
3160
3161 MessageLoop::current()->Run();
3162
3163 EXPECT_EQ(1, d.response_started_count());
3164 // There is no guarantee about how much data was received
3165 // before the cancel was issued. It could have been 0 bytes,
3166 // or it could have been all the bytes.
3167 // EXPECT_EQ(0, d.bytes_received());
3168 EXPECT_FALSE(d.received_data_before_response());
3169 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3170 }
3171}
3172
3173TEST_F(URLRequestTestHTTP, CancelTest4) {
3174 ASSERT_TRUE(test_server_.Start());
3175
3176 TestDelegate d;
3177 {
3178 URLRequest r(test_server_.GetURL(""), &d, &default_context_);
3179
3180 r.Start();
3181 EXPECT_TRUE(r.is_pending());
3182
3183 // The request will be implicitly canceled when it is destroyed. The
3184 // test delegate must not post a quit message when this happens because
3185 // this test doesn't actually have a message loop. The quit message would
3186 // get put on this thread's message queue and the next test would exit
3187 // early, causing problems.
3188 d.set_quit_on_complete(false);
3189 }
3190 // expect things to just cleanup properly.
3191
3192 // we won't actually get a received reponse here because we've never run the
3193 // message loop
3194 EXPECT_FALSE(d.received_data_before_response());
3195 EXPECT_EQ(0, d.bytes_received());
3196}
3197
3198TEST_F(URLRequestTestHTTP, CancelTest5) {
3199 ASSERT_TRUE(test_server_.Start());
3200
3201 // populate cache
3202 {
3203 TestDelegate d;
3204 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_);
3205 r.Start();
3206 MessageLoop::current()->Run();
3207 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3208 }
3209
3210 // cancel read from cache (see bug 990242)
3211 {
3212 TestDelegate d;
3213 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_);
3214 r.Start();
3215 r.Cancel();
3216 MessageLoop::current()->Run();
3217
3218 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3219 EXPECT_EQ(1, d.response_started_count());
3220 EXPECT_EQ(0, d.bytes_received());
3221 EXPECT_FALSE(d.received_data_before_response());
3222 }
3223}
3224
3225TEST_F(URLRequestTestHTTP, PostTest) {
3226 ASSERT_TRUE(test_server_.Start());
3227 HTTPUploadDataOperationTest("POST");
3228}
3229
3230TEST_F(URLRequestTestHTTP, PutTest) {
3231 ASSERT_TRUE(test_server_.Start());
3232 HTTPUploadDataOperationTest("PUT");
3233}
3234
3235TEST_F(URLRequestTestHTTP, PostEmptyTest) {
3236 ASSERT_TRUE(test_server_.Start());
3237
3238 TestDelegate d;
3239 {
3240 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3241 r.set_method("POST");
3242
3243 r.Start();
3244 EXPECT_TRUE(r.is_pending());
3245
3246 MessageLoop::current()->Run();
3247
[email protected]329b68b2012-11-14 17:54:273248 ASSERT_EQ(1, d.response_started_count())
3249 << "request failed: " << r.status().status()
3250 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:443251
3252 EXPECT_FALSE(d.received_data_before_response());
3253 EXPECT_TRUE(d.data_received().empty());
3254 }
3255}
3256
3257TEST_F(URLRequestTestHTTP, PostFileTest) {
3258 ASSERT_TRUE(test_server_.Start());
3259
3260 TestDelegate d;
3261 {
3262 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3263 r.set_method("POST");
3264
[email protected]6cdfd7f2013-02-08 20:40:153265 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:443266 PathService::Get(base::DIR_EXE, &dir);
3267 file_util::SetCurrentDirectory(dir);
3268
[email protected]f288ef02012-12-15 20:28:283269 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:443270
[email protected]6cdfd7f2013-02-08 20:40:153271 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:443272 PathService::Get(base::DIR_SOURCE_ROOT, &path);
3273 path = path.Append(FILE_PATH_LITERAL("net"));
3274 path = path.Append(FILE_PATH_LITERAL("data"));
3275 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
3276 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]f288ef02012-12-15 20:28:283277 element_readers.push_back(new UploadFileElementReader(
[email protected]671a7142013-01-10 14:08:073278 base::MessageLoopProxy::current(), path, 0, kuint64max, base::Time()));
[email protected]316c1e5e2012-09-12 15:17:443279
3280 // This file should just be ignored in the upload stream.
[email protected]f288ef02012-12-15 20:28:283281 element_readers.push_back(new UploadFileElementReader(
[email protected]671a7142013-01-10 14:08:073282 base::MessageLoopProxy::current(),
[email protected]6cdfd7f2013-02-08 20:40:153283 base::FilePath(FILE_PATH_LITERAL(
[email protected]316c1e5e2012-09-12 15:17:443284 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
[email protected]f288ef02012-12-15 20:28:283285 0, kuint64max, base::Time()));
3286 r.set_upload(make_scoped_ptr(new UploadDataStream(&element_readers, 0)));
[email protected]316c1e5e2012-09-12 15:17:443287
3288 r.Start();
3289 EXPECT_TRUE(r.is_pending());
3290
3291 MessageLoop::current()->Run();
3292
[email protected]329b68b2012-11-14 17:54:273293 int64 size = 0;
3294 ASSERT_EQ(true, file_util::GetFileSize(path, &size));
[email protected]316c1e5e2012-09-12 15:17:443295 scoped_array<char> buf(new char[size]);
3296
[email protected]329b68b2012-11-14 17:54:273297 ASSERT_EQ(size, file_util::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:443298
[email protected]329b68b2012-11-14 17:54:273299 ASSERT_EQ(1, d.response_started_count())
3300 << "request failed: " << r.status().status()
3301 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:443302
3303 EXPECT_FALSE(d.received_data_before_response());
3304
[email protected]329b68b2012-11-14 17:54:273305 EXPECT_EQ(size, d.bytes_received());
3306 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:443307 }
3308}
3309
3310TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
3311 ASSERT_TRUE(test_server_.Start());
3312
3313 TestDelegate d;
3314 {
3315 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3316 r.EnableChunkedUpload();
3317 r.set_method("POST");
3318 AddChunksToUpload(&r);
3319 r.Start();
3320 EXPECT_TRUE(r.is_pending());
3321
3322 MessageLoop::current()->Run();
3323
3324 VerifyReceivedDataMatchesChunks(&r, &d);
3325 }
3326}
3327
[email protected]329b68b2012-11-14 17:54:273328TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
3329 ASSERT_TRUE(test_server_.Start());
3330
3331 TestDelegate d;
3332 {
3333 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3334 r.EnableChunkedUpload();
3335 r.set_method("POST");
3336 r.Start();
3337 EXPECT_TRUE(r.is_pending());
3338 AddChunksToUpload(&r);
3339 MessageLoop::current()->Run();
3340
3341 VerifyReceivedDataMatchesChunks(&r, &d);
3342 }
3343}
3344
[email protected]316c1e5e2012-09-12 15:17:443345TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
3346 ASSERT_TRUE(test_server_.Start());
3347
3348 TestDelegate d;
3349 {
3350 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3351 r.EnableChunkedUpload();
3352 r.set_method("POST");
3353 r.Start();
3354 EXPECT_TRUE(r.is_pending());
3355
[email protected]b4c62eb2012-11-14 18:36:513356 MessageLoop::current()->RunUntilIdle();
[email protected]316c1e5e2012-09-12 15:17:443357 AddChunksToUpload(&r);
3358 MessageLoop::current()->Run();
3359
3360 VerifyReceivedDataMatchesChunks(&r, &d);
3361 }
3362}
3363
3364TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
3365 ASSERT_TRUE(test_server_.Start());
3366
3367 TestDelegate d;
3368 URLRequest req(
3369 test_server_.GetURL("files/with-headers.html"), &d, &default_context_);
3370 req.Start();
3371 MessageLoop::current()->Run();
3372
3373 const HttpResponseHeaders* headers = req.response_headers();
3374
3375 // Simple sanity check that response_info() accesses the same data.
3376 EXPECT_EQ(headers, req.response_info().headers.get());
3377
3378 std::string header;
3379 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
3380 EXPECT_EQ("private", header);
3381
3382 header.clear();
3383 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
3384 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
3385
3386 // The response has two "X-Multiple-Entries" headers.
3387 // This verfies our output has them concatenated together.
3388 header.clear();
3389 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
3390 EXPECT_EQ("a, b", header);
3391}
3392
[email protected]242d8562012-10-30 21:20:463393TEST_F(URLRequestTestHTTP, ProcessSTS) {
3394 TestServer::SSLOptions ssl_options;
3395 TestServer https_test_server(
3396 TestServer::TYPE_HTTPS,
3397 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:153398 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:463399 ASSERT_TRUE(https_test_server.Start());
3400
3401 TestDelegate d;
3402 URLRequest request(
3403 https_test_server.GetURL("files/hsts-headers.html"),
3404 &d,
3405 &default_context_);
3406 request.Start();
3407 MessageLoop::current()->Run();
3408
3409 TransportSecurityState* security_state =
3410 default_context_.transport_security_state();
3411 bool sni_available = true;
3412 TransportSecurityState::DomainState domain_state;
3413 EXPECT_TRUE(security_state->GetDomainState(
3414 TestServer::kLocalhost, sni_available, &domain_state));
3415 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
3416 domain_state.upgrade_mode);
3417 EXPECT_TRUE(domain_state.include_subdomains);
3418}
3419
3420TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
3421 TestServer::SSLOptions ssl_options;
3422 TestServer https_test_server(
3423 TestServer::TYPE_HTTPS,
3424 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:153425 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:463426 ASSERT_TRUE(https_test_server.Start());
3427
3428 TestDelegate d;
3429 URLRequest request(
3430 https_test_server.GetURL("files/hsts-multiple-headers.html"),
3431 &d,
3432 &default_context_);
3433 request.Start();
3434 MessageLoop::current()->Run();
3435
3436 // We should have set parameters from the first header, not the second.
3437 TransportSecurityState* security_state =
3438 default_context_.transport_security_state();
3439 bool sni_available = true;
3440 TransportSecurityState::DomainState domain_state;
3441 EXPECT_TRUE(security_state->GetDomainState(
3442 TestServer::kLocalhost, sni_available, &domain_state));
3443 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
3444 domain_state.upgrade_mode);
3445 EXPECT_FALSE(domain_state.include_subdomains);
3446}
3447
[email protected]316c1e5e2012-09-12 15:17:443448TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
3449 ASSERT_TRUE(test_server_.Start());
3450
3451 TestDelegate d;
3452 URLRequest req(test_server_.GetURL(
3453 "files/content-type-normalization.html"), &d, &default_context_);
3454 req.Start();
3455 MessageLoop::current()->Run();
3456
3457 std::string mime_type;
3458 req.GetMimeType(&mime_type);
3459 EXPECT_EQ("text/html", mime_type);
3460
3461 std::string charset;
3462 req.GetCharset(&charset);
3463 EXPECT_EQ("utf-8", charset);
3464 req.Cancel();
3465}
3466
3467TEST_F(URLRequestTestHTTP, RestrictRedirects) {
3468 ASSERT_TRUE(test_server_.Start());
3469
3470 TestDelegate d;
3471 URLRequest req(test_server_.GetURL(
3472 "files/redirect-to-file.html"), &d, &default_context_);
3473 req.Start();
3474 MessageLoop::current()->Run();
3475
3476 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
3477 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
3478}
3479
3480TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
3481 ASSERT_TRUE(test_server_.Start());
3482
3483 TestDelegate d;
3484 URLRequest req(test_server_.GetURL(
3485 "files/redirect-to-invalid-url.html"), &d, &default_context_);
3486 req.Start();
3487 MessageLoop::current()->Run();
3488
3489 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
3490 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
3491}
3492
3493TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
3494 ASSERT_TRUE(test_server_.Start());
3495
3496 TestDelegate d;
3497 URLRequest req(
3498 test_server_.GetURL("echoheader?Referer"), &d, &default_context_);
3499 req.set_referrer("http://user:[email protected]/");
3500 req.Start();
3501 MessageLoop::current()->Run();
3502
3503 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
3504}
3505
3506TEST_F(URLRequestTestHTTP, CancelRedirect) {
3507 ASSERT_TRUE(test_server_.Start());
3508
3509 TestDelegate d;
3510 {
3511 d.set_cancel_in_received_redirect(true);
3512 URLRequest req(
3513 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_);
3514 req.Start();
3515 MessageLoop::current()->Run();
3516
3517 EXPECT_EQ(1, d.response_started_count());
3518 EXPECT_EQ(0, d.bytes_received());
3519 EXPECT_FALSE(d.received_data_before_response());
3520 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
3521 }
3522}
3523
3524TEST_F(URLRequestTestHTTP, DeferredRedirect) {
3525 ASSERT_TRUE(test_server_.Start());
3526
3527 TestDelegate d;
3528 {
3529 d.set_quit_on_redirect(true);
3530 URLRequest req(
3531 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_);
3532 req.Start();
3533 MessageLoop::current()->Run();
3534
3535 EXPECT_EQ(1, d.received_redirect_count());
3536
3537 req.FollowDeferredRedirect();
3538 MessageLoop::current()->Run();
3539
3540 EXPECT_EQ(1, d.response_started_count());
3541 EXPECT_FALSE(d.received_data_before_response());
3542 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
3543
[email protected]6cdfd7f2013-02-08 20:40:153544 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:443545 PathService::Get(base::DIR_SOURCE_ROOT, &path);
3546 path = path.Append(FILE_PATH_LITERAL("net"));
3547 path = path.Append(FILE_PATH_LITERAL("data"));
3548 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
3549 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
3550
3551 std::string contents;
3552 EXPECT_TRUE(file_util::ReadFileToString(path, &contents));
3553 EXPECT_EQ(contents, d.data_received());
3554 }
3555}
3556
3557TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
3558 ASSERT_TRUE(test_server_.Start());
3559
3560 TestDelegate d;
3561 {
3562 d.set_quit_on_redirect(true);
3563 URLRequest req(
3564 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_);
3565 req.Start();
3566 MessageLoop::current()->Run();
3567
3568 EXPECT_EQ(1, d.received_redirect_count());
3569
3570 req.Cancel();
3571 MessageLoop::current()->Run();
3572
3573 EXPECT_EQ(1, d.response_started_count());
3574 EXPECT_EQ(0, d.bytes_received());
3575 EXPECT_FALSE(d.received_data_before_response());
3576 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
3577 }
3578}
3579
3580TEST_F(URLRequestTestHTTP, VaryHeader) {
3581 ASSERT_TRUE(test_server_.Start());
3582
3583 // populate the cache
3584 {
3585 TestDelegate d;
3586 URLRequest req(
3587 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
3588 HttpRequestHeaders headers;
3589 headers.SetHeader("foo", "1");
3590 req.SetExtraRequestHeaders(headers);
3591 req.Start();
3592 MessageLoop::current()->Run();
3593 }
3594
3595 // expect a cache hit
3596 {
3597 TestDelegate d;
3598 URLRequest req(
3599 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
3600 HttpRequestHeaders headers;
3601 headers.SetHeader("foo", "1");
3602 req.SetExtraRequestHeaders(headers);
3603 req.Start();
3604 MessageLoop::current()->Run();
3605
3606 EXPECT_TRUE(req.was_cached());
3607 }
3608
3609 // expect a cache miss
3610 {
3611 TestDelegate d;
3612 URLRequest req(
3613 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
3614 HttpRequestHeaders headers;
3615 headers.SetHeader("foo", "2");
3616 req.SetExtraRequestHeaders(headers);
3617 req.Start();
3618 MessageLoop::current()->Run();
3619
3620 EXPECT_FALSE(req.was_cached());
3621 }
3622}
3623
3624TEST_F(URLRequestTestHTTP, BasicAuth) {
3625 ASSERT_TRUE(test_server_.Start());
3626
3627 // populate the cache
3628 {
3629 TestDelegate d;
3630 d.set_credentials(AuthCredentials(kUser, kSecret));
3631
3632 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
3633 r.Start();
3634
3635 MessageLoop::current()->Run();
3636
3637 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
3638 }
3639
3640 // repeat request with end-to-end validation. since auth-basic results in a
3641 // cachable page, we expect this test to result in a 304. in which case, the
3642 // response should be fetched from the cache.
3643 {
3644 TestDelegate d;
3645 d.set_credentials(AuthCredentials(kUser, kSecret));
3646
3647 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
3648 r.set_load_flags(LOAD_VALIDATE_CACHE);
3649 r.Start();
3650
3651 MessageLoop::current()->Run();
3652
3653 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
3654
3655 // Should be the same cached document.
3656 EXPECT_TRUE(r.was_cached());
3657 }
3658}
3659
3660// Check that Set-Cookie headers in 401 responses are respected.
3661// http://crbug.com/6450
3662TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
3663 ASSERT_TRUE(test_server_.Start());
3664
3665 GURL url_requiring_auth =
3666 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
3667
3668 // Request a page that will give a 401 containing a Set-Cookie header.
3669 // Verify that when the transaction is restarted, it includes the new cookie.
3670 {
[email protected]ceefd7fd2012-11-29 00:36:243671 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:443672 TestURLRequestContext context(true);
3673 context.set_network_delegate(&network_delegate);
3674 context.Init();
3675
3676 TestDelegate d;
3677 d.set_credentials(AuthCredentials(kUser, kSecret));
3678
3679 URLRequest r(url_requiring_auth, &d, &context);
3680 r.Start();
3681
3682 MessageLoop::current()->Run();
3683
3684 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
3685
3686 // Make sure we sent the cookie in the restarted transaction.
3687 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
3688 != std::string::npos);
3689 }
3690
3691 // Same test as above, except this time the restart is initiated earlier
3692 // (without user intervention since identity is embedded in the URL).
3693 {
[email protected]ceefd7fd2012-11-29 00:36:243694 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:443695 TestURLRequestContext context(true);
3696 context.set_network_delegate(&network_delegate);
3697 context.Init();
3698
3699 TestDelegate d;
3700
3701 GURL::Replacements replacements;
3702 std::string username("user2");
3703 std::string password("secret");
3704 replacements.SetUsernameStr(username);
3705 replacements.SetPasswordStr(password);
3706 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
3707
3708 URLRequest r(url_with_identity, &d, &context);
3709 r.Start();
3710
3711 MessageLoop::current()->Run();
3712
3713 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
3714
3715 // Make sure we sent the cookie in the restarted transaction.
3716 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
3717 != std::string::npos);
3718 }
3719}
3720
[email protected]58e32bb2013-01-21 18:23:253721// Tests that load timing works as expected with auth and the cache.
3722TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
3723 ASSERT_TRUE(test_server_.Start());
3724
3725 // populate the cache
3726 {
3727 TestDelegate d;
3728 d.set_credentials(AuthCredentials(kUser, kSecret));
3729
3730 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
3731 r.Start();
3732
3733 MessageLoop::current()->Run();
3734
3735 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
3736
3737 LoadTimingInfo load_timing_info_before_auth;
3738 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
3739 &load_timing_info_before_auth));
3740 TestLoadTimingNotReused(load_timing_info_before_auth,
3741 CONNECT_TIMING_HAS_DNS_TIMES);
3742
3743 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173744 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253745 // The test server does not support keep alive sockets, so the second
3746 // request with auth should use a new socket.
3747 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3748 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
3749 load_timing_info.socket_log_id);
3750 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
3751 load_timing_info.connect_timing.connect_start);
3752 }
3753
3754 // repeat request with end-to-end validation. since auth-basic results in a
3755 // cachable page, we expect this test to result in a 304. in which case, the
3756 // response should be fetched from the cache.
3757 {
3758 TestDelegate d;
3759 d.set_credentials(AuthCredentials(kUser, kSecret));
3760
3761 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
3762 r.set_load_flags(LOAD_VALIDATE_CACHE);
3763 r.Start();
3764
3765 MessageLoop::current()->Run();
3766
3767 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
3768
3769 // Should be the same cached document.
3770 EXPECT_TRUE(r.was_cached());
3771
3772 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173773 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253774 TestLoadTimingNoHttpConnection(load_timing_info);
3775 }
3776}
3777
[email protected]316c1e5e2012-09-12 15:17:443778// In this test, we do a POST which the server will 302 redirect.
3779// The subsequent transaction should use GET, and should not send the
3780// Content-Type header.
3781// http://code.google.com/p/chromium/issues/detail?id=843
3782TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
3783 ASSERT_TRUE(test_server_.Start());
3784
3785 const char kData[] = "hello world";
3786
3787 TestDelegate d;
3788 URLRequest req(
3789 test_server_.GetURL("files/redirect-to-echoall"), &d, &default_context_);
3790 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:283791 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:443792
3793 // Set headers (some of which are specific to the POST).
3794 HttpRequestHeaders headers;
3795 headers.AddHeadersFromString(
3796 "Content-Type: multipart/form-data; "
3797 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
3798 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
3799 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
3800 "Accept-Language: en-US,en\r\n"
3801 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
3802 "Content-Length: 11\r\n"
3803 "Origin: http://localhost:1337/");
3804 req.SetExtraRequestHeaders(headers);
3805 req.Start();
3806 MessageLoop::current()->Run();
3807
3808 std::string mime_type;
3809 req.GetMimeType(&mime_type);
3810 EXPECT_EQ("text/html", mime_type);
3811
3812 const std::string& data = d.data_received();
3813
3814 // Check that the post-specific headers were stripped:
3815 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
3816 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
3817 EXPECT_FALSE(ContainsString(data, "Origin:"));
3818
3819 // These extra request headers should not have been stripped.
3820 EXPECT_TRUE(ContainsString(data, "Accept:"));
3821 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
3822 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
3823}
3824
3825// The following tests check that we handle mutating the request method for
3826// HTTP redirects as expected.
3827// See http://crbug.com/56373 and http://crbug.com/102130.
3828
3829TEST_F(URLRequestTestHTTP, Redirect301Tests) {
3830 ASSERT_TRUE(test_server_.Start());
3831
3832 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
3833
3834 HTTPRedirectMethodTest(url, "POST", "GET", true);
3835 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
3836 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
3837}
3838
3839TEST_F(URLRequestTestHTTP, Redirect302Tests) {
3840 ASSERT_TRUE(test_server_.Start());
3841
3842 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
3843
3844 HTTPRedirectMethodTest(url, "POST", "GET", true);
3845 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
3846 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
3847}
3848
3849TEST_F(URLRequestTestHTTP, Redirect303Tests) {
3850 ASSERT_TRUE(test_server_.Start());
3851
3852 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
3853
3854 HTTPRedirectMethodTest(url, "POST", "GET", true);
3855 HTTPRedirectMethodTest(url, "PUT", "GET", true);
3856 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
3857}
3858
3859TEST_F(URLRequestTestHTTP, Redirect307Tests) {
3860 ASSERT_TRUE(test_server_.Start());
3861
3862 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
3863
3864 HTTPRedirectMethodTest(url, "POST", "POST", true);
3865 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
3866 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
3867}
3868
3869TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
3870 ASSERT_TRUE(test_server_.Start());
3871
3872 const char kData[] = "hello world";
3873
3874 TestDelegate d;
3875 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
3876 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:283877 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:443878 HttpRequestHeaders headers;
3879 headers.SetHeader(HttpRequestHeaders::kContentLength,
3880 base::UintToString(arraysize(kData) - 1));
3881 req.SetExtraRequestHeaders(headers);
3882
3883 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:413884 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]8ccc69f2012-11-28 19:52:143885 URLRequestRedirectJob::REDIRECT_302_FOUND);
[email protected]316c1e5e2012-09-12 15:17:443886 AddTestInterceptor()->set_main_intercept_job(job);
3887
3888 req.Start();
3889 MessageLoop::current()->Run();
3890 EXPECT_EQ("GET", req.method());
3891}
3892
3893TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
3894 ASSERT_TRUE(test_server_.Start());
3895
3896 const char kData[] = "hello world";
3897
3898 TestDelegate d;
3899 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
3900 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:283901 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:443902 HttpRequestHeaders headers;
3903 headers.SetHeader(HttpRequestHeaders::kContentLength,
3904 base::UintToString(arraysize(kData) - 1));
3905 req.SetExtraRequestHeaders(headers);
3906
3907 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:413908 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]316c1e5e2012-09-12 15:17:443909 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT);
3910 AddTestInterceptor()->set_main_intercept_job(job);
3911
3912 req.Start();
3913 MessageLoop::current()->Run();
3914 EXPECT_EQ("POST", req.method());
3915 EXPECT_EQ(kData, d.data_received());
3916}
3917
3918// Check that default A-L header is sent.
3919TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
3920 ASSERT_TRUE(test_server_.Start());
3921
[email protected]84f05432013-03-15 01:00:123922 StaticHttpUserAgentSettings settings("en", EmptyString());
[email protected]ceefd7fd2012-11-29 00:36:243923 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:443924 TestURLRequestContext context(true);
3925 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:433926 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:443927 context.Init();
3928
3929 TestDelegate d;
3930 URLRequest req(
3931 test_server_.GetURL("echoheader?Accept-Language"), &d, &context);
3932 req.Start();
3933 MessageLoop::current()->Run();
3934 EXPECT_EQ("en", d.data_received());
3935}
3936
3937// Check that an empty A-L header is not sent. http://crbug.com/77365.
3938TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
3939 ASSERT_TRUE(test_server_.Start());
3940
[email protected]84f05432013-03-15 01:00:123941 StaticHttpUserAgentSettings settings(EmptyString(), EmptyString());
[email protected]ceefd7fd2012-11-29 00:36:243942 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:443943 TestURLRequestContext context(true);
3944 context.set_network_delegate(&network_delegate);
3945 context.Init();
3946 // We override the language after initialization because empty entries
3947 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:433948 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:443949
3950 TestDelegate d;
3951 URLRequest req(
3952 test_server_.GetURL("echoheader?Accept-Language"), &d, &context);
3953 req.Start();
3954 MessageLoop::current()->Run();
3955 EXPECT_EQ("None", d.data_received());
3956}
3957
3958// Check that if request overrides the A-L header, the default is not appended.
3959// See http://crbug.com/20894
3960TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
3961 ASSERT_TRUE(test_server_.Start());
3962
3963 TestDelegate d;
3964 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
3965 &d,
3966 &default_context_);
3967 HttpRequestHeaders headers;
3968 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
3969 req.SetExtraRequestHeaders(headers);
3970 req.Start();
3971 MessageLoop::current()->Run();
3972 EXPECT_EQ(std::string("ru"), d.data_received());
3973}
3974
3975// Check that default A-E header is sent.
3976TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
3977 ASSERT_TRUE(test_server_.Start());
3978
3979 TestDelegate d;
3980 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
3981 &d,
3982 &default_context_);
3983 HttpRequestHeaders headers;
3984 req.SetExtraRequestHeaders(headers);
3985 req.Start();
3986 MessageLoop::current()->Run();
3987 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
3988}
3989
3990// Check that if request overrides the A-E header, the default is not appended.
3991// See http://crbug.com/47381
3992TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
3993 ASSERT_TRUE(test_server_.Start());
3994
3995 TestDelegate d;
3996 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
3997 &d,
3998 &default_context_);
3999 HttpRequestHeaders headers;
4000 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
4001 req.SetExtraRequestHeaders(headers);
4002 req.Start();
4003 MessageLoop::current()->Run();
4004 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
4005 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
4006}
4007
[email protected]84f05432013-03-15 01:00:124008// Check that setting the A-C header sends the proper header.
4009TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:444010 ASSERT_TRUE(test_server_.Start());
4011
4012 TestDelegate d;
4013 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
4014 &d,
4015 &default_context_);
4016 HttpRequestHeaders headers;
4017 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
4018 req.SetExtraRequestHeaders(headers);
4019 req.Start();
4020 MessageLoop::current()->Run();
4021 EXPECT_EQ(std::string("koi-8r"), d.data_received());
4022}
4023
4024// Check that default User-Agent header is sent.
4025TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
4026 ASSERT_TRUE(test_server_.Start());
4027
4028 TestDelegate d;
4029 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
4030 &d,
4031 &default_context_);
4032 req.Start();
4033 MessageLoop::current()->Run();
4034 EXPECT_EQ(req.context()->GetUserAgent(req.url()), d.data_received());
4035}
4036
4037// Check that if request overrides the User-Agent header,
4038// the default is not appended.
4039TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
4040 ASSERT_TRUE(test_server_.Start());
4041
4042 TestDelegate d;
4043 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
4044 &d,
4045 &default_context_);
4046 HttpRequestHeaders headers;
4047 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
4048 req.SetExtraRequestHeaders(headers);
4049 req.Start();
4050 MessageLoop::current()->Run();
4051 // If the net tests are being run with ChromeFrame then we need to allow for
4052 // the 'chromeframe' suffix which is added to the user agent before the
4053 // closing parentheses.
4054 EXPECT_TRUE(StartsWithASCII(d.data_received(), "Lynx (textmode", true));
4055}
4056
[email protected]ee4c30d2012-11-07 15:08:434057// Check that a NULL HttpUserAgentSettings causes the corresponding empty
4058// User-Agent header to be sent but does not send the Accept-Language and
4059// Accept-Charset headers.
4060TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
4061 ASSERT_TRUE(test_server_.Start());
4062
[email protected]ceefd7fd2012-11-29 00:36:244063 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:434064 TestURLRequestContext context(true);
4065 context.set_network_delegate(&network_delegate);
4066 context.Init();
4067 // We override the HttpUserAgentSettings after initialization because empty
4068 // entries get overridden by Init().
4069 context.set_http_user_agent_settings(NULL);
4070
4071 struct {
4072 const char* request;
4073 const char* expected_response;
4074 } tests[] = { { "echoheader?Accept-Language", "None" },
4075 { "echoheader?Accept-Charset", "None" },
4076 { "echoheader?User-Agent", "" } };
4077
4078 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
4079 TestDelegate d;
4080 URLRequest req(test_server_.GetURL(tests[i].request), &d, &context);
4081 req.Start();
4082 MessageLoop::current()->Run();
4083 EXPECT_EQ(tests[i].expected_response, d.data_received())
4084 << " Request = \"" << tests[i].request << "\"";
4085 }
4086}
4087
[email protected]73e0bba2009-02-19 22:57:094088class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:504089 public:
[email protected]ef2bf422012-05-11 03:27:094090 HTTPSRequestTest() : default_context_(true) {
4091 default_context_.set_network_delegate(&default_network_delegate_);
4092 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:504093 }
4094 virtual ~HTTPSRequestTest() {}
4095
4096 protected:
[email protected]ceefd7fd2012-11-29 00:36:244097 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094098 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:464099};
4100
[email protected]c044616e2013-02-20 02:01:264101TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]7461a402011-03-24 23:19:514102 TestServer test_server(TestServer::TYPE_HTTPS,
[email protected]d9fca99a2012-02-24 16:16:204103 TestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:154104 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:114105 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:464106
[email protected]ea224582008-12-07 20:25:464107 TestDelegate d;
4108 {
[email protected]94e2bbe2012-06-22 15:26:134109 URLRequest r(test_server.GetURL(""), &d, &default_context_);
[email protected]ea224582008-12-07 20:25:464110 r.Start();
4111 EXPECT_TRUE(r.is_pending());
4112
4113 MessageLoop::current()->Run();
4114
4115 EXPECT_EQ(1, d.response_started_count());
4116 EXPECT_FALSE(d.received_data_before_response());
4117 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174118 CheckSSLInfo(r.ssl_info());
[email protected]6d81b482011-02-22 19:47:194119 EXPECT_EQ(test_server.host_port_pair().host(),
4120 r.GetSocketAddress().host());
4121 EXPECT_EQ(test_server.host_port_pair().port(),
4122 r.GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:464123 }
[email protected]ea224582008-12-07 20:25:464124}
4125
[email protected]5774ada2010-07-15 06:30:544126TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]295e5cd2012-08-23 01:05:124127 TestServer::SSLOptions ssl_options(
4128 TestServer::SSLOptions::CERT_MISMATCHED_NAME);
4129 TestServer test_server(TestServer::TYPE_HTTPS,
4130 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154131 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:114132 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:334133
4134 bool err_allowed = true;
4135 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
4136 TestDelegate d;
4137 {
4138 d.set_allow_certificate_errors(err_allowed);
[email protected]94e2bbe2012-06-22 15:26:134139 URLRequest r(test_server.GetURL(""), &d, &default_context_);
[email protected]bacff652009-03-31 17:50:334140
4141 r.Start();
4142 EXPECT_TRUE(r.is_pending());
4143
4144 MessageLoop::current()->Run();
4145
4146 EXPECT_EQ(1, d.response_started_count());
4147 EXPECT_FALSE(d.received_data_before_response());
4148 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:174149 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:334150 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174151 CheckSSLInfo(r.ssl_info());
4152 } else {
[email protected]bacff652009-03-31 17:50:334153 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174154 }
[email protected]bacff652009-03-31 17:50:334155 }
4156 }
4157}
4158
[email protected]5774ada2010-07-15 06:30:544159TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]295e5cd2012-08-23 01:05:124160 TestServer::SSLOptions ssl_options(
4161 TestServer::SSLOptions::CERT_EXPIRED);
4162 TestServer test_server(TestServer::TYPE_HTTPS,
4163 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154164 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:114165 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:334166
4167 // Iterate from false to true, just so that we do the opposite of the
4168 // previous test in order to increase test coverage.
4169 bool err_allowed = false;
4170 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
4171 TestDelegate d;
4172 {
4173 d.set_allow_certificate_errors(err_allowed);
[email protected]94e2bbe2012-06-22 15:26:134174 URLRequest r(test_server.GetURL(""), &d, &default_context_);
[email protected]bacff652009-03-31 17:50:334175
4176 r.Start();
4177 EXPECT_TRUE(r.is_pending());
4178
4179 MessageLoop::current()->Run();
4180
4181 EXPECT_EQ(1, d.response_started_count());
4182 EXPECT_FALSE(d.received_data_before_response());
4183 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:174184 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:334185 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174186 CheckSSLInfo(r.ssl_info());
4187 } else {
[email protected]bacff652009-03-31 17:50:334188 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174189 }
[email protected]bacff652009-03-31 17:50:334190 }
4191 }
4192}
[email protected]73e0bba2009-02-19 22:57:094193
[email protected]316c1e5e2012-09-12 15:17:444194// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
4195// than necessary.
4196TEST_F(HTTPSRequestTest, TLSv1Fallback) {
4197 uint16 default_version_max = SSLConfigService::default_version_max();
4198 // The OpenSSL library in use may not support TLS 1.1.
4199#if !defined(USE_OPENSSL)
4200 EXPECT_GT(default_version_max, SSL_PROTOCOL_VERSION_TLS1);
4201#endif
4202 if (default_version_max <= SSL_PROTOCOL_VERSION_TLS1)
4203 return;
4204
4205 TestServer::SSLOptions ssl_options(
4206 TestServer::SSLOptions::CERT_OK);
4207 ssl_options.tls_intolerant =
4208 TestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
4209 TestServer test_server(TestServer::TYPE_HTTPS,
4210 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154211 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:444212 ASSERT_TRUE(test_server.Start());
4213
4214 TestDelegate d;
4215 TestURLRequestContext context(true);
4216 context.Init();
4217 d.set_allow_certificate_errors(true);
4218 URLRequest r(test_server.GetURL(""), &d, &context);
4219 r.Start();
4220
4221 MessageLoop::current()->Run();
4222
4223 EXPECT_EQ(1, d.response_started_count());
4224 EXPECT_NE(0, d.bytes_received());
4225 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
4226 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
4227 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
4228}
4229
4230// This tests that a load of www.google.com with a certificate error sets
4231// the |certificate_errors_are_fatal| flag correctly. This flag will cause
4232// the interstitial to be fatal.
4233TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
4234 TestServer::SSLOptions ssl_options(
4235 TestServer::SSLOptions::CERT_MISMATCHED_NAME);
4236 TestServer test_server(TestServer::TYPE_HTTPS,
4237 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154238 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:444239 ASSERT_TRUE(test_server.Start());
4240
4241 // We require that the URL be www.google.com in order to pick up the
4242 // preloaded HSTS entries in the TransportSecurityState. This means that we
4243 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:244244 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:444245
4246 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:244247 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:444248 TestURLRequestContext context(true);
4249 context.set_network_delegate(&network_delegate);
4250 context.set_host_resolver(&host_resolver);
4251 TransportSecurityState transport_security_state;
4252 context.set_transport_security_state(&transport_security_state);
4253 context.Init();
4254
4255 TestDelegate d;
4256 URLRequest r(GURL(StringPrintf("https://www.google.com:%d",
4257 test_server.host_port_pair().port())),
4258 &d,
4259 &context);
4260
4261 r.Start();
4262 EXPECT_TRUE(r.is_pending());
4263
4264 MessageLoop::current()->Run();
4265
4266 EXPECT_EQ(1, d.response_started_count());
4267 EXPECT_FALSE(d.received_data_before_response());
4268 EXPECT_TRUE(d.have_certificate_errors());
4269 EXPECT_TRUE(d.certificate_errors_are_fatal());
4270}
4271
4272// This tests that cached HTTPS page loads do not cause any updates to the
4273// TransportSecurityState.
4274TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
4275 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
4276 // matter. It just has to be any error.
4277 TestServer::SSLOptions ssl_options(
4278 TestServer::SSLOptions::CERT_MISMATCHED_NAME);
4279 TestServer test_server(TestServer::TYPE_HTTPS,
4280 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154281 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:444282 ASSERT_TRUE(test_server.Start());
4283
4284 // We require that the URL be www.google.com in order to pick up the
4285 // preloaded and dynamic HSTS and public key pin entries in the
4286 // TransportSecurityState. This means that we have to use a
4287 // MockHostResolver in order to direct www.google.com to the testserver.
[email protected]ceefd7fd2012-11-29 00:36:244288 // By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:444289
4290 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:244291 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:444292 TestURLRequestContext context(true);
4293 context.set_network_delegate(&network_delegate);
4294 context.set_host_resolver(&host_resolver);
4295 TransportSecurityState transport_security_state;
4296 TransportSecurityState::DomainState domain_state;
4297 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
4298 &domain_state));
4299 context.set_transport_security_state(&transport_security_state);
4300 context.Init();
4301
4302 TestDelegate d;
4303 URLRequest r(GURL(StringPrintf("https://www.google.com:%d",
4304 test_server.host_port_pair().port())),
4305 &d,
4306 &context);
4307
4308 r.Start();
4309 EXPECT_TRUE(r.is_pending());
4310
4311 MessageLoop::current()->Run();
4312
4313 EXPECT_EQ(1, d.response_started_count());
4314 EXPECT_FALSE(d.received_data_before_response());
4315 EXPECT_TRUE(d.have_certificate_errors());
4316 EXPECT_TRUE(d.certificate_errors_are_fatal());
4317
4318 // Get a fresh copy of the state, and check that it hasn't been updated.
4319 TransportSecurityState::DomainState new_domain_state;
4320 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
4321 &new_domain_state));
4322 EXPECT_EQ(new_domain_state.upgrade_mode, domain_state.upgrade_mode);
4323 EXPECT_EQ(new_domain_state.include_subdomains,
4324 domain_state.include_subdomains);
4325 EXPECT_TRUE(FingerprintsEqual(new_domain_state.static_spki_hashes,
4326 domain_state.static_spki_hashes));
4327 EXPECT_TRUE(FingerprintsEqual(new_domain_state.dynamic_spki_hashes,
4328 domain_state.dynamic_spki_hashes));
4329 EXPECT_TRUE(FingerprintsEqual(new_domain_state.bad_static_spki_hashes,
4330 domain_state.bad_static_spki_hashes));
4331}
4332
[email protected]8ccc69f2012-11-28 19:52:144333// Make sure HSTS preserves a POST request's method and body.
4334TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
4335 static const char kData[] = "hello world";
4336
4337 TestServer::SSLOptions ssl_options(TestServer::SSLOptions::CERT_OK);
4338 TestServer test_server(TestServer::TYPE_HTTPS,
4339 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154340 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:144341 ASSERT_TRUE(test_server.Start());
4342
4343
4344 // Per spec, TransportSecurityState expects a domain name, rather than an IP
4345 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ceefd7fd2012-11-29 00:36:244346 // the TestServer. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:144347 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:144348
4349 // Force https for www.somewhere.com.
4350 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:204351 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
4352 bool include_subdomains = false;
4353 transport_security_state.AddHSTS("www.somewhere.com", expiry,
4354 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:144355
4356 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4357
4358 TestURLRequestContext context(true);
4359 context.set_host_resolver(&host_resolver);
4360 context.set_transport_security_state(&transport_security_state);
4361 context.set_network_delegate(&network_delegate);
4362 context.Init();
4363
4364 TestDelegate d;
4365 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
4366 // cause a certificate error. Ignore the error.
4367 d.set_allow_certificate_errors(true);
4368
4369 URLRequest req(GURL(StringPrintf("http://www.somewhere.com:%d/echo",
4370 test_server.host_port_pair().port())),
4371 &d,
4372 &context);
4373 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:284374 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]8ccc69f2012-11-28 19:52:144375
4376 req.Start();
4377 MessageLoop::current()->Run();
4378
4379 EXPECT_EQ("https", req.url().scheme());
4380 EXPECT_EQ("POST", req.method());
4381 EXPECT_EQ(kData, d.data_received());
4382}
4383
[email protected]316c1e5e2012-09-12 15:17:444384TEST_F(HTTPSRequestTest, SSLv3Fallback) {
4385 TestServer::SSLOptions ssl_options(
4386 TestServer::SSLOptions::CERT_OK);
4387 ssl_options.tls_intolerant = TestServer::SSLOptions::TLS_INTOLERANT_ALL;
4388 TestServer test_server(TestServer::TYPE_HTTPS,
4389 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154390 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:444391 ASSERT_TRUE(test_server.Start());
4392
4393 TestDelegate d;
4394 TestURLRequestContext context(true);
4395 context.Init();
4396 d.set_allow_certificate_errors(true);
4397 URLRequest r(test_server.GetURL(""), &d, &context);
4398 r.Start();
4399
4400 MessageLoop::current()->Run();
4401
4402 EXPECT_EQ(1, d.response_started_count());
4403 EXPECT_NE(0, d.bytes_received());
4404 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
4405 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
4406 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
4407}
4408
4409namespace {
4410
4411class SSLClientAuthTestDelegate : public TestDelegate {
4412 public:
4413 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
4414 }
4415 virtual void OnCertificateRequested(
4416 URLRequest* request,
[email protected]46fadfd2013-02-06 09:40:164417 SSLCertRequestInfo* cert_request_info) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:444418 on_certificate_requested_count_++;
4419 MessageLoop::current()->Quit();
4420 }
4421 int on_certificate_requested_count() {
4422 return on_certificate_requested_count_;
4423 }
4424 private:
4425 int on_certificate_requested_count_;
4426};
4427
4428} // namespace
4429
4430// TODO(davidben): Test the rest of the code. Specifically,
4431// - Filtering which certificates to select.
4432// - Sending a certificate back.
4433// - Getting a certificate request in an SSL renegotiation sending the
4434// HTTP request.
4435TEST_F(HTTPSRequestTest, ClientAuthTest) {
4436 TestServer::SSLOptions ssl_options;
4437 ssl_options.request_client_certificate = true;
4438 TestServer test_server(TestServer::TYPE_HTTPS,
4439 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154440 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:444441 ASSERT_TRUE(test_server.Start());
4442
4443 SSLClientAuthTestDelegate d;
4444 {
4445 URLRequest r(test_server.GetURL(""), &d, &default_context_);
4446
4447 r.Start();
4448 EXPECT_TRUE(r.is_pending());
4449
4450 MessageLoop::current()->Run();
4451
4452 EXPECT_EQ(1, d.on_certificate_requested_count());
4453 EXPECT_FALSE(d.received_data_before_response());
4454 EXPECT_EQ(0, d.bytes_received());
4455
4456 // Send no certificate.
4457 // TODO(davidben): Get temporary client cert import (with keys) working on
4458 // all platforms so we can test sending a cert as well.
4459 r.ContinueWithCertificate(NULL);
4460
4461 MessageLoop::current()->Run();
4462
4463 EXPECT_EQ(1, d.response_started_count());
4464 EXPECT_FALSE(d.received_data_before_response());
4465 EXPECT_NE(0, d.bytes_received());
4466 }
4467}
4468
4469TEST_F(HTTPSRequestTest, ResumeTest) {
4470 // Test that we attempt a session resume when making two connections to the
4471 // same host.
4472 TestServer::SSLOptions ssl_options;
4473 ssl_options.record_resume = true;
4474 TestServer test_server(TestServer::TYPE_HTTPS,
4475 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154476 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:444477 ASSERT_TRUE(test_server.Start());
4478
4479 SSLClientSocket::ClearSessionCache();
4480
4481 {
4482 TestDelegate d;
4483 URLRequest r(
4484 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
4485
4486 r.Start();
4487 EXPECT_TRUE(r.is_pending());
4488
4489 MessageLoop::current()->Run();
4490
4491 EXPECT_EQ(1, d.response_started_count());
4492 }
4493
4494 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
4495 CloseAllConnections();
4496
4497 {
4498 TestDelegate d;
4499 URLRequest r(
4500 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
4501
4502 r.Start();
4503 EXPECT_TRUE(r.is_pending());
4504
4505 MessageLoop::current()->Run();
4506
4507 // The response will look like;
4508 // insert abc
4509 // lookup abc
4510 // insert xyz
4511 //
4512 // With a newline at the end which makes the split think that there are
4513 // four lines.
4514
4515 EXPECT_EQ(1, d.response_started_count());
4516 std::vector<std::string> lines;
4517 base::SplitString(d.data_received(), '\n', &lines);
4518 ASSERT_EQ(4u, lines.size()) << d.data_received();
4519
4520 std::string session_id;
4521
4522 for (size_t i = 0; i < 2; i++) {
4523 std::vector<std::string> parts;
4524 base::SplitString(lines[i], '\t', &parts);
4525 ASSERT_EQ(2u, parts.size());
4526 if (i == 0) {
4527 EXPECT_EQ("insert", parts[0]);
4528 session_id = parts[1];
4529 } else {
4530 EXPECT_EQ("lookup", parts[0]);
4531 EXPECT_EQ(session_id, parts[1]);
4532 }
4533 }
4534 }
4535}
4536
4537TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
4538 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
4539 // differs.
4540 TestServer::SSLOptions ssl_options;
4541 ssl_options.record_resume = true;
4542 TestServer test_server(TestServer::TYPE_HTTPS,
4543 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154544 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:444545 ASSERT_TRUE(test_server.Start());
4546
4547 SSLClientSocket::ClearSessionCache();
4548
4549 {
4550 TestDelegate d;
4551 URLRequest r(
4552 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
4553
4554 r.Start();
4555 EXPECT_TRUE(r.is_pending());
4556
4557 MessageLoop::current()->Run();
4558
4559 EXPECT_EQ(1, d.response_started_count());
4560 }
4561
4562 // Now create a new HttpCache with a different ssl_session_cache_shard value.
4563 HttpNetworkSession::Params params;
4564 params.host_resolver = default_context_.host_resolver();
4565 params.cert_verifier = default_context_.cert_verifier();
4566 params.proxy_service = default_context_.proxy_service();
4567 params.ssl_config_service = default_context_.ssl_config_service();
4568 params.http_auth_handler_factory =
4569 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:414570 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:444571 params.http_server_properties = default_context_.http_server_properties();
4572 params.ssl_session_cache_shard = "alternate";
4573
4574 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
4575 new net::HttpNetworkSession(params),
4576 net::HttpCache::DefaultBackend::InMemory(0)));
4577
4578 default_context_.set_http_transaction_factory(cache.get());
4579
4580 {
4581 TestDelegate d;
4582 URLRequest r(
4583 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
4584
4585 r.Start();
4586 EXPECT_TRUE(r.is_pending());
4587
4588 MessageLoop::current()->Run();
4589
4590 // The response will look like;
4591 // insert abc
4592 // insert xyz
4593 //
4594 // With a newline at the end which makes the split think that there are
4595 // three lines.
4596
4597 EXPECT_EQ(1, d.response_started_count());
4598 std::vector<std::string> lines;
4599 base::SplitString(d.data_received(), '\n', &lines);
4600 ASSERT_EQ(3u, lines.size());
4601
4602 std::string session_id;
4603 for (size_t i = 0; i < 2; i++) {
4604 std::vector<std::string> parts;
4605 base::SplitString(lines[i], '\t', &parts);
4606 ASSERT_EQ(2u, parts.size());
4607 EXPECT_EQ("insert", parts[0]);
4608 if (i == 0) {
4609 session_id = parts[1];
4610 } else {
4611 EXPECT_NE(session_id, parts[1]);
4612 }
4613 }
4614 }
4615}
4616
[email protected]a13234c2012-03-20 21:45:024617class TestSSLConfigService : public SSLConfigService {
[email protected]dffe8242012-03-20 15:14:274618 public:
[email protected]a13234c2012-03-20 21:45:024619 TestSSLConfigService(bool ev_enabled, bool online_rev_checking)
4620 : ev_enabled_(ev_enabled),
4621 online_rev_checking_(online_rev_checking) {
4622 }
4623
[email protected]a9813302012-04-28 09:29:284624 // SSLConfigService:
4625 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
[email protected]dffe8242012-03-20 15:14:274626 *config = SSLConfig();
[email protected]a13234c2012-03-20 21:45:024627 config->rev_checking_enabled = online_rev_checking_;
4628 config->verify_ev_cert = ev_enabled_;
[email protected]dffe8242012-03-20 15:14:274629 }
[email protected]a13234c2012-03-20 21:45:024630
[email protected]a9813302012-04-28 09:29:284631 protected:
4632 virtual ~TestSSLConfigService() {}
4633
[email protected]a13234c2012-03-20 21:45:024634 private:
4635 const bool ev_enabled_;
4636 const bool online_rev_checking_;
[email protected]dffe8242012-03-20 15:14:274637};
4638
4639// This the fingerprint of the "Testing CA" certificate used by the testserver.
4640// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:264641static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:274642 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
4643 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
4644
4645// This is the policy OID contained in the certificates that testserver
4646// generates.
4647static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
4648
4649class HTTPSOCSPTest : public HTTPSRequestTest {
4650 public:
4651 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:094652 : context_(true),
[email protected]b6f2de32012-08-17 04:35:084653 ev_test_policy_(
4654 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
4655 kOCSPTestCertFingerprint,
4656 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:024657 }
4658
4659 virtual void SetUp() OVERRIDE {
[email protected]ef2bf422012-05-11 03:27:094660 SetupContext(&context_);
4661 context_.Init();
[email protected]dffe8242012-03-20 15:14:274662
4663 scoped_refptr<net::X509Certificate> root_cert =
4664 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
4665 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
4666 test_root_.reset(new ScopedTestRoot(root_cert));
4667
[email protected]a592c0432012-12-01 18:10:294668#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:094669 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:274670 EnsureNSSHttpIOInit();
4671#endif
4672 }
4673
[email protected]295e5cd2012-08-23 01:05:124674 void DoConnection(const TestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:274675 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:534676 // We always overwrite out_cert_status.
4677 *out_cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:124678 TestServer test_server(TestServer::TYPE_HTTPS,
4679 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154680 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:274681 ASSERT_TRUE(test_server.Start());
4682
4683 TestDelegate d;
4684 d.set_allow_certificate_errors(true);
[email protected]94e2bbe2012-06-22 15:26:134685 URLRequest r(test_server.GetURL(""), &d, &context_);
[email protected]dffe8242012-03-20 15:14:274686 r.Start();
4687
4688 MessageLoop::current()->Run();
4689
4690 EXPECT_EQ(1, d.response_started_count());
4691 *out_cert_status = r.ssl_info().cert_status;
4692 }
4693
[email protected]46fadfd2013-02-06 09:40:164694 virtual ~HTTPSOCSPTest() {
[email protected]a592c0432012-12-01 18:10:294695#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:274696 ShutdownNSSHttpIO();
4697#endif
4698 }
4699
[email protected]a13234c2012-03-20 21:45:024700 protected:
4701 // SetupContext configures the URLRequestContext that will be used for making
4702 // connetions to testserver. This can be overridden in test subclasses for
4703 // different behaviour.
4704 virtual void SetupContext(URLRequestContext* context) {
4705 context->set_ssl_config_service(
4706 new TestSSLConfigService(true /* check for EV */,
4707 true /* online revocation checking */));
4708 }
4709
[email protected]dffe8242012-03-20 15:14:274710 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:094711 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:084712 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:274713};
4714
[email protected]a13234c2012-03-20 21:45:024715static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:014716#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:024717 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
4718 // have that ability on other platforms.
4719 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
4720#else
4721 return 0;
4722#endif
4723}
4724
4725// SystemUsesChromiumEVMetadata returns true iff the current operating system
4726// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
4727// several tests are effected because our testing EV certificate won't be
4728// recognised as EV.
4729static bool SystemUsesChromiumEVMetadata() {
[email protected]5c504192012-03-27 19:00:574730#if defined(USE_OPENSSL)
4731 // http://crbug.com/117478 - OpenSSL does not support EV validation.
4732 return false;
[email protected]a592c0432012-12-01 18:10:294733#elif defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]a13234c2012-03-20 21:45:024734 // On OS X, we use the system to tell us whether a certificate is EV or not
4735 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:014736 return false;
4737#else
4738 return true;
4739#endif
4740}
4741
[email protected]b6f2de32012-08-17 04:35:084742static bool SystemSupportsOCSP() {
[email protected]5c504192012-03-27 19:00:574743#if defined(USE_OPENSSL)
4744 // http://crbug.com/117478 - OpenSSL does not support OCSP.
4745 return false;
4746#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:024747 return base::win::GetVersion() >= base::win::VERSION_VISTA;
4748#elif defined(OS_ANDROID)
4749 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
4750 return false;
4751#else
4752 return true;
4753#endif
4754}
4755
[email protected]dffe8242012-03-20 15:14:274756TEST_F(HTTPSOCSPTest, Valid) {
4757 if (!SystemSupportsOCSP()) {
4758 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
4759 return;
4760 }
4761
[email protected]295e5cd2012-08-23 01:05:124762 TestServer::SSLOptions ssl_options(TestServer::SSLOptions::CERT_AUTO);
4763 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:274764
[email protected]924e9f92012-12-16 22:00:534765 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124766 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:274767
4768 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
4769
[email protected]a13234c2012-03-20 21:45:024770 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
4771 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:274772
4773 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
4774}
4775
4776TEST_F(HTTPSOCSPTest, Revoked) {
4777 if (!SystemSupportsOCSP()) {
4778 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
4779 return;
4780 }
4781
[email protected]295e5cd2012-08-23 01:05:124782 TestServer::SSLOptions ssl_options(
4783 TestServer::SSLOptions::CERT_AUTO);
4784 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:274785
4786 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124787 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:274788
[email protected]a592c0432012-12-01 18:10:294789#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:274790 // Doesn't pass on OS X yet for reasons that need to be investigated.
4791 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
4792#endif
4793 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
4794 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
4795}
4796
4797TEST_F(HTTPSOCSPTest, Invalid) {
4798 if (!SystemSupportsOCSP()) {
4799 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
4800 return;
4801 }
4802
[email protected]295e5cd2012-08-23 01:05:124803 TestServer::SSLOptions ssl_options(
4804 TestServer::SSLOptions::CERT_AUTO);
4805 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:274806
[email protected]924e9f92012-12-16 22:00:534807 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124808 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:274809
[email protected]a13234c2012-03-20 21:45:024810 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:274811 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:274812
4813 // Without a positive OCSP response, we shouldn't show the EV status.
4814 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
4815 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
4816}
[email protected]a13234c2012-03-20 21:45:024817
4818class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
4819 protected:
4820 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
4821 context->set_ssl_config_service(
4822 new TestSSLConfigService(true /* check for EV */,
4823 false /* online revocation checking */));
4824 }
4825};
4826
4827TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
4828 if (!SystemSupportsOCSP()) {
4829 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
4830 return;
4831 }
4832
[email protected]295e5cd2012-08-23 01:05:124833 TestServer::SSLOptions ssl_options(
4834 TestServer::SSLOptions::CERT_AUTO);
4835 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:024836 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
4837
[email protected]924e9f92012-12-16 22:00:534838 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124839 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:024840
4841 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
4842 cert_status & CERT_STATUS_ALL_ERRORS);
4843
4844 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:084845 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
4846 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:024847}
4848
4849TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
4850 if (!SystemSupportsOCSP()) {
4851 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
4852 return;
4853 }
4854
[email protected]295e5cd2012-08-23 01:05:124855 TestServer::SSLOptions ssl_options(
4856 TestServer::SSLOptions::CERT_AUTO);
4857 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:024858 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
4859
4860 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124861 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:024862
4863 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
4864
4865 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
4866 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:084867 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
4868 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:024869}
4870
4871TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
4872 if (!SystemSupportsOCSP()) {
4873 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
4874 return;
4875 }
4876
[email protected]295e5cd2012-08-23 01:05:124877 TestServer::SSLOptions ssl_options(
4878 TestServer::SSLOptions::CERT_AUTO);
4879 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:024880 SSLConfigService::SetCRLSet(
4881 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
4882
4883 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124884 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:024885
4886 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
4887 cert_status & CERT_STATUS_ALL_ERRORS);
4888
4889 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:084890 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
4891 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:024892}
4893
4894TEST_F(HTTPSEVCRLSetTest, FreshCRLSet) {
[email protected]295e5cd2012-08-23 01:05:124895 TestServer::SSLOptions ssl_options(
4896 TestServer::SSLOptions::CERT_AUTO);
4897 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:024898 SSLConfigService::SetCRLSet(
4899 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
4900
[email protected]924e9f92012-12-16 22:00:534901 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124902 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:024903
4904 // With a valid, fresh CRLSet the bad OCSP response shouldn't matter because
4905 // we wont check it.
4906 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
4907
4908 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
4909 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
4910
4911 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
4912}
4913
[email protected]b6f2de32012-08-17 04:35:084914TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
4915 // Test that when EV verification is requested, but online revocation
4916 // checking is disabled, and the leaf certificate is not in fact EV, that
4917 // no revocation checking actually happens.
4918 if (!SystemSupportsOCSP()) {
4919 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
4920 return;
4921 }
4922
4923 // Unmark the certificate's OID as EV, which should disable revocation
4924 // checking (as per the user preference)
4925 ev_test_policy_.reset();
4926
[email protected]295e5cd2012-08-23 01:05:124927 TestServer::SSLOptions ssl_options(
4928 TestServer::SSLOptions::CERT_AUTO);
4929 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:084930 SSLConfigService::SetCRLSet(
4931 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
4932
4933 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124934 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:084935
4936 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
4937
4938 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
4939 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
4940}
4941
[email protected]a13234c2012-03-20 21:45:024942class HTTPSCRLSetTest : public HTTPSOCSPTest {
4943 protected:
4944 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
4945 context->set_ssl_config_service(
4946 new TestSSLConfigService(false /* check for EV */,
4947 false /* online revocation checking */));
4948 }
4949};
4950
4951TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]295e5cd2012-08-23 01:05:124952 TestServer::SSLOptions ssl_options(
4953 TestServer::SSLOptions::CERT_AUTO);
4954 ssl_options.ocsp_status = TestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:024955 SSLConfigService::SetCRLSet(
4956 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
4957
[email protected]924e9f92012-12-16 22:00:534958 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:124959 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:024960
4961 // If we're not trying EV verification then, even if the CRLSet has expired,
4962 // we don't fall back to online revocation checks.
4963 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
4964 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
4965 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
4966}
[email protected]316c1e5e2012-09-12 15:17:444967#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:274968
[email protected]316c1e5e2012-09-12 15:17:444969#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:314970class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:114971 public:
[email protected]d9fca99a2012-02-24 16:16:204972 URLRequestTestFTP()
[email protected]6cdfd7f2013-02-08 20:40:154973 : test_server_(TestServer::TYPE_FTP, TestServer::kLocalhost,
4974 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:114975 }
4976
[email protected]b89ca032009-08-31 21:41:314977 protected:
[email protected]7461a402011-03-24 23:19:514978 TestServer test_server_;
[email protected]b89ca032009-08-31 21:41:314979};
4980
[email protected]d2a133182012-08-05 16:44:084981// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:094982TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:084983 ASSERT_TRUE(test_server_.Start());
4984
[email protected]9d5730b2012-08-24 17:42:494985 URLRequestJobFactoryImpl job_factory;
[email protected]d2a133182012-08-05 16:44:084986
4987 GURL url("ftp://127.0.0.1:7");
4988 FtpProtocolHandler ftp_protocol_handler(
[email protected]d2a133182012-08-05 16:44:084989 default_context_.ftp_transaction_factory(),
4990 default_context_.ftp_auth_cache());
4991 job_factory.SetProtocolHandler(
4992 "ftp",
[email protected]9f170462012-08-24 01:06:584993 new FtpProtocolHandler(default_context_.ftp_transaction_factory(),
[email protected]d2a133182012-08-05 16:44:084994 default_context_.ftp_auth_cache()));
4995 default_context_.set_job_factory(&job_factory);
4996
4997 TestDelegate d;
4998 {
4999 URLRequest r(url, &d, &default_context_);
5000 r.Start();
5001 EXPECT_TRUE(r.is_pending());
5002
5003 MessageLoop::current()->Run();
5004
5005 EXPECT_FALSE(r.is_pending());
5006 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
5007 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
5008 }
5009}
5010
[email protected]5accf7332009-11-24 03:41:385011// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125012TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:115013 ASSERT_TRUE(test_server_.Start());
5014
[email protected]a25e90e2009-09-09 17:05:375015 TestDelegate d;
5016 {
[email protected]94e2bbe2012-06-22 15:26:135017 URLRequest r(test_server_.GetURL("/"), &d, &default_context_);
[email protected]a25e90e2009-09-09 17:05:375018 r.Start();
5019 EXPECT_TRUE(r.is_pending());
5020
5021 MessageLoop::current()->Run();
5022
5023 EXPECT_FALSE(r.is_pending());
5024 EXPECT_EQ(1, d.response_started_count());
5025 EXPECT_FALSE(d.received_data_before_response());
5026 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:195027 EXPECT_EQ(test_server_.host_port_pair().host(),
5028 r.GetSocketAddress().host());
5029 EXPECT_EQ(test_server_.host_port_pair().port(),
5030 r.GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:375031 }
5032}
5033
[email protected]7df70012010-02-04 00:09:555034// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125035TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:115036 ASSERT_TRUE(test_server_.Start());
5037
[email protected]6cdfd7f2013-02-08 20:40:155038 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:275039 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:025040 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:275041 TestDelegate d;
5042 {
[email protected]94e2bbe2012-06-22 15:26:135043 URLRequest r(test_server_.GetURL("/LICENSE"), &d, &default_context_);
[email protected]dd265012009-01-08 20:45:275044 r.Start();
5045 EXPECT_TRUE(r.is_pending());
5046
5047 MessageLoop::current()->Run();
5048
5049 int64 file_size = 0;
5050 file_util::GetFileSize(app_path, &file_size);
5051
[email protected]ba2f3342009-07-30 18:08:425052 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:275053 EXPECT_EQ(1, d.response_started_count());
5054 EXPECT_FALSE(d.received_data_before_response());
5055 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:195056 EXPECT_EQ(test_server_.host_port_pair().host(),
5057 r.GetSocketAddress().host());
5058 EXPECT_EQ(test_server_.host_port_pair().port(),
5059 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:275060 }
5061}
5062
[email protected]e9ecbd12009-12-20 18:44:405063// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125064TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:115065 ASSERT_TRUE(test_server_.Start());
5066
[email protected]6cdfd7f2013-02-08 20:40:155067 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:275068 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:025069 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:275070 TestDelegate d;
5071 {
[email protected]ef2bf422012-05-11 03:27:095072 URLRequest r(
[email protected]95409e12010-08-17 20:07:115073 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]94e2bbe2012-06-22 15:26:135074 &d,
5075 &default_context_);
[email protected]dd265012009-01-08 20:45:275076 r.Start();
5077 EXPECT_TRUE(r.is_pending());
5078
5079 MessageLoop::current()->Run();
5080
5081 int64 file_size = 0;
5082 file_util::GetFileSize(app_path, &file_size);
5083
[email protected]ba2f3342009-07-30 18:08:425084 EXPECT_FALSE(r.is_pending());
[email protected]6d81b482011-02-22 19:47:195085 EXPECT_EQ(test_server_.host_port_pair().host(),
5086 r.GetSocketAddress().host());
5087 EXPECT_EQ(test_server_.host_port_pair().port(),
5088 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:275089 EXPECT_EQ(1, d.response_started_count());
5090 EXPECT_FALSE(d.received_data_before_response());
5091 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:255092
5093 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175094 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255095 TestLoadTimingNoHttpConnection(load_timing_info);
[email protected]dd265012009-01-08 20:45:275096 }
5097}
5098
[email protected]49abd652010-08-05 05:04:535099// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125100TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:115101 ASSERT_TRUE(test_server_.Start());
5102
[email protected]6cdfd7f2013-02-08 20:40:155103 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:275104 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:025105 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:275106 TestDelegate d;
5107 {
[email protected]ef2bf422012-05-11 03:27:095108 URLRequest r(
[email protected]95409e12010-08-17 20:07:115109 test_server_.GetURLWithUserAndPassword("/LICENSE",
5110 "chrome",
5111 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:135112 &d,
5113 &default_context_);
[email protected]dd265012009-01-08 20:45:275114 r.Start();
5115 EXPECT_TRUE(r.is_pending());
5116
5117 MessageLoop::current()->Run();
5118
5119 int64 file_size = 0;
5120 file_util::GetFileSize(app_path, &file_size);
5121
[email protected]ba2f3342009-07-30 18:08:425122 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:275123 EXPECT_EQ(1, d.response_started_count());
5124 EXPECT_FALSE(d.received_data_before_response());
5125 EXPECT_EQ(d.bytes_received(), 0);
5126 }
5127}
5128
[email protected]cde4e80d2009-10-16 19:58:155129// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125130TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:115131 ASSERT_TRUE(test_server_.Start());
5132
[email protected]6cdfd7f2013-02-08 20:40:155133 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:585134 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
5135 app_path = app_path.AppendASCII("LICENSE");
5136 TestDelegate d;
5137 // Set correct login credentials. The delegate will be asked for them when
5138 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:585139 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:585140 {
[email protected]ef2bf422012-05-11 03:27:095141 URLRequest r(
[email protected]95409e12010-08-17 20:07:115142 test_server_.GetURLWithUserAndPassword("/LICENSE",
5143 "chrome",
5144 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:135145 &d,
5146 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:585147 r.Start();
5148 EXPECT_TRUE(r.is_pending());
5149
5150 MessageLoop::current()->Run();
5151
5152 int64 file_size = 0;
5153 file_util::GetFileSize(app_path, &file_size);
5154
5155 EXPECT_FALSE(r.is_pending());
5156 EXPECT_EQ(1, d.response_started_count());
5157 EXPECT_FALSE(d.received_data_before_response());
5158 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
5159 }
5160}
5161
[email protected]49abd652010-08-05 05:04:535162// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125163TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:115164 ASSERT_TRUE(test_server_.Start());
5165
[email protected]6cdfd7f2013-02-08 20:40:155166 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:275167 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:025168 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:275169 TestDelegate d;
5170 {
[email protected]ef2bf422012-05-11 03:27:095171 URLRequest r(
[email protected]95409e12010-08-17 20:07:115172 test_server_.GetURLWithUserAndPassword("/LICENSE",
5173 "wrong_user",
5174 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:135175 &d,
5176 &default_context_);
[email protected]dd265012009-01-08 20:45:275177 r.Start();
5178 EXPECT_TRUE(r.is_pending());
5179
5180 MessageLoop::current()->Run();
5181
5182 int64 file_size = 0;
5183 file_util::GetFileSize(app_path, &file_size);
5184
[email protected]ba2f3342009-07-30 18:08:425185 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:275186 EXPECT_EQ(1, d.response_started_count());
5187 EXPECT_FALSE(d.received_data_before_response());
5188 EXPECT_EQ(d.bytes_received(), 0);
5189 }
5190}
[email protected]8b8a197d2009-08-26 15:57:585191
[email protected]cde4e80d2009-10-16 19:58:155192// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125193TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:115194 ASSERT_TRUE(test_server_.Start());
5195
[email protected]6cdfd7f2013-02-08 20:40:155196 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:585197 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
5198 app_path = app_path.AppendASCII("LICENSE");
5199 TestDelegate d;
5200 // Set correct login credentials. The delegate will be asked for them when
5201 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:585202 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:585203 {
[email protected]ef2bf422012-05-11 03:27:095204 URLRequest r(
[email protected]95409e12010-08-17 20:07:115205 test_server_.GetURLWithUserAndPassword("/LICENSE",
5206 "wrong_user",
5207 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:135208 &d,
5209 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:585210 r.Start();
5211 EXPECT_TRUE(r.is_pending());
5212
5213 MessageLoop::current()->Run();
5214
5215 int64 file_size = 0;
5216 file_util::GetFileSize(app_path, &file_size);
5217
5218 EXPECT_FALSE(r.is_pending());
5219 EXPECT_EQ(1, d.response_started_count());
5220 EXPECT_FALSE(d.received_data_before_response());
5221 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
5222 }
5223}
[email protected]60a3df52009-09-22 16:13:245224
[email protected]cde4e80d2009-10-16 19:58:155225// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125226TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:115227 ASSERT_TRUE(test_server_.Start());
5228
[email protected]6cdfd7f2013-02-08 20:40:155229 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:245230 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
5231 app_path = app_path.AppendASCII("LICENSE");
5232
5233 scoped_ptr<TestDelegate> d(new TestDelegate);
5234 {
5235 // Pass correct login identity in the URL.
[email protected]ef2bf422012-05-11 03:27:095236 URLRequest r(
[email protected]95409e12010-08-17 20:07:115237 test_server_.GetURLWithUserAndPassword("/LICENSE",
5238 "chrome",
5239 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:135240 d.get(),
5241 &default_context_);
[email protected]60a3df52009-09-22 16:13:245242 r.Start();
5243 EXPECT_TRUE(r.is_pending());
5244
5245 MessageLoop::current()->Run();
5246
5247 int64 file_size = 0;
5248 file_util::GetFileSize(app_path, &file_size);
5249
5250 EXPECT_FALSE(r.is_pending());
5251 EXPECT_EQ(1, d->response_started_count());
5252 EXPECT_FALSE(d->received_data_before_response());
5253 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
5254 }
5255
5256 d.reset(new TestDelegate);
5257 {
5258 // This request should use cached identity from previous request.
[email protected]94e2bbe2012-06-22 15:26:135259 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_);
[email protected]60a3df52009-09-22 16:13:245260 r.Start();
5261 EXPECT_TRUE(r.is_pending());
5262
5263 MessageLoop::current()->Run();
5264
5265 int64 file_size = 0;
5266 file_util::GetFileSize(app_path, &file_size);
5267
5268 EXPECT_FALSE(r.is_pending());
5269 EXPECT_EQ(1, d->response_started_count());
5270 EXPECT_FALSE(d->received_data_before_response());
5271 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
5272 }
5273}
5274
[email protected]cde4e80d2009-10-16 19:58:155275// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125276TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:115277 ASSERT_TRUE(test_server_.Start());
5278
[email protected]6cdfd7f2013-02-08 20:40:155279 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:245280 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
5281 app_path = app_path.AppendASCII("LICENSE");
5282
5283 scoped_ptr<TestDelegate> d(new TestDelegate);
5284 // Set correct login credentials. The delegate will be asked for them when
5285 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:585286 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:245287 {
[email protected]ef2bf422012-05-11 03:27:095288 URLRequest r(
[email protected]95409e12010-08-17 20:07:115289 test_server_.GetURLWithUserAndPassword("/LICENSE",
5290 "chrome",
5291 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:135292 d.get(),
5293 &default_context_);
[email protected]60a3df52009-09-22 16:13:245294 r.Start();
5295 EXPECT_TRUE(r.is_pending());
5296
5297 MessageLoop::current()->Run();
5298
5299 int64 file_size = 0;
5300 file_util::GetFileSize(app_path, &file_size);
5301
5302 EXPECT_FALSE(r.is_pending());
5303 EXPECT_EQ(1, d->response_started_count());
5304 EXPECT_FALSE(d->received_data_before_response());
5305 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
5306 }
5307
5308 // Use a new delegate without explicit credentials. The cached ones should be
5309 // used.
5310 d.reset(new TestDelegate);
5311 {
5312 // Don't pass wrong credentials in the URL, they would override valid cached
5313 // ones.
[email protected]94e2bbe2012-06-22 15:26:135314 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_);
[email protected]60a3df52009-09-22 16:13:245315 r.Start();
5316 EXPECT_TRUE(r.is_pending());
5317
5318 MessageLoop::current()->Run();
5319
5320 int64 file_size = 0;
5321 file_util::GetFileSize(app_path, &file_size);
5322
5323 EXPECT_FALSE(r.is_pending());
5324 EXPECT_EQ(1, d->response_started_count());
5325 EXPECT_FALSE(d->received_data_before_response());
5326 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
5327 }
5328}
[email protected]316c1e5e2012-09-12 15:17:445329#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:515330
5331} // namespace net