blob: 79e7967d11b233310600685832d5e2aba3332917 [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]3ca8b362013-11-11 22:18:0719#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2820#include "base/format_macros.h"
[email protected]084262c2011-12-01 21:12:4721#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2222#include "base/message_loop/message_loop.h"
[email protected]255620da2013-08-19 13:14:2923#include "base/message_loop/message_loop_proxy.h"
initial.commit586acc5fe2008-07-26 22:42:5224#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2925#include "base/run_loop.h"
[email protected]4dc3ad4f2013-06-11 07:15:5026#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5527#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2228#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2229#include "base/strings/string_util.h"
30#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0531#include "base/strings/utf_string_conversions.h"
[email protected]58e32bb2013-01-21 18:23:2532#include "net/base/capturing_net_log.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]d8eb84242010-09-25 02:25:0636#include "net/base/net_errors.h"
[email protected]9e743cd2010-03-16 07:03:5337#include "net/base/net_log.h"
38#include "net/base/net_log_unittest.h"
initial.commit586acc5fe2008-07-26 22:42:5239#include "net/base/net_module.h"
40#include "net/base/net_util.h"
[email protected]2ca01e52013-10-31 22:05:1941#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4042#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2843#include "net/base/upload_bytes_element_reader.h"
44#include "net/base/upload_data_stream.h"
45#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1146#include "net/cert/ev_root_ca_metadata.h"
47#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0648#include "net/cookies/cookie_monster.h"
49#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5250#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5351#include "net/dns/mock_host_resolver.h"
[email protected]ba2f3342009-07-30 18:08:4252#include "net/ftp/ftp_network_layer.h"
[email protected]b7572ea2013-11-26 20:16:3853#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "net/http/http_cache.h"
55#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1956#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2557#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2158#include "net/http/http_response_headers.h"
[email protected]dffe8242012-03-20 15:14:2759#include "net/ocsp/nss_ocsp.h"
[email protected]63de95b2008-12-10 04:11:2760#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1961#include "net/socket/ssl_client_socket.h"
[email protected]536fd0b2013-03-14 17:41:5762#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1163#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2164#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3465#include "net/url_request/data_protocol_handler.h"
66#include "net/url_request/file_protocol_handler.h"
[email protected]d2a133182012-08-05 16:44:0867#include "net/url_request/ftp_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4368#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5269#include "net/url_request/url_request.h"
[email protected]7886a8c2009-08-21 04:11:0970#include "net/url_request/url_request_file_dir_job.h"
[email protected]bcb84f8b2009-08-31 16:20:1471#include "net/url_request/url_request_http_job.h"
[email protected]9d5730b2012-08-24 17:42:4972#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5173#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4774#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4475#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5276#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1577#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5278
[email protected]dffe8242012-03-20 15:14:2779#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:4880#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:5681#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:2782#include "base/win/windows_version.h"
83#endif
84
[email protected]e1acf6f2008-10-27 20:43:3385using base::Time;
86
[email protected]7461a402011-03-24 23:19:5187namespace net {
88
initial.commit586acc5fe2008-07-26 22:42:5289namespace {
90
[email protected]42cba2fb2013-03-29 19:58:5791const base::string16 kChrome(ASCIIToUTF16("chrome"));
92const base::string16 kSecret(ASCIIToUTF16("secret"));
93const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:4494
[email protected]2bba3252013-04-08 19:50:5995// Tests load timing information in the case a fresh connection was used, with
96// no proxy.
[email protected]58e32bb2013-01-21 18:23:2597void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
98 int connect_timing_flags) {
99 EXPECT_FALSE(load_timing_info.socket_reused);
100 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
101
102 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
103 EXPECT_FALSE(load_timing_info.request_start.is_null());
104
105 EXPECT_LE(load_timing_info.request_start,
106 load_timing_info.connect_timing.connect_start);
107 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
108 connect_timing_flags);
109 EXPECT_LE(load_timing_info.connect_timing.connect_end,
110 load_timing_info.send_start);
111 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
112 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
113
[email protected]58e32bb2013-01-21 18:23:25114 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
115 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
116}
117
[email protected]2bba3252013-04-08 19:50:59118// Same as above, but with proxy times.
119void TestLoadTimingNotReusedWithProxy(
120 const net::LoadTimingInfo& load_timing_info,
121 int connect_timing_flags) {
122 EXPECT_FALSE(load_timing_info.socket_reused);
123 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
124
125 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
126 EXPECT_FALSE(load_timing_info.request_start.is_null());
127
128 EXPECT_LE(load_timing_info.request_start,
129 load_timing_info.proxy_resolve_start);
130 EXPECT_LE(load_timing_info.proxy_resolve_start,
131 load_timing_info.proxy_resolve_end);
132 EXPECT_LE(load_timing_info.proxy_resolve_end,
133 load_timing_info.connect_timing.connect_start);
134 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
135 connect_timing_flags);
136 EXPECT_LE(load_timing_info.connect_timing.connect_end,
137 load_timing_info.send_start);
138 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
139 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
140}
141
142// Same as above, but with a reused socket and proxy times.
143void TestLoadTimingReusedWithProxy(
144 const net::LoadTimingInfo& load_timing_info) {
145 EXPECT_TRUE(load_timing_info.socket_reused);
146 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
147
148 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
149 EXPECT_FALSE(load_timing_info.request_start.is_null());
150
151 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
152
153 EXPECT_LE(load_timing_info.request_start,
154 load_timing_info.proxy_resolve_start);
155 EXPECT_LE(load_timing_info.proxy_resolve_start,
156 load_timing_info.proxy_resolve_end);
157 EXPECT_LE(load_timing_info.proxy_resolve_end,
158 load_timing_info.send_start);
159 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
160 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
161}
162
[email protected]3b23a222013-05-15 21:33:25163// Tests load timing information in the case of a cache hit, when no cache
164// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17165base::StringPiece TestNetResourceProvider(int key) {
166 return "header";
167}
168
169void FillBuffer(char* buffer, size_t len) {
170 static bool called = false;
171 if (!called) {
172 called = true;
173 int seed = static_cast<int>(Time::Now().ToInternalValue());
174 srand(seed);
175 }
176
177 for (size_t i = 0; i < len; i++) {
178 buffer[i] = static_cast<char>(rand());
179 if (!buffer[i])
180 buffer[i] = 'g';
181 }
182}
183
184#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25185void TestLoadTimingCacheHitNoNetwork(
186 const net::LoadTimingInfo& load_timing_info) {
187 EXPECT_FALSE(load_timing_info.socket_reused);
188 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
189
190 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
191 EXPECT_FALSE(load_timing_info.request_start.is_null());
192
193 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
194 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
195 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
196 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
197
198 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
199 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
200}
201
202// Tests load timing in the case that there is no HTTP response. This can be
203// used to test in the case of errors or non-HTTP requests.
204void TestLoadTimingNoHttpResponse(
[email protected]58e32bb2013-01-21 18:23:25205 const net::LoadTimingInfo& load_timing_info) {
206 EXPECT_FALSE(load_timing_info.socket_reused);
207 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
208
209 // Only the request times should be non-null.
210 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
211 EXPECT_FALSE(load_timing_info.request_start.is_null());
212
213 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
214
215 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
216 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
217 EXPECT_TRUE(load_timing_info.send_start.is_null());
218 EXPECT_TRUE(load_timing_info.send_end.is_null());
219 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
220}
221
[email protected]71c64f62008-11-15 04:36:51222// Do a case-insensitive search through |haystack| for |needle|.
223bool ContainsString(const std::string& haystack, const char* needle) {
224 std::string::const_iterator it =
225 std::search(haystack.begin(),
226 haystack.end(),
227 needle,
228 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35229 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51230 return it != haystack.end();
231}
232
[email protected]f288ef02012-12-15 20:28:28233UploadDataStream* CreateSimpleUploadData(const char* data) {
234 scoped_ptr<UploadElementReader> reader(
235 new UploadBytesElementReader(data, strlen(data)));
236 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23237}
238
[email protected]96adadb2010-08-28 01:16:17239// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51240void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]89af3d92010-10-15 20:31:37241 // Allow ChromeFrame fake SSLInfo to get through.
[email protected]c679be22010-08-29 15:20:05242 if (ssl_info.cert.get() &&
[email protected]89af3d92010-10-15 20:31:37243 ssl_info.cert.get()->issuer().GetDisplayName() == "Chrome Internal") {
244 // -1 means unknown.
245 EXPECT_EQ(ssl_info.security_bits, -1);
[email protected]c679be22010-08-29 15:20:05246 return;
[email protected]89af3d92010-10-15 20:31:37247 }
248
[email protected]96adadb2010-08-28 01:16:17249 // -1 means unknown. 0 means no encryption.
250 EXPECT_GT(ssl_info.security_bits, 0);
251
252 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
[email protected]7461a402011-03-24 23:19:51253 int cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17254 ssl_info.connection_status);
255 EXPECT_NE(0, cipher_suite);
256}
257
[email protected]79e1fd62013-06-20 06:50:04258void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
259 const GURL& host_url) {
260 std::string sent_value;
261
262 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
263 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
264
265 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
266 EXPECT_EQ("keep-alive", sent_value);
267}
268
[email protected]ede03212012-09-07 12:52:26269bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27270 size_t size = a.size();
271
272 if (size != b.size())
273 return false;
274
275 for (size_t i = 0; i < size; ++i) {
276 if (!a[i].Equals(b[i]))
277 return false;
278 }
279
280 return true;
281}
[email protected]e3a85452013-11-14 01:46:17282#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27283
[email protected]dc5a5cf2012-09-26 02:49:30284// A network delegate that allows the user to choose a subset of request stages
285// to block in. When blocking, the delegate can do one of the following:
286// * synchronously return a pre-specified error code, or
287// * asynchronously return that value via an automatically called callback,
288// or
289// * block and wait for the user to do a callback.
290// Additionally, the user may also specify a redirect URL -- then each request
291// with the current URL different from the redirect target will be redirected
292// to that target, in the on-before-URL-request stage, independent of whether
293// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12294class BlockingNetworkDelegate : public TestNetworkDelegate {
295 public:
[email protected]dc5a5cf2012-09-26 02:49:30296 // Stages in which the delegate can block.
297 enum Stage {
[email protected]9045b8822012-01-13 20:35:35298 NOT_BLOCKED = 0,
299 ON_BEFORE_URL_REQUEST = 1 << 0,
300 ON_BEFORE_SEND_HEADERS = 1 << 1,
301 ON_HEADERS_RECEIVED = 1 << 2,
302 ON_AUTH_REQUIRED = 1 << 3
303 };
304
[email protected]dc5a5cf2012-09-26 02:49:30305 // Behavior during blocked stages. During other stages, just
306 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
307 enum BlockMode {
308 SYNCHRONOUS, // No callback, returns specified return values.
309 AUTO_CALLBACK, // |this| posts a task to run the callback using the
310 // specified return codes.
311 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
312 // |auth_retval_| are ignored. In every blocking stage the
313 // message loop is quit.
314 };
315
316 // Creates a delegate which does not block at all.
317 explicit BlockingNetworkDelegate(BlockMode block_mode);
318
319 // For users to trigger a callback returning |response|.
320 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
321 // Only call if |block_mode_| == USER_CALLBACK.
322 void DoCallback(int response);
323 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
324
325 // Setters.
326 void set_retval(int retval) {
327 ASSERT_NE(USER_CALLBACK, block_mode_);
328 ASSERT_NE(ERR_IO_PENDING, retval);
329 ASSERT_NE(OK, retval);
330 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35331 }
332
[email protected]dc5a5cf2012-09-26 02:49:30333 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
334 // |auth_credentials_| will be passed with the response.
335 void set_auth_retval(AuthRequiredResponse auth_retval) {
336 ASSERT_NE(USER_CALLBACK, block_mode_);
337 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
338 auth_retval_ = auth_retval;
339 }
340 void set_auth_credentials(const AuthCredentials& auth_credentials) {
341 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35342 }
343
[email protected]dc5a5cf2012-09-26 02:49:30344 void set_redirect_url(const GURL& url) {
345 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35346 }
347
[email protected]dc5a5cf2012-09-26 02:49:30348 void set_block_on(int block_on) {
349 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35350 }
351
[email protected]dc5a5cf2012-09-26 02:49:30352 // Allows the user to check in which state did we block.
353 Stage stage_blocked_for_callback() const {
354 EXPECT_EQ(USER_CALLBACK, block_mode_);
355 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35356 }
357
358 private:
[email protected]dc5a5cf2012-09-26 02:49:30359 void RunCallback(int response, const CompletionCallback& callback);
360 void RunAuthCallback(AuthRequiredResponse response,
361 const AuthCallback& callback);
362
[email protected]9045b8822012-01-13 20:35:35363 // TestNetworkDelegate implementation.
364 virtual int OnBeforeURLRequest(URLRequest* request,
365 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30366 GURL* new_url) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35367
368 virtual int OnBeforeSendHeaders(URLRequest* request,
369 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30370 HttpRequestHeaders* headers) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35371
372 virtual int OnHeadersReceived(
373 URLRequest* request,
374 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32375 const HttpResponseHeaders* original_response_headers,
[email protected]dc5a5cf2012-09-26 02:49:30376 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35377
378 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
379 URLRequest* request,
380 const AuthChallengeInfo& auth_info,
381 const AuthCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30382 AuthCredentials* credentials) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35383
[email protected]dc5a5cf2012-09-26 02:49:30384 // Resets the callbacks and |stage_blocked_for_callback_|.
385 void Reset();
[email protected]9045b8822012-01-13 20:35:35386
[email protected]dc5a5cf2012-09-26 02:49:30387 // Checks whether we should block in |stage|. If yes, returns an error code
388 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
389 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
390
391 // Configuration parameters, can be adjusted by public methods:
392 const BlockMode block_mode_;
393
394 // Values returned on blocking stages when mode is SYNCHRONOUS or
395 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
396 int retval_; // To be returned in non-auth stages.
397 AuthRequiredResponse auth_retval_;
398
399 GURL redirect_url_; // Used if non-empty.
400 int block_on_; // Bit mask: in which stages to block.
401
402 // |auth_credentials_| will be copied to |*target_auth_credential_| on
403 // callback.
404 AuthCredentials auth_credentials_;
405 AuthCredentials* target_auth_credentials_;
406
407 // Internal variables, not set by not the user:
408 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
409 // USER_CALLBACK).
410 Stage stage_blocked_for_callback_;
411
412 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35413 CompletionCallback callback_;
414 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30415
416 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
417
418 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35419};
420
[email protected]dc5a5cf2012-09-26 02:49:30421BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
422 : block_mode_(block_mode),
423 retval_(OK),
424 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
425 block_on_(0),
426 target_auth_credentials_(NULL),
427 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32428 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30429}
430
431void BlockingNetworkDelegate::DoCallback(int response) {
432 ASSERT_EQ(USER_CALLBACK, block_mode_);
433 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
434 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
435 CompletionCallback callback = callback_;
436 Reset();
437 RunCallback(response, callback);
438}
439
440void BlockingNetworkDelegate::DoAuthCallback(
441 NetworkDelegate::AuthRequiredResponse response) {
442 ASSERT_EQ(USER_CALLBACK, block_mode_);
443 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
444 AuthCallback auth_callback = auth_callback_;
445 Reset();
446 RunAuthCallback(response, auth_callback);
447}
448
449void BlockingNetworkDelegate::RunCallback(int response,
450 const CompletionCallback& callback) {
451 callback.Run(response);
452}
453
454void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
455 const AuthCallback& callback) {
456 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
457 ASSERT_TRUE(target_auth_credentials_ != NULL);
458 *target_auth_credentials_ = auth_credentials_;
459 }
460 callback.Run(response);
461}
462
463int BlockingNetworkDelegate::OnBeforeURLRequest(
464 URLRequest* request,
465 const CompletionCallback& callback,
466 GURL* new_url) {
467 if (redirect_url_ == request->url())
468 return OK; // We've already seen this request and redirected elsewhere.
469
470 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
471
472 if (!redirect_url_.is_empty())
473 *new_url = redirect_url_;
474
475 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
476}
477
478int BlockingNetworkDelegate::OnBeforeSendHeaders(
479 URLRequest* request,
480 const CompletionCallback& callback,
481 HttpRequestHeaders* headers) {
482 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
483
484 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
485}
486
487int BlockingNetworkDelegate::OnHeadersReceived(
488 URLRequest* request,
489 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32490 const HttpResponseHeaders* original_response_headers,
[email protected]dc5a5cf2012-09-26 02:49:30491 scoped_refptr<HttpResponseHeaders>* override_response_headers) {
492 TestNetworkDelegate::OnHeadersReceived(
493 request, callback, original_response_headers,
494 override_response_headers);
495
496 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
497}
498
499NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
500 URLRequest* request,
501 const AuthChallengeInfo& auth_info,
502 const AuthCallback& callback,
503 AuthCredentials* credentials) {
504 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
505 credentials);
506 // Check that the user has provided callback for the previous blocked stage.
507 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
508
509 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
510 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
511 }
512
513 target_auth_credentials_ = credentials;
514
515 switch (block_mode_) {
516 case SYNCHRONOUS:
517 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
518 *target_auth_credentials_ = auth_credentials_;
519 return auth_retval_;
520
521 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34522 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30523 FROM_HERE,
524 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
525 weak_factory_.GetWeakPtr(), auth_retval_, callback));
526 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
527
528 case USER_CALLBACK:
529 auth_callback_ = callback;
530 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34531 base::MessageLoop::current()->PostTask(FROM_HERE,
532 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30533 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
534 }
535 NOTREACHED();
536 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
537}
538
539void BlockingNetworkDelegate::Reset() {
540 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
541 stage_blocked_for_callback_ = NOT_BLOCKED;
542 callback_.Reset();
543 auth_callback_.Reset();
544}
545
546int BlockingNetworkDelegate::MaybeBlockStage(
547 BlockingNetworkDelegate::Stage stage,
548 const CompletionCallback& callback) {
549 // Check that the user has provided callback for the previous blocked stage.
550 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
551
552 if ((block_on_ & stage) == 0) {
553 return OK;
554 }
555
556 switch (block_mode_) {
557 case SYNCHRONOUS:
558 EXPECT_NE(OK, retval_);
559 return retval_;
560
561 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34562 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30563 FROM_HERE,
564 base::Bind(&BlockingNetworkDelegate::RunCallback,
565 weak_factory_.GetWeakPtr(), retval_, callback));
566 return ERR_IO_PENDING;
567
568 case USER_CALLBACK:
569 callback_ = callback;
570 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34571 base::MessageLoop::current()->PostTask(FROM_HERE,
572 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30573 return ERR_IO_PENDING;
574 }
575 NOTREACHED();
576 return 0;
577}
578
[email protected]d5a4dd62012-05-23 01:41:04579class TestURLRequestContextWithProxy : public TestURLRequestContext {
580 public:
581 // Does not own |delegate|.
582 TestURLRequestContextWithProxy(const std::string& proxy,
583 NetworkDelegate* delegate)
584 : TestURLRequestContext(true) {
585 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
586 set_network_delegate(delegate);
587 Init();
588 }
589 virtual ~TestURLRequestContextWithProxy() {}
590};
591
592} // namespace
593
[email protected]a592c0432012-12-01 18:10:29594// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48595class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00596 public:
[email protected]ef2bf422012-05-11 03:27:09597 URLRequestTest() : default_context_(true) {
598 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25599 default_context_.set_net_log(&net_log_);
[email protected]e0f35c92013-05-08 16:04:34600 job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
[email protected]255620da2013-08-19 13:14:29601 job_factory_.SetProtocolHandler(
602 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
[email protected]e0f35c92013-05-08 16:04:34603 default_context_.set_job_factory(&job_factory_);
[email protected]ef2bf422012-05-11 03:27:09604 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:50605 }
[email protected]e4034ad2013-09-20 08:36:18606 virtual ~URLRequestTest() {
607 // URLRequestJobs may post clean-up tasks on destruction.
608 base::RunLoop().RunUntilIdle();
609 }
[email protected]87a09a92011-07-14 15:50:50610
[email protected]3c5ca8c2011-09-29 01:14:51611 // Adds the TestJobInterceptor to the default context.
612 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23613 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
[email protected]e0f35c92013-05-08 16:04:34614 job_factory_.SetProtocolHandler("http", NULL);
615 job_factory_.SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23616 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51617 }
618
[email protected]87a09a92011-07-14 15:50:50619 protected:
[email protected]58e32bb2013-01-21 18:23:25620 CapturingNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24621 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]e0f35c92013-05-08 16:04:34622 URLRequestJobFactoryImpl job_factory_;
[email protected]ef2bf422012-05-11 03:27:09623 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48624};
625
[email protected]316c1e5e2012-09-12 15:17:44626TEST_F(URLRequestTest, AboutBlankTest) {
627 TestDelegate d;
628 {
[email protected]2ca01e52013-10-31 22:05:19629 URLRequest r(GURL("about:blank"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44630
631 r.Start();
632 EXPECT_TRUE(r.is_pending());
633
[email protected]255620da2013-08-19 13:14:29634 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44635
636 EXPECT_TRUE(!r.is_pending());
637 EXPECT_FALSE(d.received_data_before_response());
638 EXPECT_EQ(d.bytes_received(), 0);
639 EXPECT_EQ("", r.GetSocketAddress().host());
640 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04641
642 HttpRequestHeaders headers;
643 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44644 }
645}
646
647TEST_F(URLRequestTest, DataURLImageTest) {
648 TestDelegate d;
649 {
650 // Use our nice little Chrome logo.
[email protected]2ca01e52013-10-31 22:05:19651 URLRequest r(
652 GURL(
[email protected]316c1e5e2012-09-12 15:17:44653 "data:image/png;base64,"
654 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
655 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
656 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
657 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
658 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
659 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
660 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
661 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
662 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
663 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
664 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
665 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
666 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
667 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
668 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
669 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
670 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
671 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
[email protected]2ca01e52013-10-31 22:05:19672 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:44673 &d,
674 &default_context_);
675
676 r.Start();
677 EXPECT_TRUE(r.is_pending());
678
[email protected]255620da2013-08-19 13:14:29679 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44680
681 EXPECT_TRUE(!r.is_pending());
682 EXPECT_FALSE(d.received_data_before_response());
683 EXPECT_EQ(d.bytes_received(), 911);
684 EXPECT_EQ("", r.GetSocketAddress().host());
685 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04686
687 HttpRequestHeaders headers;
688 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44689 }
690}
691
692TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15693 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44694 PathService::Get(base::FILE_EXE, &app_path);
695 GURL app_url = FilePathToFileURL(app_path);
696
697 TestDelegate d;
698 {
[email protected]2ca01e52013-10-31 22:05:19699 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44700
701 r.Start();
702 EXPECT_TRUE(r.is_pending());
703
[email protected]255620da2013-08-19 13:14:29704 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44705
706 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49707 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44708
709 EXPECT_TRUE(!r.is_pending());
710 EXPECT_EQ(1, d.response_started_count());
711 EXPECT_FALSE(d.received_data_before_response());
712 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
713 EXPECT_EQ("", r.GetSocketAddress().host());
714 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04715
716 HttpRequestHeaders headers;
717 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44718 }
719}
720
[email protected]ba40bb762012-12-17 07:11:04721TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15722 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04723 PathService::Get(base::FILE_EXE, &app_path);
724 GURL app_url = FilePathToFileURL(app_path);
725
726 TestDelegate d;
727 {
[email protected]2ca01e52013-10-31 22:05:19728 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]ba40bb762012-12-17 07:11:04729
730 r.Start();
731 EXPECT_TRUE(r.is_pending());
732 r.Cancel();
733 }
[email protected]79e1fd62013-06-20 06:50:04734 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04735 // destroyed.
[email protected]255620da2013-08-19 13:14:29736 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04737}
738
[email protected]316c1e5e2012-09-12 15:17:44739TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
740 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17741 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44742 FillBuffer(buffer.get(), buffer_size);
743
[email protected]6cdfd7f2013-02-08 20:40:15744 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52745 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44746 GURL temp_url = FilePathToFileURL(temp_path);
747 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
748
749 int64 file_size;
[email protected]56285702013-12-04 18:22:49750 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44751
752 const size_t first_byte_position = 500;
753 const size_t last_byte_position = buffer_size - first_byte_position;
754 const size_t content_length = last_byte_position - first_byte_position + 1;
755 std::string partial_buffer_string(buffer.get() + first_byte_position,
756 buffer.get() + last_byte_position + 1);
757
758 TestDelegate d;
759 {
[email protected]2ca01e52013-10-31 22:05:19760 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44761
762 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38763 headers.SetHeader(
764 HttpRequestHeaders::kRange,
765 net::HttpByteRange::Bounded(
766 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]316c1e5e2012-09-12 15:17:44767 r.SetExtraRequestHeaders(headers);
768 r.Start();
769 EXPECT_TRUE(r.is_pending());
770
[email protected]255620da2013-08-19 13:14:29771 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44772 EXPECT_TRUE(!r.is_pending());
773 EXPECT_EQ(1, d.response_started_count());
774 EXPECT_FALSE(d.received_data_before_response());
775 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
776 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
777 EXPECT_TRUE(partial_buffer_string == d.data_received());
778 }
779
[email protected]dd3aa792013-07-16 19:10:23780 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44781}
782
783TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
784 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17785 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44786 FillBuffer(buffer.get(), buffer_size);
787
[email protected]6cdfd7f2013-02-08 20:40:15788 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52789 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44790 GURL temp_url = FilePathToFileURL(temp_path);
791 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
792
793 int64 file_size;
[email protected]56285702013-12-04 18:22:49794 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44795
796 const size_t first_byte_position = 500;
797 const size_t last_byte_position = buffer_size - 1;
798 const size_t content_length = last_byte_position - first_byte_position + 1;
799 std::string partial_buffer_string(buffer.get() + first_byte_position,
800 buffer.get() + last_byte_position + 1);
801
802 TestDelegate d;
803 {
[email protected]2ca01e52013-10-31 22:05:19804 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44805
806 HttpRequestHeaders headers;
807 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]b7572ea2013-11-26 20:16:38808 net::HttpByteRange::RightUnbounded(
809 first_byte_position).GetHeaderValue());
[email protected]316c1e5e2012-09-12 15:17:44810 r.SetExtraRequestHeaders(headers);
811 r.Start();
812 EXPECT_TRUE(r.is_pending());
813
[email protected]255620da2013-08-19 13:14:29814 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44815 EXPECT_TRUE(!r.is_pending());
816 EXPECT_EQ(1, d.response_started_count());
817 EXPECT_FALSE(d.received_data_before_response());
818 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
819 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
820 EXPECT_TRUE(partial_buffer_string == d.data_received());
821 }
822
[email protected]dd3aa792013-07-16 19:10:23823 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44824}
825
826TEST_F(URLRequestTest, FileTestMultipleRanges) {
827 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17828 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44829 FillBuffer(buffer.get(), buffer_size);
830
[email protected]6cdfd7f2013-02-08 20:40:15831 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52832 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44833 GURL temp_url = FilePathToFileURL(temp_path);
834 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
835
836 int64 file_size;
[email protected]56285702013-12-04 18:22:49837 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44838
839 TestDelegate d;
840 {
[email protected]2ca01e52013-10-31 22:05:19841 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44842
843 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38844 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]316c1e5e2012-09-12 15:17:44845 r.SetExtraRequestHeaders(headers);
846 r.Start();
847 EXPECT_TRUE(r.is_pending());
848
[email protected]255620da2013-08-19 13:14:29849 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44850 EXPECT_TRUE(d.request_failed());
851 }
852
[email protected]dd3aa792013-07-16 19:10:23853 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44854}
855
[email protected]3ca8b362013-11-11 22:18:07856TEST_F(URLRequestTest, AllowFileURLs) {
857 base::ScopedTempDir temp_dir;
858 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
859 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52860 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07861 std::string test_data("monkey");
862 file_util::WriteFile(test_file, test_data.data(), test_data.size());
863 GURL test_file_url = net::FilePathToFileURL(test_file);
864
865 {
866 TestDelegate d;
867 TestNetworkDelegate network_delegate;
868 network_delegate.set_can_access_files(true);
869 default_context_.set_network_delegate(&network_delegate);
870 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
871 r.Start();
872 base::RunLoop().Run();
873 EXPECT_FALSE(d.request_failed());
874 EXPECT_EQ(test_data, d.data_received());
875 }
876
877 {
878 TestDelegate d;
879 TestNetworkDelegate network_delegate;
880 network_delegate.set_can_access_files(false);
881 default_context_.set_network_delegate(&network_delegate);
882 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
883 r.Start();
884 base::RunLoop().Run();
885 EXPECT_TRUE(d.request_failed());
886 EXPECT_EQ("", d.data_received());
887 }
888}
889
[email protected]316c1e5e2012-09-12 15:17:44890TEST_F(URLRequestTest, InvalidUrlTest) {
891 TestDelegate d;
892 {
[email protected]2ca01e52013-10-31 22:05:19893 URLRequest r(GURL("invalid url"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44894
895 r.Start();
896 EXPECT_TRUE(r.is_pending());
897
[email protected]255620da2013-08-19 13:14:29898 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44899 EXPECT_TRUE(d.request_failed());
900 }
901}
902
903#if defined(OS_WIN)
904TEST_F(URLRequestTest, ResolveShortcutTest) {
[email protected]6cdfd7f2013-02-08 20:40:15905 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44906 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
907 app_path = app_path.AppendASCII("net");
908 app_path = app_path.AppendASCII("data");
909 app_path = app_path.AppendASCII("url_request_unittest");
910 app_path = app_path.AppendASCII("with-headers.html");
911
912 std::wstring lnk_path = app_path.value() + L".lnk";
913
[email protected]451fd902012-10-03 17:14:48914 base::win::ScopedCOMInitializer com_initializer;
[email protected]00d60fa2012-10-01 18:20:17915
[email protected]316c1e5e2012-09-12 15:17:44916 // Temporarily create a shortcut for test
[email protected]aed9efb2013-04-13 01:20:56917 {
918 base::win::ScopedComPtr<IShellLink> shell;
919 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
920 CLSCTX_INPROC_SERVER)));
921 base::win::ScopedComPtr<IPersistFile> persist;
922 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
923 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
924 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
925 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
926 }
[email protected]316c1e5e2012-09-12 15:17:44927
928 TestDelegate d;
929 {
[email protected]2ca01e52013-10-31 22:05:19930 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)),
931 DEFAULT_PRIORITY,
932 &d,
[email protected]6cdfd7f2013-02-08 20:40:15933 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44934
935 r.Start();
936 EXPECT_TRUE(r.is_pending());
937
[email protected]255620da2013-08-19 13:14:29938 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44939
940 WIN32_FILE_ATTRIBUTE_DATA data;
941 GetFileAttributesEx(app_path.value().c_str(),
942 GetFileExInfoStandard, &data);
943 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
944 FILE_SHARE_READ, NULL, OPEN_EXISTING,
945 FILE_ATTRIBUTE_NORMAL, NULL);
946 EXPECT_NE(INVALID_HANDLE_VALUE, file);
[email protected]ec530c22013-04-11 15:54:04947 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]316c1e5e2012-09-12 15:17:44948 DWORD read_size;
949 BOOL result;
950 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
951 &read_size, NULL);
952 std::string content(buffer.get(), read_size);
953 CloseHandle(file);
954
955 EXPECT_TRUE(!r.is_pending());
956 EXPECT_EQ(1, d.received_redirect_count());
957 EXPECT_EQ(content, d.data_received());
958 }
959
960 // Clean the shortcut
961 DeleteFile(lnk_path.c_str());
[email protected]316c1e5e2012-09-12 15:17:44962}
963#endif // defined(OS_WIN)
964
965TEST_F(URLRequestTest, FileDirCancelTest) {
966 // Put in mock resource provider.
967 NetModule::SetResourceProvider(TestNetResourceProvider);
968
969 TestDelegate d;
970 {
[email protected]6cdfd7f2013-02-08 20:40:15971 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44972 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
973 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
974 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
975
[email protected]2ca01e52013-10-31 22:05:19976 URLRequest req(
977 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44978 req.Start();
979 EXPECT_TRUE(req.is_pending());
980
981 d.set_cancel_in_received_data_pending(true);
982
[email protected]255620da2013-08-19 13:14:29983 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44984 }
985
986 // Take out mock resource provider.
987 NetModule::SetResourceProvider(NULL);
988}
989
[email protected]5f9581402013-10-30 13:08:32990TEST_F(URLRequestTest, FileDirOutputSanity) {
991 // Verify the general sanity of the the output of the file:
992 // directory lister by checking for the output of a known existing
993 // file.
994 const char sentinel_name[] = "filedir-sentinel";
995
996 base::FilePath path;
997 PathService::Get(base::DIR_SOURCE_ROOT, &path);
998 path = path.Append(FILE_PATH_LITERAL("net"));
999 path = path.Append(FILE_PATH_LITERAL("data"));
1000 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1001
1002 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191003 URLRequest req(
1004 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]5f9581402013-10-30 13:08:321005 req.Start();
1006 base::RunLoop().Run();
1007
1008 // Generate entry for the sentinel file.
1009 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
1010 base::PlatformFileInfo info;
[email protected]9eae4e62013-12-04 20:56:491011 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321012 EXPECT_GT(info.size, 0);
1013 std::string sentinel_output = GetDirectoryListingEntry(
1014 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1015 std::string(sentinel_name),
1016 false /* is_dir */,
1017 info.size,
1018 info.last_modified);
1019
1020 ASSERT_LT(0, d.bytes_received());
1021 ASSERT_FALSE(d.request_failed());
1022 ASSERT_TRUE(req.status().is_success());
1023 // Check for the entry generated for the "sentinel" file.
1024 const std::string& data = d.data_received();
1025 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1026}
1027
[email protected]316c1e5e2012-09-12 15:17:441028TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1029 // There is an implicit redirect when loading a file path that matches a
1030 // directory and does not end with a slash. Ensure that following such
1031 // redirects does not crash. See http://crbug.com/18686.
1032
[email protected]6cdfd7f2013-02-08 20:40:151033 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441034 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1035 path = path.Append(FILE_PATH_LITERAL("net"));
1036 path = path.Append(FILE_PATH_LITERAL("data"));
1037 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1038
1039 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191040 URLRequest req(
1041 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441042 req.Start();
[email protected]255620da2013-08-19 13:14:291043 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441044
1045 ASSERT_EQ(1, d.received_redirect_count());
1046 ASSERT_LT(0, d.bytes_received());
1047 ASSERT_FALSE(d.request_failed());
1048 ASSERT_TRUE(req.status().is_success());
1049}
1050
1051#if defined(OS_WIN)
1052// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1053TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1054 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191055 URLRequest req(GURL("file:///"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441056 req.Start();
[email protected]255620da2013-08-19 13:14:291057 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441058
1059 ASSERT_EQ(1, d.received_redirect_count());
1060 ASSERT_FALSE(req.status().is_success());
1061}
1062#endif
1063
1064// Custom URLRequestJobs for use with interceptor tests
1065class RestartTestJob : public URLRequestTestJob {
1066 public:
1067 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1068 : URLRequestTestJob(request, network_delegate, true) {}
1069 protected:
[email protected]46fadfd2013-02-06 09:40:161070 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441071 this->NotifyRestartRequired();
1072 }
1073 private:
[email protected]46fadfd2013-02-06 09:40:161074 virtual ~RestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441075};
1076
1077class CancelTestJob : public URLRequestTestJob {
1078 public:
1079 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1080 : URLRequestTestJob(request, network_delegate, true) {}
1081 protected:
[email protected]46fadfd2013-02-06 09:40:161082 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441083 request_->Cancel();
1084 }
1085 private:
[email protected]46fadfd2013-02-06 09:40:161086 virtual ~CancelTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441087};
1088
1089class CancelThenRestartTestJob : public URLRequestTestJob {
1090 public:
1091 explicit CancelThenRestartTestJob(URLRequest* request,
1092 NetworkDelegate* network_delegate)
1093 : URLRequestTestJob(request, network_delegate, true) {
1094 }
1095 protected:
[email protected]46fadfd2013-02-06 09:40:161096 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441097 request_->Cancel();
1098 this->NotifyRestartRequired();
1099 }
1100 private:
[email protected]46fadfd2013-02-06 09:40:161101 virtual ~CancelThenRestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441102};
1103
1104// An Interceptor for use with interceptor tests
1105class TestInterceptor : URLRequest::Interceptor {
1106 public:
1107 TestInterceptor()
1108 : intercept_main_request_(false), restart_main_request_(false),
1109 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1110 simulate_main_network_error_(false),
1111 intercept_redirect_(false), cancel_redirect_request_(false),
1112 intercept_final_response_(false), cancel_final_request_(false),
1113 did_intercept_main_(false), did_restart_main_(false),
1114 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1115 did_simulate_error_main_(false),
1116 did_intercept_redirect_(false), did_cancel_redirect_(false),
1117 did_intercept_final_(false), did_cancel_final_(false) {
1118 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1119 }
1120
[email protected]46fadfd2013-02-06 09:40:161121 virtual ~TestInterceptor() {
[email protected]316c1e5e2012-09-12 15:17:441122 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1123 }
1124
[email protected]46fadfd2013-02-06 09:40:161125 virtual URLRequestJob* MaybeIntercept(
1126 URLRequest* request,
1127 NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441128 if (restart_main_request_) {
1129 restart_main_request_ = false;
1130 did_restart_main_ = true;
1131 return new RestartTestJob(request, network_delegate);
1132 }
1133 if (cancel_main_request_) {
1134 cancel_main_request_ = false;
1135 did_cancel_main_ = true;
1136 return new CancelTestJob(request, network_delegate);
1137 }
1138 if (cancel_then_restart_main_request_) {
1139 cancel_then_restart_main_request_ = false;
1140 did_cancel_then_restart_main_ = true;
1141 return new CancelThenRestartTestJob(request, network_delegate);
1142 }
1143 if (simulate_main_network_error_) {
1144 simulate_main_network_error_ = false;
1145 did_simulate_error_main_ = true;
1146 // will error since the requeted url is not one of its canned urls
1147 return new URLRequestTestJob(request, network_delegate, true);
1148 }
1149 if (!intercept_main_request_)
1150 return NULL;
1151 intercept_main_request_ = false;
1152 did_intercept_main_ = true;
[email protected]2bba3252013-04-08 19:50:591153 URLRequestTestJob* job = new URLRequestTestJob(request,
1154 network_delegate,
1155 main_headers_,
1156 main_data_,
1157 true);
1158 job->set_load_timing_info(main_request_load_timing_info_);
1159 return job;
[email protected]316c1e5e2012-09-12 15:17:441160 }
1161
1162 virtual URLRequestJob* MaybeInterceptRedirect(
1163 URLRequest* request,
1164 NetworkDelegate* network_delegate,
[email protected]46fadfd2013-02-06 09:40:161165 const GURL& location) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441166 if (cancel_redirect_request_) {
1167 cancel_redirect_request_ = false;
1168 did_cancel_redirect_ = true;
1169 return new CancelTestJob(request, network_delegate);
1170 }
1171 if (!intercept_redirect_)
1172 return NULL;
1173 intercept_redirect_ = false;
1174 did_intercept_redirect_ = true;
1175 return new URLRequestTestJob(request,
1176 network_delegate,
1177 redirect_headers_,
1178 redirect_data_,
1179 true);
1180 }
1181
1182 virtual URLRequestJob* MaybeInterceptResponse(
[email protected]46fadfd2013-02-06 09:40:161183 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441184 if (cancel_final_request_) {
1185 cancel_final_request_ = false;
1186 did_cancel_final_ = true;
1187 return new CancelTestJob(request, network_delegate);
1188 }
1189 if (!intercept_final_response_)
1190 return NULL;
1191 intercept_final_response_ = false;
1192 did_intercept_final_ = true;
1193 return new URLRequestTestJob(request,
1194 network_delegate,
1195 final_headers_,
1196 final_data_,
1197 true);
1198 }
1199
[email protected]2bba3252013-04-08 19:50:591200 // Whether to intercept the main request, and if so the response to return and
1201 // the LoadTimingInfo to use.
[email protected]316c1e5e2012-09-12 15:17:441202 bool intercept_main_request_;
1203 std::string main_headers_;
1204 std::string main_data_;
[email protected]2bba3252013-04-08 19:50:591205 LoadTimingInfo main_request_load_timing_info_;
[email protected]316c1e5e2012-09-12 15:17:441206
1207 // Other actions we take at MaybeIntercept time
1208 bool restart_main_request_;
1209 bool cancel_main_request_;
1210 bool cancel_then_restart_main_request_;
1211 bool simulate_main_network_error_;
1212
1213 // Whether to intercept redirects, and if so the response to return.
1214 bool intercept_redirect_;
1215 std::string redirect_headers_;
1216 std::string redirect_data_;
1217
1218 // Other actions we can take at MaybeInterceptRedirect time
1219 bool cancel_redirect_request_;
1220
1221 // Whether to intercept final response, and if so the response to return.
1222 bool intercept_final_response_;
1223 std::string final_headers_;
1224 std::string final_data_;
1225
1226 // Other actions we can take at MaybeInterceptResponse time
1227 bool cancel_final_request_;
1228
1229 // If we did something or not
1230 bool did_intercept_main_;
1231 bool did_restart_main_;
1232 bool did_cancel_main_;
1233 bool did_cancel_then_restart_main_;
1234 bool did_simulate_error_main_;
1235 bool did_intercept_redirect_;
1236 bool did_cancel_redirect_;
1237 bool did_intercept_final_;
1238 bool did_cancel_final_;
1239
1240 // Static getters for canned response header and data strings
1241
1242 static std::string ok_data() {
1243 return URLRequestTestJob::test_data_1();
1244 }
1245
1246 static std::string ok_headers() {
1247 return URLRequestTestJob::test_headers();
1248 }
1249
1250 static std::string redirect_data() {
1251 return std::string();
1252 }
1253
1254 static std::string redirect_headers() {
1255 return URLRequestTestJob::test_redirect_headers();
1256 }
1257
1258 static std::string error_data() {
1259 return std::string("ohhh nooooo mr. bill!");
1260 }
1261
1262 static std::string error_headers() {
1263 return URLRequestTestJob::test_error_headers();
1264 }
1265};
1266
1267TEST_F(URLRequestTest, Intercept) {
1268 TestInterceptor interceptor;
1269
1270 // intercept the main request and respond with a simple response
1271 interceptor.intercept_main_request_ = true;
1272 interceptor.main_headers_ = TestInterceptor::ok_headers();
1273 interceptor.main_data_ = TestInterceptor::ok_data();
1274
1275 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191276 URLRequest req(GURL("http://test_intercept/foo"),
1277 DEFAULT_PRIORITY,
1278 &d,
1279 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441280 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1281 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1282 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1283 req.SetUserData(NULL, user_data0);
1284 req.SetUserData(&user_data1, user_data1);
1285 req.SetUserData(&user_data2, user_data2);
1286 req.set_method("GET");
1287 req.Start();
[email protected]255620da2013-08-19 13:14:291288 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441289
1290 // Make sure we can retrieve our specific user data
1291 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1292 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1293 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1294
1295 // Check the interceptor got called as expected
1296 EXPECT_TRUE(interceptor.did_intercept_main_);
1297
1298 // Check we got one good response
1299 EXPECT_TRUE(req.status().is_success());
1300 EXPECT_EQ(200, req.response_headers()->response_code());
1301 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1302 EXPECT_EQ(1, d.response_started_count());
1303 EXPECT_EQ(0, d.received_redirect_count());
1304}
1305
1306TEST_F(URLRequestTest, InterceptRedirect) {
1307 TestInterceptor interceptor;
1308
1309 // intercept the main request and respond with a redirect
1310 interceptor.intercept_main_request_ = true;
1311 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1312 interceptor.main_data_ = TestInterceptor::redirect_data();
1313
1314 // intercept that redirect and respond a final OK response
1315 interceptor.intercept_redirect_ = true;
1316 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1317 interceptor.redirect_data_ = TestInterceptor::ok_data();
1318
1319 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191320 URLRequest req(GURL("http://test_intercept/foo"),
1321 DEFAULT_PRIORITY,
1322 &d,
1323 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441324 req.set_method("GET");
1325 req.Start();
[email protected]255620da2013-08-19 13:14:291326 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441327
1328 // Check the interceptor got called as expected
1329 EXPECT_TRUE(interceptor.did_intercept_main_);
1330 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1331
1332 // Check we got one good response
1333 EXPECT_TRUE(req.status().is_success());
1334 if (req.status().is_success()) {
1335 EXPECT_EQ(200, req.response_headers()->response_code());
1336 }
1337 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1338 EXPECT_EQ(1, d.response_started_count());
1339 EXPECT_EQ(0, d.received_redirect_count());
1340}
1341
1342TEST_F(URLRequestTest, InterceptServerError) {
1343 TestInterceptor interceptor;
1344
1345 // intercept the main request to generate a server error response
1346 interceptor.intercept_main_request_ = true;
1347 interceptor.main_headers_ = TestInterceptor::error_headers();
1348 interceptor.main_data_ = TestInterceptor::error_data();
1349
1350 // intercept that error and respond with an OK response
1351 interceptor.intercept_final_response_ = true;
1352 interceptor.final_headers_ = TestInterceptor::ok_headers();
1353 interceptor.final_data_ = TestInterceptor::ok_data();
1354
1355 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191356 URLRequest req(GURL("http://test_intercept/foo"),
1357 DEFAULT_PRIORITY,
1358 &d,
1359 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441360 req.set_method("GET");
1361 req.Start();
[email protected]255620da2013-08-19 13:14:291362 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441363
1364 // Check the interceptor got called as expected
1365 EXPECT_TRUE(interceptor.did_intercept_main_);
1366 EXPECT_TRUE(interceptor.did_intercept_final_);
1367
1368 // Check we got one good response
1369 EXPECT_TRUE(req.status().is_success());
1370 EXPECT_EQ(200, req.response_headers()->response_code());
1371 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1372 EXPECT_EQ(1, d.response_started_count());
1373 EXPECT_EQ(0, d.received_redirect_count());
1374}
1375
1376TEST_F(URLRequestTest, InterceptNetworkError) {
1377 TestInterceptor interceptor;
1378
1379 // intercept the main request to simulate a network error
1380 interceptor.simulate_main_network_error_ = true;
1381
1382 // intercept that error and respond with an OK response
1383 interceptor.intercept_final_response_ = true;
1384 interceptor.final_headers_ = TestInterceptor::ok_headers();
1385 interceptor.final_data_ = TestInterceptor::ok_data();
1386
1387 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191388 URLRequest req(GURL("http://test_intercept/foo"),
1389 DEFAULT_PRIORITY,
1390 &d,
1391 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441392 req.set_method("GET");
1393 req.Start();
[email protected]255620da2013-08-19 13:14:291394 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441395
1396 // Check the interceptor got called as expected
1397 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1398 EXPECT_TRUE(interceptor.did_intercept_final_);
1399
1400 // Check we received one good response
1401 EXPECT_TRUE(req.status().is_success());
1402 EXPECT_EQ(200, req.response_headers()->response_code());
1403 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1404 EXPECT_EQ(1, d.response_started_count());
1405 EXPECT_EQ(0, d.received_redirect_count());
1406}
1407
1408TEST_F(URLRequestTest, InterceptRestartRequired) {
1409 TestInterceptor interceptor;
1410
1411 // restart the main request
1412 interceptor.restart_main_request_ = true;
1413
1414 // then intercept the new main request and respond with an OK response
1415 interceptor.intercept_main_request_ = true;
1416 interceptor.main_headers_ = TestInterceptor::ok_headers();
1417 interceptor.main_data_ = TestInterceptor::ok_data();
1418
1419 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191420 URLRequest req(GURL("http://test_intercept/foo"),
1421 DEFAULT_PRIORITY,
1422 &d,
1423 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441424 req.set_method("GET");
1425 req.Start();
[email protected]255620da2013-08-19 13:14:291426 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441427
1428 // Check the interceptor got called as expected
1429 EXPECT_TRUE(interceptor.did_restart_main_);
1430 EXPECT_TRUE(interceptor.did_intercept_main_);
1431
1432 // Check we received one good response
1433 EXPECT_TRUE(req.status().is_success());
1434 if (req.status().is_success()) {
1435 EXPECT_EQ(200, req.response_headers()->response_code());
1436 }
1437 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1438 EXPECT_EQ(1, d.response_started_count());
1439 EXPECT_EQ(0, d.received_redirect_count());
1440}
1441
1442TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1443 TestInterceptor interceptor;
1444
1445 // intercept the main request and cancel from within the restarted job
1446 interceptor.cancel_main_request_ = true;
1447
1448 // setup to intercept final response and override it with an OK response
1449 interceptor.intercept_final_response_ = true;
1450 interceptor.final_headers_ = TestInterceptor::ok_headers();
1451 interceptor.final_data_ = TestInterceptor::ok_data();
1452
1453 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191454 URLRequest req(GURL("http://test_intercept/foo"),
1455 DEFAULT_PRIORITY,
1456 &d,
1457 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441458 req.set_method("GET");
1459 req.Start();
[email protected]255620da2013-08-19 13:14:291460 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441461
1462 // Check the interceptor got called as expected
1463 EXPECT_TRUE(interceptor.did_cancel_main_);
1464 EXPECT_FALSE(interceptor.did_intercept_final_);
1465
1466 // Check we see a canceled request
1467 EXPECT_FALSE(req.status().is_success());
1468 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1469}
1470
1471TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1472 TestInterceptor interceptor;
1473
1474 // intercept the main request and respond with a redirect
1475 interceptor.intercept_main_request_ = true;
1476 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1477 interceptor.main_data_ = TestInterceptor::redirect_data();
1478
1479 // intercept the redirect and cancel from within that job
1480 interceptor.cancel_redirect_request_ = true;
1481
1482 // setup to intercept final response and override it with an OK response
1483 interceptor.intercept_final_response_ = true;
1484 interceptor.final_headers_ = TestInterceptor::ok_headers();
1485 interceptor.final_data_ = TestInterceptor::ok_data();
1486
1487 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191488 URLRequest req(GURL("http://test_intercept/foo"),
1489 DEFAULT_PRIORITY,
1490 &d,
1491 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441492 req.set_method("GET");
1493 req.Start();
[email protected]255620da2013-08-19 13:14:291494 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441495
1496 // Check the interceptor got called as expected
1497 EXPECT_TRUE(interceptor.did_intercept_main_);
1498 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1499 EXPECT_FALSE(interceptor.did_intercept_final_);
1500
1501 // Check we see a canceled request
1502 EXPECT_FALSE(req.status().is_success());
1503 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1504}
1505
1506TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1507 TestInterceptor interceptor;
1508
1509 // intercept the main request to simulate a network error
1510 interceptor.simulate_main_network_error_ = true;
1511
1512 // setup to intercept final response and cancel from within that job
1513 interceptor.cancel_final_request_ = true;
1514
1515 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191516 URLRequest req(GURL("http://test_intercept/foo"),
1517 DEFAULT_PRIORITY,
1518 &d,
1519 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441520 req.set_method("GET");
1521 req.Start();
[email protected]255620da2013-08-19 13:14:291522 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441523
1524 // Check the interceptor got called as expected
1525 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1526 EXPECT_TRUE(interceptor.did_cancel_final_);
1527
1528 // Check we see a canceled request
1529 EXPECT_FALSE(req.status().is_success());
1530 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1531}
1532
1533TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1534 TestInterceptor interceptor;
1535
1536 // intercept the main request and cancel then restart from within that job
1537 interceptor.cancel_then_restart_main_request_ = true;
1538
1539 // setup to intercept final response and override it with an OK response
1540 interceptor.intercept_final_response_ = true;
1541 interceptor.final_headers_ = TestInterceptor::ok_headers();
1542 interceptor.final_data_ = TestInterceptor::ok_data();
1543
1544 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191545 URLRequest req(GURL("http://test_intercept/foo"),
1546 DEFAULT_PRIORITY,
1547 &d,
1548 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441549 req.set_method("GET");
1550 req.Start();
[email protected]255620da2013-08-19 13:14:291551 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441552
1553 // Check the interceptor got called as expected
1554 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1555 EXPECT_FALSE(interceptor.did_intercept_final_);
1556
1557 // Check we see a canceled request
1558 EXPECT_FALSE(req.status().is_success());
1559 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1560}
1561
[email protected]2bba3252013-04-08 19:50:591562LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1563 URLRequestContext* context) {
1564 TestInterceptor interceptor;
1565 interceptor.intercept_main_request_ = true;
1566 interceptor.main_request_load_timing_info_ = job_load_timing;
1567 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191568 URLRequest req(
1569 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, context);
[email protected]2bba3252013-04-08 19:50:591570 req.Start();
[email protected]255620da2013-08-19 13:14:291571 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591572
1573 LoadTimingInfo resulting_load_timing;
1574 req.GetLoadTimingInfo(&resulting_load_timing);
1575
1576 // None of these should be modified by the URLRequest.
1577 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1578 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1579 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1580 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1581 EXPECT_EQ(job_load_timing.receive_headers_end,
1582 resulting_load_timing.receive_headers_end);
1583
1584 return resulting_load_timing;
1585}
1586
1587// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1588// reused. |connect_time_flags| is used to indicate if there should be dns
1589// or SSL times, and |used_proxy| is used for proxy times.
1590LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1591 int connect_time_flags,
1592 bool used_proxy) {
1593 LoadTimingInfo load_timing;
1594 load_timing.socket_log_id = 1;
1595
1596 if (used_proxy) {
1597 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1598 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1599 }
1600
1601 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1602 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1603 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1604 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1605 }
1606 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1607 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1608 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1609 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1610 }
1611 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1612
1613 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1614 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1615 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1616 return load_timing;
1617}
1618
1619// Same as above, but in the case of a reused socket.
1620LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1621 bool used_proxy) {
1622 LoadTimingInfo load_timing;
1623 load_timing.socket_log_id = 1;
1624 load_timing.socket_reused = true;
1625
1626 if (used_proxy) {
1627 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1628 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1629 }
1630
1631 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1632 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1633 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1634 return load_timing;
1635}
1636
1637// Basic test that the intercept + load timing tests work.
1638TEST_F(URLRequestTest, InterceptLoadTiming) {
1639 base::TimeTicks now = base::TimeTicks::Now();
1640 LoadTimingInfo job_load_timing =
1641 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1642
[email protected]2ca01e52013-10-31 22:05:191643 LoadTimingInfo load_timing_result =
1644 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591645
1646 // Nothing should have been changed by the URLRequest.
1647 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1648 load_timing_result.proxy_resolve_start);
1649 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1650 load_timing_result.proxy_resolve_end);
1651 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1652 load_timing_result.connect_timing.dns_start);
1653 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1654 load_timing_result.connect_timing.dns_end);
1655 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1656 load_timing_result.connect_timing.connect_start);
1657 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1658 load_timing_result.connect_timing.connect_end);
1659 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1660 load_timing_result.connect_timing.ssl_start);
1661 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1662 load_timing_result.connect_timing.ssl_end);
1663
1664 // Redundant sanity check.
1665 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1666}
1667
1668// Another basic test, with proxy and SSL times, but no DNS times.
1669TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1670 base::TimeTicks now = base::TimeTicks::Now();
1671 LoadTimingInfo job_load_timing =
1672 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1673
[email protected]2ca01e52013-10-31 22:05:191674 LoadTimingInfo load_timing_result =
1675 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591676
1677 // Nothing should have been changed by the URLRequest.
1678 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1679 load_timing_result.proxy_resolve_start);
1680 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1681 load_timing_result.proxy_resolve_end);
1682 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1683 load_timing_result.connect_timing.dns_start);
1684 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1685 load_timing_result.connect_timing.dns_end);
1686 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1687 load_timing_result.connect_timing.connect_start);
1688 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1689 load_timing_result.connect_timing.connect_end);
1690 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1691 load_timing_result.connect_timing.ssl_start);
1692 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1693 load_timing_result.connect_timing.ssl_end);
1694
1695 // Redundant sanity check.
1696 TestLoadTimingNotReusedWithProxy(load_timing_result,
1697 CONNECT_TIMING_HAS_SSL_TIMES);
1698}
1699
1700// Make sure that URLRequest correctly adjusts proxy times when they're before
1701// |request_start|, due to already having a connected socket. This happens in
1702// the case of reusing a SPDY session or HTTP pipeline. The connected socket is
1703// not considered reused in this test (May be a preconnect).
1704//
1705// To mix things up from the test above, assumes DNS times but no SSL times.
1706TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1707 base::TimeTicks now = base::TimeTicks::Now();
1708 LoadTimingInfo job_load_timing =
1709 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1710 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1711 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1712 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1713 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1714 job_load_timing.connect_timing.connect_start =
1715 now - base::TimeDelta::FromDays(2);
1716 job_load_timing.connect_timing.connect_end =
1717 now - base::TimeDelta::FromDays(1);
1718
[email protected]2ca01e52013-10-31 22:05:191719 LoadTimingInfo load_timing_result =
1720 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591721
1722 // Proxy times, connect times, and DNS times should all be replaced with
1723 // request_start.
1724 EXPECT_EQ(load_timing_result.request_start,
1725 load_timing_result.proxy_resolve_start);
1726 EXPECT_EQ(load_timing_result.request_start,
1727 load_timing_result.proxy_resolve_end);
1728 EXPECT_EQ(load_timing_result.request_start,
1729 load_timing_result.connect_timing.dns_start);
1730 EXPECT_EQ(load_timing_result.request_start,
1731 load_timing_result.connect_timing.dns_end);
1732 EXPECT_EQ(load_timing_result.request_start,
1733 load_timing_result.connect_timing.connect_start);
1734 EXPECT_EQ(load_timing_result.request_start,
1735 load_timing_result.connect_timing.connect_end);
1736
1737 // Other times should have been left null.
1738 TestLoadTimingNotReusedWithProxy(load_timing_result,
1739 CONNECT_TIMING_HAS_DNS_TIMES);
1740}
1741
1742// Same as above, but in the reused case.
1743TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1744 base::TimeTicks now = base::TimeTicks::Now();
1745 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1746 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1747 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1748
[email protected]2ca01e52013-10-31 22:05:191749 LoadTimingInfo load_timing_result =
1750 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591751
1752 // Proxy times and connect times should all be replaced with request_start.
1753 EXPECT_EQ(load_timing_result.request_start,
1754 load_timing_result.proxy_resolve_start);
1755 EXPECT_EQ(load_timing_result.request_start,
1756 load_timing_result.proxy_resolve_end);
1757
1758 // Other times should have been left null.
1759 TestLoadTimingReusedWithProxy(load_timing_result);
1760}
1761
1762// Make sure that URLRequest correctly adjusts connect times when they're before
1763// |request_start|, due to reusing a connected socket. The connected socket is
1764// not considered reused in this test (May be a preconnect).
1765//
1766// To mix things up, the request has SSL times, but no DNS times.
1767TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1768 base::TimeTicks now = base::TimeTicks::Now();
1769 LoadTimingInfo job_load_timing =
1770 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1771 job_load_timing.connect_timing.connect_start =
1772 now - base::TimeDelta::FromDays(1);
1773 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1774 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1775 job_load_timing.connect_timing.connect_end =
1776 now - base::TimeDelta::FromDays(4);
1777
[email protected]2ca01e52013-10-31 22:05:191778 LoadTimingInfo load_timing_result =
1779 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591780
1781 // Connect times, and SSL times should be replaced with request_start.
1782 EXPECT_EQ(load_timing_result.request_start,
1783 load_timing_result.connect_timing.connect_start);
1784 EXPECT_EQ(load_timing_result.request_start,
1785 load_timing_result.connect_timing.ssl_start);
1786 EXPECT_EQ(load_timing_result.request_start,
1787 load_timing_result.connect_timing.ssl_end);
1788 EXPECT_EQ(load_timing_result.request_start,
1789 load_timing_result.connect_timing.connect_end);
1790
1791 // Other times should have been left null.
1792 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1793}
1794
1795// Make sure that URLRequest correctly adjusts connect times when they're before
1796// |request_start|, due to reusing a connected socket in the case that there
1797// are also proxy times. The connected socket is not considered reused in this
1798// test (May be a preconnect).
1799//
1800// In this test, there are no SSL or DNS times.
1801TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1802 base::TimeTicks now = base::TimeTicks::Now();
1803 LoadTimingInfo job_load_timing =
1804 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1805 job_load_timing.connect_timing.connect_start =
1806 now - base::TimeDelta::FromDays(1);
1807 job_load_timing.connect_timing.connect_end =
1808 now - base::TimeDelta::FromDays(2);
1809
[email protected]2ca01e52013-10-31 22:05:191810 LoadTimingInfo load_timing_result =
1811 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591812
1813 // Connect times should be replaced with proxy_resolve_end.
1814 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1815 load_timing_result.connect_timing.connect_start);
1816 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1817 load_timing_result.connect_timing.connect_end);
1818
1819 // Other times should have been left null.
1820 TestLoadTimingNotReusedWithProxy(load_timing_result,
1821 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1822}
1823
[email protected]316c1e5e2012-09-12 15:17:441824// Check that two different URL requests have different identifiers.
1825TEST_F(URLRequestTest, Identifiers) {
1826 TestDelegate d;
1827 TestURLRequestContext context;
[email protected]2ca01e52013-10-31 22:05:191828 TestURLRequest req(
1829 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1830 TestURLRequest other_req(
1831 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:441832
1833 ASSERT_NE(req.identifier(), other_req.identifier());
1834}
1835
1836// Check that a failure to connect to the proxy is reported to the network
1837// delegate.
1838TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1839 MockHostResolver host_resolver;
1840 host_resolver.rules()->AddSimulatedFailure("*");
1841
[email protected]ceefd7fd2012-11-29 00:36:241842 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:441843 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1844
1845 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191846 URLRequest req(GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:441847 req.set_method("GET");
1848
1849 req.Start();
[email protected]255620da2013-08-19 13:14:291850 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441851
1852 // Check we see a failed request.
1853 EXPECT_FALSE(req.status().is_success());
1854 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1855 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1856
1857 EXPECT_EQ(1, network_delegate.error_count());
1858 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1859 EXPECT_EQ(1, network_delegate.completed_requests());
1860}
1861
1862// Make sure that net::NetworkDelegate::NotifyCompleted is called if
1863// content is empty.
1864TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1865 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191866 URLRequest req(GURL("data:,"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441867 req.Start();
[email protected]255620da2013-08-19 13:14:291868 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441869 EXPECT_EQ("", d.data_received());
1870 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1871}
1872
[email protected]5033ab82013-03-22 20:17:461873// Make sure that SetPriority actually sets the URLRequest's priority
1874// correctly, both before and after start.
1875TEST_F(URLRequestTest, SetPriorityBasic) {
1876 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191877 URLRequest req(GURL("http://test_intercept/foo"),
1878 DEFAULT_PRIORITY,
1879 &d,
1880 &default_context_);
[email protected]5033ab82013-03-22 20:17:461881 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1882
1883 req.SetPriority(LOW);
1884 EXPECT_EQ(LOW, req.priority());
1885
1886 req.Start();
1887 EXPECT_EQ(LOW, req.priority());
1888
1889 req.SetPriority(MEDIUM);
1890 EXPECT_EQ(MEDIUM, req.priority());
1891}
1892
1893// Make sure that URLRequest calls SetPriority on a job before calling
1894// Start on it.
1895TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1896 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191897 URLRequest req(GURL("http://test_intercept/foo"),
1898 DEFAULT_PRIORITY,
1899 &d,
1900 &default_context_);
[email protected]5033ab82013-03-22 20:17:461901 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1902
1903 scoped_refptr<URLRequestTestJob> job =
1904 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501905 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461906 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1907
1908 req.SetPriority(LOW);
1909
1910 req.Start();
1911 EXPECT_EQ(LOW, job->priority());
1912}
1913
1914// Make sure that URLRequest passes on its priority updates to its
1915// job.
1916TEST_F(URLRequestTest, SetJobPriority) {
1917 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191918 URLRequest req(GURL("http://test_intercept/foo"),
1919 DEFAULT_PRIORITY,
1920 &d,
1921 &default_context_);
[email protected]5033ab82013-03-22 20:17:461922
1923 scoped_refptr<URLRequestTestJob> job =
1924 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501925 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461926
1927 req.SetPriority(LOW);
1928 req.Start();
1929 EXPECT_EQ(LOW, job->priority());
1930
1931 req.SetPriority(MEDIUM);
1932 EXPECT_EQ(MEDIUM, req.priority());
1933 EXPECT_EQ(MEDIUM, job->priority());
1934}
1935
[email protected]bb1c4662013-11-14 00:00:071936// Setting the IGNORE_LIMITS load flag should be okay if the priority
1937// is MAXIMUM_PRIORITY.
1938TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1939 TestDelegate d;
1940 URLRequest req(GURL("http://test_intercept/foo"),
1941 MAXIMUM_PRIORITY,
1942 &d,
1943 &default_context_);
1944 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1945
1946 scoped_refptr<URLRequestTestJob> job =
1947 new URLRequestTestJob(&req, &default_network_delegate_);
1948 AddTestInterceptor()->set_main_intercept_job(job.get());
1949
1950 req.SetLoadFlags(LOAD_IGNORE_LIMITS);
1951 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1952
1953 req.SetPriority(MAXIMUM_PRIORITY);
1954 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1955
1956 req.Start();
1957 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1958 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1959}
1960
[email protected]ce7d0cbc2013-05-03 18:57:221961// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:441962#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:221963// A subclass of SpawnedTestServer that uses a statically-configured hostname.
1964// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:441965// http://crbug.com/114369
[email protected]ce7d0cbc2013-05-03 18:57:221966class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:441967 public:
[email protected]6cdfd7f2013-02-08 20:40:151968 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:221969 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1970 ScopedCustomUrlRequestTestHttpHost::value(),
1971 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:441972 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:221973 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1974 ScopedCustomUrlRequestTestHttpHost::value(),
1975 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:441976};
1977
[email protected]f2f31b32013-01-16 23:24:091978TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:441979 LocalHttpTestServer test_server;
1980 ASSERT_TRUE(test_server.Start());
1981
1982 TestURLRequestContext context;
1983 scoped_refptr<DelayedCookieMonster> delayed_cm =
1984 new DelayedCookieMonster();
1985 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:501986 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:441987
1988 // Set up a cookie.
1989 {
1990 TestNetworkDelegate network_delegate;
1991 context.set_network_delegate(&network_delegate);
1992 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191993 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1994 DEFAULT_PRIORITY,
1995 &d,
1996 &context);
[email protected]316c1e5e2012-09-12 15:17:441997 req.Start();
[email protected]255620da2013-08-19 13:14:291998 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441999 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2000 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2001 EXPECT_EQ(1, network_delegate.set_cookie_count());
2002 }
2003
2004 // Verify that the cookie is set.
2005 {
2006 TestNetworkDelegate network_delegate;
2007 context.set_network_delegate(&network_delegate);
2008 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192009 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2010 DEFAULT_PRIORITY,
2011 &d,
2012 &context);
[email protected]316c1e5e2012-09-12 15:17:442013 req.Start();
[email protected]255620da2013-08-19 13:14:292014 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442015
2016 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2017 != std::string::npos);
2018 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2019 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2020 }
2021}
2022
[email protected]f2f31b32013-01-16 23:24:092023TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442024 LocalHttpTestServer test_server;
2025 ASSERT_TRUE(test_server.Start());
2026
2027 // Set up a cookie.
2028 {
2029 TestNetworkDelegate network_delegate;
2030 default_context_.set_network_delegate(&network_delegate);
2031 TestDelegate d;
2032 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192033 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442034 &d,
2035 &default_context_);
2036 req.Start();
[email protected]255620da2013-08-19 13:14:292037 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442038 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2039 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2040 }
2041
2042 // Verify that the cookie is set.
2043 {
2044 TestNetworkDelegate network_delegate;
2045 default_context_.set_network_delegate(&network_delegate);
2046 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192047 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2048 DEFAULT_PRIORITY,
2049 &d,
2050 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442051 req.Start();
[email protected]255620da2013-08-19 13:14:292052 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442053
2054 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2055 != std::string::npos);
2056 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2057 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2058 }
2059
2060 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2061 {
2062 TestNetworkDelegate network_delegate;
2063 default_context_.set_network_delegate(&network_delegate);
2064 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192065 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2066 DEFAULT_PRIORITY,
2067 &d,
2068 &default_context_);
[email protected]bb1c4662013-11-14 00:00:072069 req.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]316c1e5e2012-09-12 15:17:442070 req.Start();
[email protected]255620da2013-08-19 13:14:292071 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442072
2073 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2074 == std::string::npos);
2075
2076 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2077 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2078 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2079 }
2080}
2081
2082TEST_F(URLRequestTest, DoNotSaveCookies) {
2083 LocalHttpTestServer test_server;
2084 ASSERT_TRUE(test_server.Start());
2085
2086 // Set up a cookie.
2087 {
2088 TestNetworkDelegate network_delegate;
2089 default_context_.set_network_delegate(&network_delegate);
2090 TestDelegate d;
2091 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192092 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442093 &d,
2094 &default_context_);
2095 req.Start();
[email protected]255620da2013-08-19 13:14:292096 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442097
2098 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2099 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2100 EXPECT_EQ(1, network_delegate.set_cookie_count());
2101 }
2102
2103 // Try to set-up another cookie and update the previous cookie.
2104 {
2105 TestNetworkDelegate network_delegate;
2106 default_context_.set_network_delegate(&network_delegate);
2107 TestDelegate d;
2108 URLRequest req(
2109 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192110 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442111 &d,
2112 &default_context_);
[email protected]bb1c4662013-11-14 00:00:072113 req.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
[email protected]316c1e5e2012-09-12 15:17:442114 req.Start();
2115
[email protected]255620da2013-08-19 13:14:292116 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442117
2118 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2119 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2120 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2121 EXPECT_EQ(0, network_delegate.set_cookie_count());
2122 }
2123
2124 // Verify the cookies weren't saved or updated.
2125 {
2126 TestNetworkDelegate network_delegate;
2127 default_context_.set_network_delegate(&network_delegate);
2128 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192129 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2130 DEFAULT_PRIORITY,
2131 &d,
2132 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442133 req.Start();
[email protected]255620da2013-08-19 13:14:292134 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442135
2136 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2137 == std::string::npos);
2138 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2139 != std::string::npos);
2140
2141 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2142 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2143 EXPECT_EQ(0, network_delegate.set_cookie_count());
2144 }
2145}
2146
2147TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2148 LocalHttpTestServer test_server;
2149 ASSERT_TRUE(test_server.Start());
2150
2151 // Set up a cookie.
2152 {
2153 TestNetworkDelegate network_delegate;
2154 default_context_.set_network_delegate(&network_delegate);
2155 TestDelegate d;
2156 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192157 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442158 &d,
2159 &default_context_);
2160 req.Start();
[email protected]255620da2013-08-19 13:14:292161 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442162
2163 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2164 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2165 }
2166
2167 // Verify that the cookie is set.
2168 {
2169 TestNetworkDelegate network_delegate;
2170 default_context_.set_network_delegate(&network_delegate);
2171 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192172 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2173 DEFAULT_PRIORITY,
2174 &d,
2175 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442176 req.Start();
[email protected]255620da2013-08-19 13:14:292177 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442178
2179 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2180 != std::string::npos);
2181
2182 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2183 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2184 }
2185
2186 // Verify that the cookie isn't sent.
2187 {
2188 TestNetworkDelegate network_delegate;
2189 default_context_.set_network_delegate(&network_delegate);
2190 TestDelegate d;
2191 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]2ca01e52013-10-31 22:05:192192 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2193 DEFAULT_PRIORITY,
2194 &d,
2195 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442196 req.Start();
[email protected]255620da2013-08-19 13:14:292197 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442198
2199 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2200 == std::string::npos);
2201
[email protected]22e045f2013-09-20 03:54:032202 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442203 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2204 }
2205}
2206
2207TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2208 LocalHttpTestServer test_server;
2209 ASSERT_TRUE(test_server.Start());
2210
2211 // Set up a cookie.
2212 {
2213 TestNetworkDelegate network_delegate;
2214 default_context_.set_network_delegate(&network_delegate);
2215 TestDelegate d;
2216 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192217 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442218 &d,
2219 &default_context_);
2220 req.Start();
[email protected]255620da2013-08-19 13:14:292221 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442222
2223 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2224 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2225 }
2226
2227 // Try to set-up another cookie and update the previous cookie.
2228 {
2229 TestNetworkDelegate network_delegate;
2230 default_context_.set_network_delegate(&network_delegate);
2231 TestDelegate d;
2232 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2233 URLRequest req(
2234 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192235 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442236 &d,
2237 &default_context_);
2238 req.Start();
2239
[email protected]255620da2013-08-19 13:14:292240 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442241
2242 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2243 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2244 }
2245
2246 // Verify the cookies weren't saved or updated.
2247 {
2248 TestNetworkDelegate network_delegate;
2249 default_context_.set_network_delegate(&network_delegate);
2250 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192251 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2252 DEFAULT_PRIORITY,
2253 &d,
2254 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442255 req.Start();
[email protected]255620da2013-08-19 13:14:292256 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442257
2258 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2259 == std::string::npos);
2260 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2261 != std::string::npos);
2262
2263 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2264 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2265 }
2266}
2267
2268TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2269 LocalHttpTestServer test_server;
2270 ASSERT_TRUE(test_server.Start());
2271
2272 // Set up an empty cookie.
2273 {
2274 TestNetworkDelegate network_delegate;
2275 default_context_.set_network_delegate(&network_delegate);
2276 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192277 URLRequest req(test_server.GetURL("set-cookie"),
2278 DEFAULT_PRIORITY,
2279 &d,
2280 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442281 req.Start();
[email protected]255620da2013-08-19 13:14:292282 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442283
2284 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2285 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2286 EXPECT_EQ(0, network_delegate.set_cookie_count());
2287 }
2288}
2289
2290TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2291 LocalHttpTestServer test_server;
2292 ASSERT_TRUE(test_server.Start());
2293
2294 // Set up a cookie.
2295 {
2296 TestNetworkDelegate network_delegate;
2297 default_context_.set_network_delegate(&network_delegate);
2298 TestDelegate d;
2299 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192300 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442301 &d,
2302 &default_context_);
2303 req.Start();
[email protected]255620da2013-08-19 13:14:292304 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442305
2306 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2307 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2308 }
2309
2310 // Verify that the cookie is set.
2311 {
2312 TestNetworkDelegate network_delegate;
2313 default_context_.set_network_delegate(&network_delegate);
2314 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192315 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2316 DEFAULT_PRIORITY,
2317 &d,
2318 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442319 req.Start();
[email protected]255620da2013-08-19 13:14:292320 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442321
2322 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2323 != std::string::npos);
2324
2325 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2326 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2327 }
2328
2329 // Verify that the cookie isn't sent.
2330 {
2331 TestNetworkDelegate network_delegate;
2332 default_context_.set_network_delegate(&network_delegate);
2333 TestDelegate d;
2334 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]2ca01e52013-10-31 22:05:192335 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2336 DEFAULT_PRIORITY,
2337 &d,
2338 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442339 req.Start();
[email protected]255620da2013-08-19 13:14:292340 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442341
2342 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2343 == std::string::npos);
2344
[email protected]22e045f2013-09-20 03:54:032345 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442346 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2347 }
2348}
2349
2350TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2351 LocalHttpTestServer test_server;
2352 ASSERT_TRUE(test_server.Start());
2353
2354 // Set up a cookie.
2355 {
2356 TestNetworkDelegate network_delegate;
2357 default_context_.set_network_delegate(&network_delegate);
2358 TestDelegate d;
2359 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192360 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442361 &d,
2362 &default_context_);
2363 req.Start();
[email protected]255620da2013-08-19 13:14:292364 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442365
2366 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2367 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2368 }
2369
2370 // Try to set-up another cookie and update the previous cookie.
2371 {
2372 TestNetworkDelegate network_delegate;
2373 default_context_.set_network_delegate(&network_delegate);
2374 TestDelegate d;
2375 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2376 URLRequest req(
2377 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192378 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442379 &d,
2380 &default_context_);
2381 req.Start();
2382
[email protected]255620da2013-08-19 13:14:292383 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442384
2385 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2386 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2387 }
2388
2389 // Verify the cookies weren't saved or updated.
2390 {
2391 TestNetworkDelegate network_delegate;
2392 default_context_.set_network_delegate(&network_delegate);
2393 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192394 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2395 DEFAULT_PRIORITY,
2396 &d,
2397 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442398 req.Start();
[email protected]255620da2013-08-19 13:14:292399 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442400
2401 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2402 == std::string::npos);
2403 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2404 != std::string::npos);
2405
2406 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2407 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2408 }
2409}
2410
[email protected]5095cd72012-11-01 10:29:162411// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2412// value for the |fixed_date| argument given to the constructor.
2413class FixedDateNetworkDelegate : public TestNetworkDelegate {
2414 public:
2415 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2416 : fixed_date_(fixed_date) {}
2417 virtual ~FixedDateNetworkDelegate() {}
2418
2419 // net::NetworkDelegate implementation
2420 virtual int OnHeadersReceived(
2421 net::URLRequest* request,
2422 const net::CompletionCallback& callback,
2423 const net::HttpResponseHeaders* original_response_headers,
2424 scoped_refptr<net::HttpResponseHeaders>* override_response_headers)
2425 OVERRIDE;
2426
2427 private:
2428 std::string fixed_date_;
2429
2430 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2431};
2432
2433int FixedDateNetworkDelegate::OnHeadersReceived(
2434 net::URLRequest* request,
2435 const net::CompletionCallback& callback,
2436 const net::HttpResponseHeaders* original_response_headers,
2437 scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
2438 net::HttpResponseHeaders* new_response_headers =
2439 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2440
2441 new_response_headers->RemoveHeader("Date");
2442 new_response_headers->AddHeader("Date: " + fixed_date_);
2443
2444 *override_response_headers = new_response_headers;
2445 return TestNetworkDelegate::OnHeadersReceived(request,
2446 callback,
2447 original_response_headers,
2448 override_response_headers);
2449}
2450
2451// Test that cookie expiration times are adjusted for server/client clock
2452// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2453// headers by defaulting to GMT. (crbug.com/135131)
2454TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2455 LocalHttpTestServer test_server;
2456 ASSERT_TRUE(test_server.Start());
2457
2458 // Set up an expired cookie.
2459 {
2460 TestNetworkDelegate network_delegate;
2461 default_context_.set_network_delegate(&network_delegate);
2462 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192463 URLRequest req(
2464 test_server.GetURL(
2465 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2466 DEFAULT_PRIORITY,
[email protected]5095cd72012-11-01 10:29:162467 &d,
2468 &default_context_);
2469 req.Start();
[email protected]255620da2013-08-19 13:14:292470 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162471 }
2472 // Verify that the cookie is not set.
2473 {
2474 TestNetworkDelegate network_delegate;
2475 default_context_.set_network_delegate(&network_delegate);
2476 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192477 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2478 DEFAULT_PRIORITY,
2479 &d,
2480 &default_context_);
[email protected]5095cd72012-11-01 10:29:162481 req.Start();
[email protected]255620da2013-08-19 13:14:292482 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162483
2484 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2485 }
2486 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2487 {
2488 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2489 default_context_.set_network_delegate(&network_delegate);
2490 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192491 URLRequest req(
2492 test_server.GetURL(
2493 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2494 DEFAULT_PRIORITY,
[email protected]5095cd72012-11-01 10:29:162495 &d,
2496 &default_context_);
2497 req.Start();
[email protected]255620da2013-08-19 13:14:292498 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162499 }
2500 // Verify that the cookie is set.
2501 {
2502 TestNetworkDelegate network_delegate;
2503 default_context_.set_network_delegate(&network_delegate);
2504 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192505 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2506 DEFAULT_PRIORITY,
2507 &d,
2508 &default_context_);
[email protected]5095cd72012-11-01 10:29:162509 req.Start();
[email protected]255620da2013-08-19 13:14:292510 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162511
2512 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2513 }
2514}
2515
2516
[email protected]316c1e5e2012-09-12 15:17:442517// Check that it is impossible to change the referrer in the extra headers of
2518// an URLRequest.
2519TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2520 LocalHttpTestServer test_server;
2521 ASSERT_TRUE(test_server.Start());
2522
2523 // If extra headers contain referer and the request contains a referer,
2524 // only the latter shall be respected.
2525 {
2526 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192527 URLRequest req(test_server.GetURL("echoheader?Referer"),
2528 DEFAULT_PRIORITY,
2529 &d,
2530 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:132531 req.SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442532
2533 HttpRequestHeaders headers;
2534 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2535 req.SetExtraRequestHeaders(headers);
2536
2537 req.Start();
[email protected]255620da2013-08-19 13:14:292538 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442539
2540 EXPECT_EQ("http://foo.com/", d.data_received());
2541 }
2542
2543 // If extra headers contain a referer but the request does not, no referer
2544 // shall be sent in the header.
2545 {
2546 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192547 URLRequest req(test_server.GetURL("echoheader?Referer"),
2548 DEFAULT_PRIORITY,
2549 &d,
2550 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442551
2552 HttpRequestHeaders headers;
2553 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2554 req.SetExtraRequestHeaders(headers);
[email protected]bb1c4662013-11-14 00:00:072555 req.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442556
2557 req.Start();
[email protected]255620da2013-08-19 13:14:292558 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442559
2560 EXPECT_EQ("None", d.data_received());
2561 }
2562}
2563
[email protected]b89290212009-08-14 22:37:352564class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112565 public:
2566 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152567 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112568 "net/data/url_request_unittest"))) {
2569 }
2570
[email protected]b89290212009-08-14 22:37:352571 protected:
[email protected]21184962011-10-26 00:50:302572 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2573 // |request_method| is the method to use for the initial request.
2574 // |redirect_method| is the method that is expected to be used for the second
2575 // request, after redirection.
2576 // If |include_data| is true, data is uploaded with the request. The
2577 // response body is expected to match it exactly, if and only if
2578 // |request_method| == |redirect_method|.
2579 void HTTPRedirectMethodTest(const GURL& redirect_url,
2580 const std::string& request_method,
2581 const std::string& redirect_method,
2582 bool include_data) {
2583 static const char kData[] = "hello world";
2584 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192585 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]21184962011-10-26 00:50:302586 req.set_method(request_method);
2587 if (include_data) {
[email protected]f288ef02012-12-15 20:28:282588 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]21184962011-10-26 00:50:302589 HttpRequestHeaders headers;
2590 headers.SetHeader(HttpRequestHeaders::kContentLength,
2591 base::UintToString(arraysize(kData) - 1));
2592 req.SetExtraRequestHeaders(headers);
2593 }
2594 req.Start();
[email protected]255620da2013-08-19 13:14:292595 base::RunLoop().Run();
[email protected]21184962011-10-26 00:50:302596 EXPECT_EQ(redirect_method, req.method());
2597 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2598 EXPECT_EQ(OK, req.status().error());
2599 if (include_data) {
2600 if (request_method == redirect_method) {
2601 EXPECT_EQ(kData, d.data_received());
2602 } else {
2603 EXPECT_NE(kData, d.data_received());
2604 }
2605 }
2606 if (HasFailure())
2607 LOG(WARNING) << "Request method was: " << request_method;
2608 }
2609
[email protected]762d2db2010-01-11 19:03:012610 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012611 const int kMsgSize = 20000; // multiple of 10
2612 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482613 char* uploadBytes = new char[kMsgSize+1];
2614 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012615 char marker = 'a';
2616 for (int idx = 0; idx < kMsgSize/10; idx++) {
2617 memcpy(ptr, "----------", 10);
2618 ptr += 10;
2619 if (idx % 100 == 0) {
2620 ptr--;
2621 *ptr++ = marker;
2622 if (++marker > 'z')
2623 marker = 'a';
2624 }
2625 }
2626 uploadBytes[kMsgSize] = '\0';
2627
[email protected]762d2db2010-01-11 19:03:012628 for (int i = 0; i < kIterations; ++i) {
2629 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192630 URLRequest r(
2631 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]762d2db2010-01-11 19:03:012632 r.set_method(method.c_str());
2633
[email protected]f288ef02012-12-15 20:28:282634 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
[email protected]762d2db2010-01-11 19:03:012635
2636 r.Start();
2637 EXPECT_TRUE(r.is_pending());
2638
[email protected]255620da2013-08-19 13:14:292639 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012640
[email protected]329b68b2012-11-14 17:54:272641 ASSERT_EQ(1, d.response_started_count())
2642 << "request failed: " << r.status().status()
2643 << ", os error: " << r.status().error();
[email protected]762d2db2010-01-11 19:03:012644
2645 EXPECT_FALSE(d.received_data_before_response());
2646 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012647 }
2648 delete[] uploadBytes;
2649 }
2650
[email protected]ef2bf422012-05-11 03:27:092651 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222652 r->AppendChunkToUpload("a", 1, false);
2653 r->AppendChunkToUpload("bcd", 3, false);
2654 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2655 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2656 r->AppendChunkToUpload("0", 1, false);
2657 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112658 }
2659
[email protected]ef2bf422012-05-11 03:27:092660 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112661 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272662 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112663 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2664
[email protected]329b68b2012-11-14 17:54:272665 ASSERT_EQ(1, d->response_started_count())
2666 << "request failed: " << r->status().status()
2667 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112668
2669 EXPECT_FALSE(d->received_data_before_response());
2670
[email protected]329b68b2012-11-14 17:54:272671 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2672 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112673 }
2674
[email protected]ede03212012-09-07 12:52:262675 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342676 TestDelegate d;
2677 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2678 base::IntToString(num_cookies)),
[email protected]2ca01e52013-10-31 22:05:192679 DEFAULT_PRIORITY,
2680 &d,
2681 &default_context_);
[email protected]263163f2012-06-14 22:40:342682
2683 r.Start();
2684 EXPECT_TRUE(r.is_pending());
2685
[email protected]255620da2013-08-19 13:14:292686 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342687
2688 bool is_success = r.status().is_success();
2689
[email protected]ede03212012-09-07 12:52:262690 if (!is_success) {
[email protected]263163f2012-06-14 22:40:342691 // Requests handled by ChromeFrame send a less precise error message,
2692 // ERR_CONNECTION_ABORTED.
2693 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG ||
2694 r.status().error() == ERR_CONNECTION_ABORTED);
2695 // The test server appears to be unable to handle subsequent requests
2696 // after this error is triggered. Force it to restart.
2697 EXPECT_TRUE(test_server_.Stop());
2698 EXPECT_TRUE(test_server_.Start());
2699 }
2700
2701 return is_success;
2702 }
2703
[email protected]1700c6a2012-02-22 18:07:072704 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352705};
2706
[email protected]95409e12010-08-17 20:07:112707// In this unit test, we're using the HTTPTestServer as a proxy server and
2708// issuing a CONNECT request with the magic host name "www.redirect.com".
2709// The HTTPTestServer will return a 302 response, which we should not
2710// follow.
[email protected]f2f31b32013-01-16 23:24:092711TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112712 ASSERT_TRUE(test_server_.Start());
2713
[email protected]ceefd7fd2012-11-29 00:36:242714 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042715 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192716 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502717
[email protected]d1ec59082009-02-11 02:48:152718 TestDelegate d;
2719 {
[email protected]2ca01e52013-10-31 22:05:192720 URLRequest r(
2721 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]d1ec59082009-02-11 02:48:152722 r.Start();
2723 EXPECT_TRUE(r.is_pending());
2724
[email protected]255620da2013-08-19 13:14:292725 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:152726
[email protected]7461a402011-03-24 23:19:512727 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052728 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:082729 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152730 // We should not have followed the redirect.
2731 EXPECT_EQ(0, d.received_redirect_count());
2732 }
2733}
2734
[email protected]8202d0c2011-02-23 08:31:142735// This is the same as the previous test, but checks that the network delegate
2736// registers the error.
[email protected]c044616e2013-02-20 02:01:262737TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142738 ASSERT_TRUE(test_server_.Start());
2739
[email protected]ceefd7fd2012-11-29 00:36:242740 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042741 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192742 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502743
[email protected]8202d0c2011-02-23 08:31:142744 TestDelegate d;
2745 {
[email protected]2ca01e52013-10-31 22:05:192746 URLRequest r(
2747 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]8202d0c2011-02-23 08:31:142748 r.Start();
2749 EXPECT_TRUE(r.is_pending());
2750
[email protected]255620da2013-08-19 13:14:292751 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:142752
[email protected]7461a402011-03-24 23:19:512753 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052754 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]8202d0c2011-02-23 08:31:142755 EXPECT_EQ(1, d.response_started_count());
2756 // We should not have followed the redirect.
2757 EXPECT_EQ(0, d.received_redirect_count());
2758
2759 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052760 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142761 }
2762}
2763
[email protected]dc5a5cf2012-09-26 02:49:302764// Tests that we can block and asynchronously return OK in various stages.
2765TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2766 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2767 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2768 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2769 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2770 };
2771 static const size_t blocking_stages_length = arraysize(blocking_stages);
2772
2773 ASSERT_TRUE(test_server_.Start());
2774
2775 TestDelegate d;
2776 BlockingNetworkDelegate network_delegate(
2777 BlockingNetworkDelegate::USER_CALLBACK);
2778 network_delegate.set_block_on(
2779 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2780 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2781 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2782
2783 TestURLRequestContext context(true);
2784 context.set_network_delegate(&network_delegate);
2785 context.Init();
2786
2787 {
[email protected]2ca01e52013-10-31 22:05:192788 URLRequest r(
2789 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, &context);
[email protected]dc5a5cf2012-09-26 02:49:302790
2791 r.Start();
2792 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:292793 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302794 EXPECT_EQ(blocking_stages[i],
2795 network_delegate.stage_blocked_for_callback());
2796 network_delegate.DoCallback(OK);
2797 }
[email protected]255620da2013-08-19 13:14:292798 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302799 EXPECT_EQ(200, r.GetResponseCode());
2800 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2801 EXPECT_EQ(1, network_delegate.created_requests());
2802 EXPECT_EQ(0, network_delegate.destroyed_requests());
2803 }
2804 EXPECT_EQ(1, network_delegate.destroyed_requests());
2805}
2806
[email protected]4c76d7c2011-04-15 19:14:122807// Tests that the network delegate can block and cancel a request.
2808TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2809 ASSERT_TRUE(test_server_.Start());
2810
2811 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302812 BlockingNetworkDelegate network_delegate(
2813 BlockingNetworkDelegate::AUTO_CALLBACK);
2814 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2815 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:122816
[email protected]d5a4dd62012-05-23 01:41:042817 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192818 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502819
[email protected]4c76d7c2011-04-15 19:14:122820 {
[email protected]2ca01e52013-10-31 22:05:192821 URLRequest r(
2822 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122823
2824 r.Start();
[email protected]255620da2013-08-19 13:14:292825 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122826
2827 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052828 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122829 EXPECT_EQ(1, network_delegate.created_requests());
2830 EXPECT_EQ(0, network_delegate.destroyed_requests());
2831 }
2832 EXPECT_EQ(1, network_delegate.destroyed_requests());
2833}
2834
[email protected]b4438d32012-09-27 06:15:302835// Helper function for NetworkDelegateCancelRequestAsynchronously and
2836// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2837// delegate operating in |block_mode| and a request for |url|. It blocks the
2838// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2839void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2840 BlockingNetworkDelegate::Stage stage,
2841 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:362842 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:302843 BlockingNetworkDelegate network_delegate(block_mode);
2844 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2845 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:362846
[email protected]b4438d32012-09-27 06:15:302847 TestURLRequestContext context(true);
2848 context.set_network_delegate(&network_delegate);
2849 context.Init();
[email protected]3cd384c602011-08-31 16:12:362850
2851 {
[email protected]2ca01e52013-10-31 22:05:192852 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]3cd384c602011-08-31 16:12:362853
2854 r.Start();
[email protected]255620da2013-08-19 13:14:292855 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:362856
2857 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]b4438d32012-09-27 06:15:302858 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
[email protected]3cd384c602011-08-31 16:12:362859 EXPECT_EQ(1, network_delegate.created_requests());
2860 EXPECT_EQ(0, network_delegate.destroyed_requests());
2861 }
2862 EXPECT_EQ(1, network_delegate.destroyed_requests());
2863}
2864
[email protected]b4438d32012-09-27 06:15:302865// The following 3 tests check that the network delegate can cancel a request
2866// synchronously in various stages of the request.
2867TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2868 ASSERT_TRUE(test_server_.Start());
2869 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2870 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452871 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302872}
2873
2874TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2875 ASSERT_TRUE(test_server_.Start());
2876 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2877 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452878 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302879}
2880
2881TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2882 ASSERT_TRUE(test_server_.Start());
2883 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2884 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452885 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302886}
2887
2888// The following 3 tests check that the network delegate can cancel a request
2889// asynchronously in various stages of the request.
2890TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2891 ASSERT_TRUE(test_server_.Start());
2892 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2893 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452894 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302895}
2896
2897TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2898 ASSERT_TRUE(test_server_.Start());
2899 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2900 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452901 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302902}
2903
2904TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2905 ASSERT_TRUE(test_server_.Start());
2906 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2907 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452908 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302909}
2910
[email protected]4c76d7c2011-04-15 19:14:122911// Tests that the network delegate can block and redirect a request to a new
2912// URL.
2913TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2914 ASSERT_TRUE(test_server_.Start());
2915
2916 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302917 BlockingNetworkDelegate network_delegate(
2918 BlockingNetworkDelegate::AUTO_CALLBACK);
2919 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:122920 GURL redirect_url(test_server_.GetURL("simple.html"));
2921 network_delegate.set_redirect_url(redirect_url);
2922
[email protected]d5a4dd62012-05-23 01:41:042923 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192924 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502925
[email protected]4c76d7c2011-04-15 19:14:122926 {
[email protected]8f1ac082011-04-19 21:14:132927 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:192928 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122929
2930 r.Start();
[email protected]255620da2013-08-19 13:14:292931 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122932
2933 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052934 EXPECT_EQ(0, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122935 EXPECT_EQ(redirect_url, r.url());
[email protected]8f1ac082011-04-19 21:14:132936 EXPECT_EQ(original_url, r.original_url());
2937 EXPECT_EQ(2U, r.url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:122938 EXPECT_EQ(1, network_delegate.created_requests());
2939 EXPECT_EQ(0, network_delegate.destroyed_requests());
2940 }
2941 EXPECT_EQ(1, network_delegate.destroyed_requests());
2942}
2943
[email protected]b813ed72012-04-05 08:21:362944// Tests that the network delegate can block and redirect a request to a new
2945// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2946TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2947 ASSERT_TRUE(test_server_.Start());
2948
2949 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302950 BlockingNetworkDelegate network_delegate(
2951 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:362952 GURL redirect_url(test_server_.GetURL("simple.html"));
2953 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:362954
[email protected]d5a4dd62012-05-23 01:41:042955 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192956 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:362957
2958 {
2959 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:192960 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]b813ed72012-04-05 08:21:362961
2962 r.Start();
[email protected]255620da2013-08-19 13:14:292963 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:362964
2965 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2966 EXPECT_EQ(0, r.status().error());
2967 EXPECT_EQ(redirect_url, r.url());
2968 EXPECT_EQ(original_url, r.original_url());
2969 EXPECT_EQ(2U, r.url_chain().size());
2970 EXPECT_EQ(1, network_delegate.created_requests());
2971 EXPECT_EQ(0, network_delegate.destroyed_requests());
2972 }
2973 EXPECT_EQ(1, network_delegate.destroyed_requests());
2974}
2975
[email protected]3c5ca8c2011-09-29 01:14:512976// Tests that redirects caused by the network delegate preserve POST data.
2977TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2978 ASSERT_TRUE(test_server_.Start());
2979
2980 const char kData[] = "hello world";
2981
2982 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302983 BlockingNetworkDelegate network_delegate(
2984 BlockingNetworkDelegate::AUTO_CALLBACK);
2985 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:512986 GURL redirect_url(test_server_.GetURL("echo"));
2987 network_delegate.set_redirect_url(redirect_url);
2988
[email protected]ef2bf422012-05-11 03:27:092989 TestURLRequestContext context(true);
2990 context.set_network_delegate(&network_delegate);
2991 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:512992
2993 {
2994 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:192995 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]3c5ca8c2011-09-29 01:14:512996 r.set_method("POST");
[email protected]f288ef02012-12-15 20:28:282997 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]3c5ca8c2011-09-29 01:14:512998 HttpRequestHeaders headers;
2999 headers.SetHeader(HttpRequestHeaders::kContentLength,
3000 base::UintToString(arraysize(kData) - 1));
3001 r.SetExtraRequestHeaders(headers);
[email protected]3c5ca8c2011-09-29 01:14:513002 r.Start();
[email protected]255620da2013-08-19 13:14:293003 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513004
3005 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3006 EXPECT_EQ(0, r.status().error());
3007 EXPECT_EQ(redirect_url, r.url());
3008 EXPECT_EQ(original_url, r.original_url());
3009 EXPECT_EQ(2U, r.url_chain().size());
3010 EXPECT_EQ(1, network_delegate.created_requests());
3011 EXPECT_EQ(0, network_delegate.destroyed_requests());
3012 EXPECT_EQ("POST", r.method());
3013 EXPECT_EQ(kData, d.data_received());
3014 }
3015 EXPECT_EQ(1, network_delegate.destroyed_requests());
3016}
3017
[email protected]c2911d72011-10-03 22:16:363018// Tests that the network delegate can synchronously complete OnAuthRequired
3019// by taking no action. This indicates that the NetworkDelegate does not want to
3020// handle the challenge, and is passing the buck along to the
3021// URLRequest::Delegate.
3022TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3023 ASSERT_TRUE(test_server_.Start());
3024
3025 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303026 BlockingNetworkDelegate network_delegate(
3027 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363028
[email protected]ef2bf422012-05-11 03:27:093029 TestURLRequestContext context(true);
3030 context.set_network_delegate(&network_delegate);
3031 context.Init();
[email protected]c2911d72011-10-03 22:16:363032
[email protected]f3cf9802011-10-28 18:44:583033 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363034
3035 {
3036 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193037 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363038 r.Start();
[email protected]79e1fd62013-06-20 06:50:043039
[email protected]255620da2013-08-19 13:14:293040 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043041
3042 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3043 EXPECT_EQ(0, r.status().error());
3044 EXPECT_EQ(200, r.GetResponseCode());
3045 EXPECT_TRUE(d.auth_required_called());
3046 EXPECT_EQ(1, network_delegate.created_requests());
3047 EXPECT_EQ(0, network_delegate.destroyed_requests());
3048 }
3049 EXPECT_EQ(1, network_delegate.destroyed_requests());
3050}
3051
3052TEST_F(URLRequestTestHTTP,
3053 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3054 ASSERT_TRUE(test_server_.Start());
3055
3056 TestDelegate d;
3057 BlockingNetworkDelegate network_delegate(
3058 BlockingNetworkDelegate::SYNCHRONOUS);
3059
3060 TestURLRequestContext context(true);
3061 context.set_network_delegate(&network_delegate);
3062 context.Init();
3063
3064 d.set_credentials(AuthCredentials(kUser, kSecret));
3065
3066 {
3067 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193068 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]79e1fd62013-06-20 06:50:043069 r.Start();
3070
3071 {
3072 HttpRequestHeaders headers;
3073 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3074 EXPECT_FALSE(headers.HasHeader("Authorization"));
3075 }
3076
[email protected]255620da2013-08-19 13:14:293077 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363078
3079 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3080 EXPECT_EQ(0, r.status().error());
3081 EXPECT_EQ(200, r.GetResponseCode());
3082 EXPECT_TRUE(d.auth_required_called());
3083 EXPECT_EQ(1, network_delegate.created_requests());
3084 EXPECT_EQ(0, network_delegate.destroyed_requests());
3085 }
3086 EXPECT_EQ(1, network_delegate.destroyed_requests());
3087}
3088
3089// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403090// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363091TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3092 ASSERT_TRUE(test_server_.Start());
3093
3094 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303095 BlockingNetworkDelegate network_delegate(
3096 BlockingNetworkDelegate::SYNCHRONOUS);
3097 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363098 network_delegate.set_auth_retval(
3099 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3100
[email protected]f3cf9802011-10-28 18:44:583101 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363102
[email protected]ef2bf422012-05-11 03:27:093103 TestURLRequestContext context(true);
3104 context.set_network_delegate(&network_delegate);
3105 context.Init();
[email protected]c2911d72011-10-03 22:16:363106
3107 {
3108 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193109 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363110 r.Start();
[email protected]255620da2013-08-19 13:14:293111 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363112
3113 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3114 EXPECT_EQ(0, r.status().error());
3115 EXPECT_EQ(200, r.GetResponseCode());
3116 EXPECT_FALSE(d.auth_required_called());
3117 EXPECT_EQ(1, network_delegate.created_requests());
3118 EXPECT_EQ(0, network_delegate.destroyed_requests());
3119 }
3120 EXPECT_EQ(1, network_delegate.destroyed_requests());
3121}
3122
[email protected]79e1fd62013-06-20 06:50:043123// Same as above, but also tests that GetFullRequestHeaders returns the proper
3124// headers (for the first or second request) when called at the proper times.
3125TEST_F(URLRequestTestHTTP,
3126 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3127 ASSERT_TRUE(test_server_.Start());
3128
3129 TestDelegate d;
3130 BlockingNetworkDelegate network_delegate(
3131 BlockingNetworkDelegate::SYNCHRONOUS);
3132 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3133 network_delegate.set_auth_retval(
3134 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3135
3136 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3137
3138 TestURLRequestContext context(true);
3139 context.set_network_delegate(&network_delegate);
3140 context.Init();
3141
3142 {
3143 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193144 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]79e1fd62013-06-20 06:50:043145 r.Start();
[email protected]255620da2013-08-19 13:14:293146 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043147
3148 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3149 EXPECT_EQ(0, r.status().error());
3150 EXPECT_EQ(200, r.GetResponseCode());
3151 EXPECT_FALSE(d.auth_required_called());
3152 EXPECT_EQ(1, network_delegate.created_requests());
3153 EXPECT_EQ(0, network_delegate.destroyed_requests());
3154
3155 {
3156 HttpRequestHeaders headers;
3157 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3158 EXPECT_TRUE(headers.HasHeader("Authorization"));
3159 }
3160 }
3161 EXPECT_EQ(1, network_delegate.destroyed_requests());
3162}
3163
[email protected]c2911d72011-10-03 22:16:363164// Tests that the network delegate can synchronously complete OnAuthRequired
3165// by cancelling authentication.
3166TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3167 ASSERT_TRUE(test_server_.Start());
3168
3169 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303170 BlockingNetworkDelegate network_delegate(
3171 BlockingNetworkDelegate::SYNCHRONOUS);
3172 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363173 network_delegate.set_auth_retval(
3174 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3175
[email protected]ef2bf422012-05-11 03:27:093176 TestURLRequestContext context(true);
3177 context.set_network_delegate(&network_delegate);
3178 context.Init();
[email protected]c2911d72011-10-03 22:16:363179
3180 {
3181 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193182 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363183 r.Start();
[email protected]255620da2013-08-19 13:14:293184 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363185
3186 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3187 EXPECT_EQ(OK, r.status().error());
3188 EXPECT_EQ(401, r.GetResponseCode());
3189 EXPECT_FALSE(d.auth_required_called());
3190 EXPECT_EQ(1, network_delegate.created_requests());
3191 EXPECT_EQ(0, network_delegate.destroyed_requests());
3192 }
3193 EXPECT_EQ(1, network_delegate.destroyed_requests());
3194}
3195
3196// Tests that the network delegate can asynchronously complete OnAuthRequired
3197// by taking no action. This indicates that the NetworkDelegate does not want
3198// to handle the challenge, and is passing the buck along to the
3199// URLRequest::Delegate.
3200TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3201 ASSERT_TRUE(test_server_.Start());
3202
3203 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303204 BlockingNetworkDelegate network_delegate(
3205 BlockingNetworkDelegate::AUTO_CALLBACK);
3206 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363207
[email protected]ef2bf422012-05-11 03:27:093208 TestURLRequestContext context(true);
3209 context.set_network_delegate(&network_delegate);
3210 context.Init();
[email protected]c2911d72011-10-03 22:16:363211
[email protected]f3cf9802011-10-28 18:44:583212 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363213
3214 {
3215 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193216 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363217 r.Start();
[email protected]255620da2013-08-19 13:14:293218 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363219
3220 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3221 EXPECT_EQ(0, r.status().error());
3222 EXPECT_EQ(200, r.GetResponseCode());
3223 EXPECT_TRUE(d.auth_required_called());
3224 EXPECT_EQ(1, network_delegate.created_requests());
3225 EXPECT_EQ(0, network_delegate.destroyed_requests());
3226 }
3227 EXPECT_EQ(1, network_delegate.destroyed_requests());
3228}
3229
3230// Tests that the network delegate can asynchronously complete OnAuthRequired
3231// by setting credentials.
3232TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3233 ASSERT_TRUE(test_server_.Start());
3234
3235 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303236 BlockingNetworkDelegate network_delegate(
3237 BlockingNetworkDelegate::AUTO_CALLBACK);
3238 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363239 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363240 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3241
[email protected]f3cf9802011-10-28 18:44:583242 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363243 network_delegate.set_auth_credentials(auth_credentials);
3244
[email protected]ef2bf422012-05-11 03:27:093245 TestURLRequestContext context(true);
3246 context.set_network_delegate(&network_delegate);
3247 context.Init();
[email protected]c2911d72011-10-03 22:16:363248
3249 {
3250 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193251 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363252 r.Start();
[email protected]255620da2013-08-19 13:14:293253 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363254
3255 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3256 EXPECT_EQ(0, r.status().error());
3257
3258 EXPECT_EQ(200, r.GetResponseCode());
3259 EXPECT_FALSE(d.auth_required_called());
3260 EXPECT_EQ(1, network_delegate.created_requests());
3261 EXPECT_EQ(0, network_delegate.destroyed_requests());
3262 }
3263 EXPECT_EQ(1, network_delegate.destroyed_requests());
3264}
3265
3266// Tests that the network delegate can asynchronously complete OnAuthRequired
3267// by cancelling authentication.
3268TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3269 ASSERT_TRUE(test_server_.Start());
3270
3271 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303272 BlockingNetworkDelegate network_delegate(
3273 BlockingNetworkDelegate::AUTO_CALLBACK);
3274 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363275 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363276 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3277
[email protected]ef2bf422012-05-11 03:27:093278 TestURLRequestContext context(true);
3279 context.set_network_delegate(&network_delegate);
3280 context.Init();
[email protected]c2911d72011-10-03 22:16:363281
3282 {
3283 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193284 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363285 r.Start();
[email protected]255620da2013-08-19 13:14:293286 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363287
3288 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3289 EXPECT_EQ(OK, r.status().error());
3290 EXPECT_EQ(401, r.GetResponseCode());
3291 EXPECT_FALSE(d.auth_required_called());
3292 EXPECT_EQ(1, network_delegate.created_requests());
3293 EXPECT_EQ(0, network_delegate.destroyed_requests());
3294 }
3295 EXPECT_EQ(1, network_delegate.destroyed_requests());
3296}
3297
[email protected]9045b8822012-01-13 20:35:353298// Tests that we can handle when a network request was canceled while we were
3299// waiting for the network delegate.
3300// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3301TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3302 ASSERT_TRUE(test_server_.Start());
3303
3304 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303305 BlockingNetworkDelegate network_delegate(
3306 BlockingNetworkDelegate::USER_CALLBACK);
3307 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353308
[email protected]ef2bf422012-05-11 03:27:093309 TestURLRequestContext context(true);
3310 context.set_network_delegate(&network_delegate);
3311 context.Init();
[email protected]9045b8822012-01-13 20:35:353312
3313 {
[email protected]2ca01e52013-10-31 22:05:193314 URLRequest r(
3315 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353316
3317 r.Start();
[email protected]255620da2013-08-19 13:14:293318 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303319 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3320 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353321 EXPECT_EQ(0, network_delegate.completed_requests());
3322 // Cancel before callback.
3323 r.Cancel();
3324 // Ensure that network delegate is notified.
3325 EXPECT_EQ(1, network_delegate.completed_requests());
3326 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3327 EXPECT_EQ(ERR_ABORTED, r.status().error());
3328 EXPECT_EQ(1, network_delegate.created_requests());
3329 EXPECT_EQ(0, network_delegate.destroyed_requests());
3330 }
3331 EXPECT_EQ(1, network_delegate.destroyed_requests());
3332}
3333
3334// Tests that we can handle when a network request was canceled while we were
3335// waiting for the network delegate.
3336// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3337TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3338 ASSERT_TRUE(test_server_.Start());
3339
3340 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303341 BlockingNetworkDelegate network_delegate(
3342 BlockingNetworkDelegate::USER_CALLBACK);
3343 network_delegate.set_block_on(
3344 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353345
[email protected]ef2bf422012-05-11 03:27:093346 TestURLRequestContext context(true);
3347 context.set_network_delegate(&network_delegate);
3348 context.Init();
[email protected]9045b8822012-01-13 20:35:353349
3350 {
[email protected]2ca01e52013-10-31 22:05:193351 URLRequest r(
3352 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353353
3354 r.Start();
[email protected]255620da2013-08-19 13:14:293355 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303356 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3357 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353358 EXPECT_EQ(0, network_delegate.completed_requests());
3359 // Cancel before callback.
3360 r.Cancel();
3361 // Ensure that network delegate is notified.
3362 EXPECT_EQ(1, network_delegate.completed_requests());
3363 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3364 EXPECT_EQ(ERR_ABORTED, r.status().error());
3365 EXPECT_EQ(1, network_delegate.created_requests());
3366 EXPECT_EQ(0, network_delegate.destroyed_requests());
3367 }
3368 EXPECT_EQ(1, network_delegate.destroyed_requests());
3369}
3370
3371// Tests that we can handle when a network request was canceled while we were
3372// waiting for the network delegate.
3373// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3374TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3375 ASSERT_TRUE(test_server_.Start());
3376
3377 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303378 BlockingNetworkDelegate network_delegate(
3379 BlockingNetworkDelegate::USER_CALLBACK);
3380 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353381
[email protected]ef2bf422012-05-11 03:27:093382 TestURLRequestContext context(true);
3383 context.set_network_delegate(&network_delegate);
3384 context.Init();
[email protected]9045b8822012-01-13 20:35:353385
3386 {
[email protected]2ca01e52013-10-31 22:05:193387 URLRequest r(
3388 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353389
3390 r.Start();
[email protected]255620da2013-08-19 13:14:293391 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303392 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3393 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353394 EXPECT_EQ(0, network_delegate.completed_requests());
3395 // Cancel before callback.
3396 r.Cancel();
3397 // Ensure that network delegate is notified.
3398 EXPECT_EQ(1, network_delegate.completed_requests());
3399 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3400 EXPECT_EQ(ERR_ABORTED, r.status().error());
3401 EXPECT_EQ(1, network_delegate.created_requests());
3402 EXPECT_EQ(0, network_delegate.destroyed_requests());
3403 }
3404 EXPECT_EQ(1, network_delegate.destroyed_requests());
3405}
3406
3407// Tests that we can handle when a network request was canceled while we were
3408// waiting for the network delegate.
3409// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023410TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353411 ASSERT_TRUE(test_server_.Start());
3412
3413 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303414 BlockingNetworkDelegate network_delegate(
3415 BlockingNetworkDelegate::USER_CALLBACK);
3416 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353417
[email protected]ef2bf422012-05-11 03:27:093418 TestURLRequestContext context(true);
3419 context.set_network_delegate(&network_delegate);
3420 context.Init();
[email protected]9045b8822012-01-13 20:35:353421
3422 {
[email protected]2ca01e52013-10-31 22:05:193423 URLRequest r(
3424 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353425
3426 r.Start();
[email protected]255620da2013-08-19 13:14:293427 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303428 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3429 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353430 EXPECT_EQ(0, network_delegate.completed_requests());
3431 // Cancel before callback.
3432 r.Cancel();
3433 // Ensure that network delegate is notified.
3434 EXPECT_EQ(1, network_delegate.completed_requests());
3435 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3436 EXPECT_EQ(ERR_ABORTED, r.status().error());
3437 EXPECT_EQ(1, network_delegate.created_requests());
3438 EXPECT_EQ(0, network_delegate.destroyed_requests());
3439 }
3440 EXPECT_EQ(1, network_delegate.destroyed_requests());
3441}
3442
[email protected]95409e12010-08-17 20:07:113443// In this unit test, we're using the HTTPTestServer as a proxy server and
3444// issuing a CONNECT request with the magic host name "www.server-auth.com".
3445// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353446TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113447 ASSERT_TRUE(test_server_.Start());
3448
[email protected]ceefd7fd2012-11-29 00:36:243449 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043450 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193451 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503452
[email protected]dc651782009-02-14 01:45:083453 TestDelegate d;
3454 {
[email protected]2ca01e52013-10-31 22:05:193455 URLRequest r(
3456 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]dc651782009-02-14 01:45:083457
3458 r.Start();
3459 EXPECT_TRUE(r.is_pending());
3460
[email protected]255620da2013-08-19 13:14:293461 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083462
[email protected]7461a402011-03-24 23:19:513463 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:053464 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:083465 }
3466}
3467
[email protected]b89290212009-08-14 22:37:353468TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113469 ASSERT_TRUE(test_server_.Start());
3470
initial.commit586acc5fe2008-07-26 22:42:523471 TestDelegate d;
3472 {
[email protected]2ca01e52013-10-31 22:05:193473 URLRequest r(test_server_.GetURL(std::string()),
3474 DEFAULT_PRIORITY,
3475 &d,
3476 &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523477
3478 r.Start();
3479 EXPECT_TRUE(r.is_pending());
3480
[email protected]255620da2013-08-19 13:14:293481 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523482
3483 EXPECT_EQ(1, d.response_started_count());
3484 EXPECT_FALSE(d.received_data_before_response());
3485 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193486 EXPECT_EQ(test_server_.host_port_pair().host(),
3487 r.GetSocketAddress().host());
3488 EXPECT_EQ(test_server_.host_port_pair().port(),
3489 r.GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163490
[email protected]9e743cd2010-03-16 07:03:533491 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523492 }
initial.commit586acc5fe2008-07-26 22:42:523493}
3494
[email protected]263163f2012-06-14 22:40:343495// This test has the server send a large number of cookies to the client.
3496// To ensure that no number of cookies causes a crash, a galloping binary
3497// search is used to estimate that maximum number of cookies that are accepted
3498// by the browser. Beyond the maximum number, the request will fail with
3499// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303500#if defined(OS_WIN)
3501// http://crbug.com/177916
3502#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3503#else
3504#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3505#endif // defined(OS_WIN)
3506TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343507 ASSERT_TRUE(test_server_.Start());
3508
3509 int lower_bound = 0;
3510 int upper_bound = 1;
3511
3512 // Double the number of cookies until the response header limits are
3513 // exceeded.
3514 while (DoManyCookiesRequest(upper_bound)) {
3515 lower_bound = upper_bound;
3516 upper_bound *= 2;
3517 ASSERT_LT(upper_bound, 1000000);
3518 }
3519
3520 int tolerance = upper_bound * 0.005;
3521 if (tolerance < 2)
3522 tolerance = 2;
3523
3524 // Perform a binary search to find the highest possible number of cookies,
3525 // within the desired tolerance.
3526 while (upper_bound - lower_bound >= tolerance) {
3527 int num_cookies = (lower_bound + upper_bound) / 2;
3528
3529 if (DoManyCookiesRequest(num_cookies))
3530 lower_bound = num_cookies;
3531 else
3532 upper_bound = num_cookies;
3533 }
3534 // Success: the test did not crash.
3535}
3536
[email protected]b89290212009-08-14 22:37:353537TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113538 ASSERT_TRUE(test_server_.Start());
3539
initial.commit586acc5fe2008-07-26 22:42:523540 TestDelegate d;
3541 {
[email protected]2ca01e52013-10-31 22:05:193542 URLRequest r(test_server_.GetURL(std::string()),
3543 DEFAULT_PRIORITY,
3544 &d,
3545 &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523546
3547 r.Start();
3548 EXPECT_TRUE(r.is_pending());
3549
[email protected]255620da2013-08-19 13:14:293550 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523551
3552 EXPECT_EQ(1, d.response_started_count());
3553 EXPECT_FALSE(d.received_data_before_response());
3554 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193555 EXPECT_EQ(test_server_.host_port_pair().host(),
3556 r.GetSocketAddress().host());
3557 EXPECT_EQ(test_server_.host_port_pair().port(),
3558 r.GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523559 }
[email protected]5d7b373e2009-09-02 07:19:033560}
3561
[email protected]79e1fd62013-06-20 06:50:043562TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3563 ASSERT_TRUE(test_server_.Start());
3564
3565 TestDelegate d;
3566 {
3567 GURL test_url(test_server_.GetURL(std::string()));
[email protected]2ca01e52013-10-31 22:05:193568 URLRequest r(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:043569
3570 HttpRequestHeaders headers;
3571 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3572
3573 r.Start();
3574 EXPECT_TRUE(r.is_pending());
3575
[email protected]255620da2013-08-19 13:14:293576 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043577
3578 EXPECT_EQ(1, d.response_started_count());
3579 EXPECT_FALSE(d.received_data_before_response());
3580 EXPECT_NE(0, d.bytes_received());
3581 EXPECT_EQ(test_server_.host_port_pair().host(),
3582 r.GetSocketAddress().host());
3583 EXPECT_EQ(test_server_.host_port_pair().port(),
3584 r.GetSocketAddress().port());
3585
3586 EXPECT_TRUE(d.have_full_request_headers());
3587 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3588 }
3589}
3590
[email protected]58e32bb2013-01-21 18:23:253591TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3592 ASSERT_TRUE(test_server_.Start());
3593
3594 TestDelegate d;
3595 {
[email protected]2ca01e52013-10-31 22:05:193596 URLRequest r(test_server_.GetURL(std::string()),
3597 DEFAULT_PRIORITY,
3598 &d,
3599 &default_context_);
[email protected]58e32bb2013-01-21 18:23:253600
3601 r.Start();
3602 EXPECT_TRUE(r.is_pending());
3603
[email protected]255620da2013-08-19 13:14:293604 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253605
3606 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173607 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253608 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3609
3610 EXPECT_EQ(1, d.response_started_count());
3611 EXPECT_FALSE(d.received_data_before_response());
3612 EXPECT_NE(0, d.bytes_received());
3613 EXPECT_EQ(test_server_.host_port_pair().host(),
3614 r.GetSocketAddress().host());
3615 EXPECT_EQ(test_server_.host_port_pair().port(),
3616 r.GetSocketAddress().port());
3617 }
3618}
3619
[email protected]aad63572011-05-24 20:14:393620TEST_F(URLRequestTestHTTP, GetZippedTest) {
3621 ASSERT_TRUE(test_server_.Start());
3622
3623 // Parameter that specifies the Content-Length field in the response:
3624 // C - Compressed length.
3625 // U - Uncompressed length.
3626 // L - Large length (larger than both C & U).
3627 // M - Medium length (between C & U).
3628 // S - Small length (smaller than both C & U).
3629 const char test_parameters[] = "CULMS";
3630 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3631 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:443632 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:393633 // S has too little data, but we seem to accept it.
3634 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:373635 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:393636
3637 for (int i = 0; i < num_tests ; i++) {
3638 TestDelegate d;
3639 {
3640 std::string test_file =
3641 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3642 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:393643
[email protected]ceefd7fd2012-11-29 00:36:243644 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:093645 TestURLRequestContext context(true);
3646 context.set_network_delegate(&network_delegate);
3647 context.Init();
[email protected]87a09a92011-07-14 15:50:503648
[email protected]2ca01e52013-10-31 22:05:193649 URLRequest r(
3650 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, &context);
[email protected]aad63572011-05-24 20:14:393651 r.Start();
3652 EXPECT_TRUE(r.is_pending());
3653
[email protected]255620da2013-08-19 13:14:293654 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:393655
3656 EXPECT_EQ(1, d.response_started_count());
3657 EXPECT_FALSE(d.received_data_before_response());
3658 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3659 << " status = " << r.status().status()
[email protected]d0cc35b2011-09-08 12:02:053660 << " error = " << r.status().error();
[email protected]aad63572011-05-24 20:14:393661 if (test_expect_success[i]) {
3662 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3663 << " Parameter = \"" << test_file << "\"";
3664 } else {
3665 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]5543cbb2012-04-20 16:35:233666 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
[email protected]aad63572011-05-24 20:14:393667 << " Parameter = \"" << test_file << "\"";
3668 }
3669 }
3670 }
3671}
3672
[email protected]c044616e2013-02-20 02:01:263673TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
[email protected]95409e12010-08-17 20:07:113674 ASSERT_TRUE(test_server_.Start());
3675
[email protected]ce7d0cbc2013-05-03 18:57:223676 SpawnedTestServer https_test_server(
3677 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:153678 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:113679 ASSERT_TRUE(https_test_server.Start());
[email protected]7844480a2009-12-16 21:18:583680
3681 // An https server is sent a request with an https referer,
3682 // and responds with a redirect to an http url. The http
3683 // server should not be sent the referer.
[email protected]007b3f82013-04-09 08:46:453684 GURL http_destination = test_server_.GetURL(std::string());
[email protected]7844480a2009-12-16 21:18:583685 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193686 URLRequest req(
3687 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3688 DEFAULT_PRIORITY,
3689 &d,
3690 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:133691 req.SetReferrer("https://www.referrer.com/");
[email protected]7844480a2009-12-16 21:18:583692 req.Start();
[email protected]255620da2013-08-19 13:14:293693 base::RunLoop().Run();
[email protected]7844480a2009-12-16 21:18:583694
3695 EXPECT_EQ(1, d.response_started_count());
3696 EXPECT_EQ(1, d.received_redirect_count());
3697 EXPECT_EQ(http_destination, req.url());
3698 EXPECT_EQ(std::string(), req.referrer());
3699}
3700
[email protected]58e32bb2013-01-21 18:23:253701TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3702 ASSERT_TRUE(test_server_.Start());
3703
[email protected]007b3f82013-04-09 08:46:453704 GURL destination_url = test_server_.GetURL(std::string());
3705 GURL original_url =
3706 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:253707 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193708 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]58e32bb2013-01-21 18:23:253709 req.Start();
[email protected]255620da2013-08-19 13:14:293710 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253711
3712 EXPECT_EQ(1, d.response_started_count());
3713 EXPECT_EQ(1, d.received_redirect_count());
3714 EXPECT_EQ(destination_url, req.url());
3715 EXPECT_EQ(original_url, req.original_url());
3716 ASSERT_EQ(2U, req.url_chain().size());
3717 EXPECT_EQ(original_url, req.url_chain()[0]);
3718 EXPECT_EQ(destination_url, req.url_chain()[1]);
3719
3720 LoadTimingInfo load_timing_info_before_redirect;
3721 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3722 &load_timing_info_before_redirect));
3723 TestLoadTimingNotReused(load_timing_info_before_redirect,
3724 CONNECT_TIMING_HAS_DNS_TIMES);
3725
3726 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173727 req.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253728 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3729
3730 // Check that a new socket was used on redirect, since the server does not
3731 // supposed keep-alive sockets, and that the times before the redirect are
3732 // before the ones recorded for the second request.
3733 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3734 load_timing_info.socket_log_id);
3735 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3736 load_timing_info.connect_timing.connect_start);
3737}
3738
[email protected]8f1ac082011-04-19 21:14:133739TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3740 ASSERT_TRUE(test_server_.Start());
3741
[email protected]007b3f82013-04-09 08:46:453742 GURL destination_url = test_server_.GetURL(std::string());
3743 GURL middle_redirect_url =
3744 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:133745 GURL original_url = test_server_.GetURL(
3746 "server-redirect?" + middle_redirect_url.spec());
3747 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193748 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]8f1ac082011-04-19 21:14:133749 req.Start();
[email protected]255620da2013-08-19 13:14:293750 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:133751
3752 EXPECT_EQ(1, d.response_started_count());
3753 EXPECT_EQ(2, d.received_redirect_count());
3754 EXPECT_EQ(destination_url, req.url());
3755 EXPECT_EQ(original_url, req.original_url());
3756 ASSERT_EQ(3U, req.url_chain().size());
3757 EXPECT_EQ(original_url, req.url_chain()[0]);
3758 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3759 EXPECT_EQ(destination_url, req.url_chain()[2]);
3760}
3761
[email protected]abe1c4a2013-10-25 19:28:513762// First and second pieces of information logged by delegates to URLRequests.
3763const char kFirstDelegateInfo[] = "Wonderful delegate";
3764const char kSecondDelegateInfo[] = "Exciting delegate";
3765
3766// Logs delegate information to a URLRequest. The first string is logged
3767// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3768// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3769// another asynchronous call is used to clear the delegate information
3770// before calling a callback. The object then deletes itself.
3771class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3772 public:
3773 typedef base::Callback<void()> Callback;
3774
3775 // Each time delegate information is added to the URLRequest, the resulting
3776 // load state is checked. The expected load state after each request is
3777 // passed in as an argument.
3778 static void Run(URLRequest* url_request,
3779 LoadState expected_first_load_state,
3780 LoadState expected_second_load_state,
3781 LoadState expected_third_load_state,
3782 const Callback& callback) {
3783 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3784 url_request,
3785 expected_first_load_state,
3786 expected_second_load_state,
3787 expected_third_load_state,
3788 callback);
3789 logger->Start();
3790 }
3791
3792 // Checks that the log entries, starting with log_position, contain the
3793 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3794 // recorded. Returns the index of entry after the expected number of
3795 // events this logged, or entries.size() if there aren't enough entries.
3796 static size_t CheckDelegateInfo(
3797 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3798 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3799 if (log_position + 3 >= entries.size()) {
3800 ADD_FAILURE() << "Not enough log entries";
3801 return entries.size();
3802 }
3803 std::string delegate_info;
3804 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3805 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3806 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3807 &delegate_info));
3808 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3809
3810 ++log_position;
3811 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3812 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3813
3814 ++log_position;
3815 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3816 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3817 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3818 &delegate_info));
3819 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3820
3821 ++log_position;
3822 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3823 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3824
3825 return log_position + 1;
3826 }
3827
3828 private:
3829 friend class base::RefCounted<AsyncDelegateLogger>;
3830
3831 AsyncDelegateLogger(URLRequest* url_request,
3832 LoadState expected_first_load_state,
3833 LoadState expected_second_load_state,
3834 LoadState expected_third_load_state,
3835 const Callback& callback)
3836 : url_request_(url_request),
3837 expected_first_load_state_(expected_first_load_state),
3838 expected_second_load_state_(expected_second_load_state),
3839 expected_third_load_state_(expected_third_load_state),
3840 callback_(callback) {
3841 }
3842
3843 ~AsyncDelegateLogger() {}
3844
3845 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:533846 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:513847 LoadStateWithParam load_state = url_request_->GetLoadState();
3848 EXPECT_EQ(expected_first_load_state_, load_state.state);
3849 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3850 base::MessageLoop::current()->PostTask(
3851 FROM_HERE,
3852 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3853 }
3854
3855 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:533856 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:513857 LoadStateWithParam load_state = url_request_->GetLoadState();
3858 EXPECT_EQ(expected_second_load_state_, load_state.state);
3859 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3860 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3861 } else {
3862 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3863 }
3864 base::MessageLoop::current()->PostTask(
3865 FROM_HERE,
3866 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3867 }
3868
3869 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:533870 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:513871 LoadStateWithParam load_state = url_request_->GetLoadState();
3872 EXPECT_EQ(expected_third_load_state_, load_state.state);
3873 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3874 EXPECT_EQ(string16(), load_state.param);
3875 callback_.Run();
3876 }
3877
3878 URLRequest* url_request_;
3879 const int expected_first_load_state_;
3880 const int expected_second_load_state_;
3881 const int expected_third_load_state_;
3882 const Callback callback_;
3883
3884 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3885};
3886
3887// NetworkDelegate that logs delegate information before a request is started,
3888// before headers are sent, when headers are read, and when auth information
3889// is requested. Uses AsyncDelegateLogger.
3890class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3891 public:
3892 AsyncLoggingNetworkDelegate() {}
3893 virtual ~AsyncLoggingNetworkDelegate() {}
3894
3895 // NetworkDelegate implementation.
3896 virtual int OnBeforeURLRequest(URLRequest* request,
3897 const CompletionCallback& callback,
3898 GURL* new_url) OVERRIDE {
3899 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3900 return RunCallbackAsynchronously(request, callback);
3901 }
3902
3903 virtual int OnBeforeSendHeaders(URLRequest* request,
3904 const CompletionCallback& callback,
3905 HttpRequestHeaders* headers) OVERRIDE {
3906 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3907 return RunCallbackAsynchronously(request, callback);
3908 }
3909
3910 virtual int OnHeadersReceived(
3911 URLRequest* request,
3912 const CompletionCallback& callback,
3913 const HttpResponseHeaders* original_response_headers,
3914 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE {
3915 TestNetworkDelegate::OnHeadersReceived(request, callback,
3916 original_response_headers,
3917 override_response_headers);
3918 return RunCallbackAsynchronously(request, callback);
3919 }
3920
3921 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
3922 URLRequest* request,
3923 const AuthChallengeInfo& auth_info,
3924 const AuthCallback& callback,
3925 AuthCredentials* credentials) OVERRIDE {
3926 AsyncDelegateLogger::Run(
3927 request,
3928 LOAD_STATE_WAITING_FOR_DELEGATE,
3929 LOAD_STATE_WAITING_FOR_DELEGATE,
3930 LOAD_STATE_WAITING_FOR_DELEGATE,
3931 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
3932 callback, credentials));
3933 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
3934 }
3935
3936 private:
3937 static int RunCallbackAsynchronously(
3938 URLRequest* request,
3939 const CompletionCallback& callback) {
3940 AsyncDelegateLogger::Run(
3941 request,
3942 LOAD_STATE_WAITING_FOR_DELEGATE,
3943 LOAD_STATE_WAITING_FOR_DELEGATE,
3944 LOAD_STATE_WAITING_FOR_DELEGATE,
3945 base::Bind(callback, OK));
3946 return ERR_IO_PENDING;
3947 }
3948
3949 static void SetAuthAndResume(const AuthCallback& callback,
3950 AuthCredentials* credentials) {
3951 *credentials = AuthCredentials(kUser, kSecret);
3952 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3953 }
3954
3955 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
3956};
3957
3958// URLRequest::Delegate that logs delegate information when the headers
3959// are received, when each read completes, and during redirects. Uses
3960// AsyncDelegateLogger. Can optionally cancel a request in any phase.
3961//
3962// Inherits from TestDelegate to reuse the TestDelegate code to handle
3963// advancing to the next step in most cases, as well as cancellation.
3964class AsyncLoggingUrlRequestDelegate : public TestDelegate {
3965 public:
3966 enum CancelStage {
3967 NO_CANCEL = 0,
3968 CANCEL_ON_RECEIVED_REDIRECT,
3969 CANCEL_ON_RESPONSE_STARTED,
3970 CANCEL_ON_READ_COMPLETED
3971 };
3972
3973 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
3974 : cancel_stage_(cancel_stage) {
3975 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
3976 set_cancel_in_received_redirect(true);
3977 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
3978 set_cancel_in_response_started(true);
3979 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
3980 set_cancel_in_received_data(true);
3981 }
3982 virtual ~AsyncLoggingUrlRequestDelegate() {}
3983
3984 // URLRequest::Delegate implementation:
3985 void virtual OnReceivedRedirect(URLRequest* request,
3986 const GURL& new_url,
3987 bool* defer_redirect) OVERRIDE {
3988 *defer_redirect = true;
3989 AsyncDelegateLogger::Run(
3990 request,
3991 LOAD_STATE_WAITING_FOR_DELEGATE,
3992 LOAD_STATE_WAITING_FOR_DELEGATE,
3993 LOAD_STATE_WAITING_FOR_DELEGATE,
3994 base::Bind(
3995 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
3996 base::Unretained(this), request, new_url));
3997 }
3998
3999 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4000 AsyncDelegateLogger::Run(
4001 request,
4002 LOAD_STATE_WAITING_FOR_DELEGATE,
4003 LOAD_STATE_WAITING_FOR_DELEGATE,
4004 LOAD_STATE_WAITING_FOR_DELEGATE,
4005 base::Bind(
4006 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4007 base::Unretained(this), request));
4008 }
4009
4010 virtual void OnReadCompleted(URLRequest* request,
4011 int bytes_read) OVERRIDE {
4012 AsyncDelegateLogger::Run(
4013 request,
4014 LOAD_STATE_IDLE,
4015 LOAD_STATE_IDLE,
4016 LOAD_STATE_IDLE,
4017 base::Bind(
4018 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4019 base::Unretained(this), request, bytes_read));
4020 }
4021
4022 private:
4023 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4024 const GURL& new_url) {
4025 bool defer_redirect = false;
4026 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
4027 // FollowDeferredRedirect should not be called after cancellation.
4028 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4029 return;
4030 if (!defer_redirect)
4031 request->FollowDeferredRedirect();
4032 }
4033
4034 void OnResponseStartedLoggingComplete(URLRequest* request) {
4035 // The parent class continues the request.
4036 TestDelegate::OnResponseStarted(request);
4037 }
4038
4039 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4040 // The parent class continues the request.
4041 TestDelegate::OnReadCompleted(request, bytes_read);
4042 }
4043
4044 const CancelStage cancel_stage_;
4045
4046 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4047};
4048
4049// Tests handling of delegate info before a request starts.
4050TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4051 ASSERT_TRUE(test_server_.Start());
4052
4053 TestDelegate request_delegate;
4054 TestURLRequestContext context(true);
4055 context.set_network_delegate(NULL);
4056 context.set_net_log(&net_log_);
4057 context.Init();
4058
4059 {
4060 URLRequest r(test_server_.GetURL("empty.html"),
[email protected]2ca01e52013-10-31 22:05:194061 DEFAULT_PRIORITY,
4062 &request_delegate,
4063 &context);
[email protected]abe1c4a2013-10-25 19:28:514064 LoadStateWithParam load_state = r.GetLoadState();
4065 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4066 EXPECT_EQ(string16(), load_state.param);
4067
4068 AsyncDelegateLogger::Run(
4069 &r,
4070 LOAD_STATE_WAITING_FOR_DELEGATE,
4071 LOAD_STATE_WAITING_FOR_DELEGATE,
4072 LOAD_STATE_IDLE,
4073 base::Bind(&URLRequest::Start, base::Unretained(&r)));
4074
4075 base::RunLoop().Run();
4076
4077 EXPECT_EQ(200, r.GetResponseCode());
4078 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4079 }
4080
4081 CapturingNetLog::CapturedEntryList entries;
4082 net_log_.GetEntries(&entries);
4083 size_t log_position = ExpectLogContainsSomewhereAfter(
4084 entries,
4085 0,
4086 NetLog::TYPE_DELEGATE_INFO,
4087 NetLog::PHASE_BEGIN);
4088
4089 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4090
4091 // Nothing else should add any delegate info to the request.
4092 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4093 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4094}
4095
4096// Tests handling of delegate info from a network delegate.
4097TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4098 ASSERT_TRUE(test_server_.Start());
4099
4100 TestDelegate request_delegate;
4101 AsyncLoggingNetworkDelegate network_delegate;
4102 TestURLRequestContext context(true);
4103 context.set_network_delegate(&network_delegate);
4104 context.set_net_log(&net_log_);
4105 context.Init();
4106
4107 {
4108 URLRequest r(test_server_.GetURL("simple.html"),
[email protected]2ca01e52013-10-31 22:05:194109 DEFAULT_PRIORITY,
4110 &request_delegate,
4111 &context);
[email protected]abe1c4a2013-10-25 19:28:514112 LoadStateWithParam load_state = r.GetLoadState();
4113 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4114 EXPECT_EQ(string16(), load_state.param);
4115
4116 r.Start();
4117 base::RunLoop().Run();
4118
4119 EXPECT_EQ(200, r.GetResponseCode());
4120 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4121 EXPECT_EQ(1, network_delegate.created_requests());
4122 EXPECT_EQ(0, network_delegate.destroyed_requests());
4123 }
4124 EXPECT_EQ(1, network_delegate.destroyed_requests());
4125
4126 size_t log_position = 0;
4127 CapturingNetLog::CapturedEntryList entries;
4128 net_log_.GetEntries(&entries);
4129 for (size_t i = 0; i < 3; ++i) {
4130 log_position = ExpectLogContainsSomewhereAfter(
4131 entries,
4132 log_position + 1,
4133 NetLog::TYPE_URL_REQUEST_DELEGATE,
4134 NetLog::PHASE_BEGIN);
4135
4136 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4137 log_position + 1);
4138
4139 ASSERT_LT(log_position, entries.size());
4140 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4141 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4142 }
4143
4144 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4145 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4146}
4147
4148// Tests handling of delegate info from a network delegate in the case of an
4149// HTTP redirect.
4150TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4151 ASSERT_TRUE(test_server_.Start());
4152
4153 TestDelegate request_delegate;
4154 AsyncLoggingNetworkDelegate network_delegate;
4155 TestURLRequestContext context(true);
4156 context.set_network_delegate(&network_delegate);
4157 context.set_net_log(&net_log_);
4158 context.Init();
4159
4160 {
4161 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194162 DEFAULT_PRIORITY,
4163 &request_delegate,
4164 &context);
[email protected]abe1c4a2013-10-25 19:28:514165 LoadStateWithParam load_state = r.GetLoadState();
4166 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4167 EXPECT_EQ(string16(), load_state.param);
4168
4169 r.Start();
4170 base::RunLoop().Run();
4171
4172 EXPECT_EQ(200, r.GetResponseCode());
4173 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4174 EXPECT_EQ(2, network_delegate.created_requests());
4175 EXPECT_EQ(0, network_delegate.destroyed_requests());
4176 }
4177 EXPECT_EQ(1, network_delegate.destroyed_requests());
4178
4179 size_t log_position = 0;
4180 CapturingNetLog::CapturedEntryList entries;
4181 net_log_.GetEntries(&entries);
4182 // The NetworkDelegate logged information in OnBeforeURLRequest,
4183 // OnBeforeSendHeaders, and OnHeadersReceived.
4184 for (size_t i = 0; i < 3; ++i) {
4185 log_position = ExpectLogContainsSomewhereAfter(
4186 entries,
4187 log_position + 1,
4188 NetLog::TYPE_URL_REQUEST_DELEGATE,
4189 NetLog::PHASE_BEGIN);
4190
4191 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4192 log_position + 1);
4193
4194 ASSERT_LT(log_position, entries.size());
4195 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4196 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4197 }
4198
4199 // The URLRequest::Delegate then gets informed about the redirect.
4200 log_position = ExpectLogContainsSomewhereAfter(
4201 entries,
4202 log_position + 1,
4203 NetLog::TYPE_URL_REQUEST_DELEGATE,
4204 NetLog::PHASE_BEGIN);
4205
4206 // The NetworkDelegate logged information in the same three events as before.
4207 for (size_t i = 0; i < 3; ++i) {
4208 log_position = ExpectLogContainsSomewhereAfter(
4209 entries,
4210 log_position + 1,
4211 NetLog::TYPE_URL_REQUEST_DELEGATE,
4212 NetLog::PHASE_BEGIN);
4213
4214 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4215 log_position + 1);
4216
4217 ASSERT_LT(log_position, entries.size());
4218 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4219 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4220 }
4221
4222 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4223 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4224}
4225
4226// Tests handling of delegate info from a network delegate in the case of HTTP
4227// AUTH.
4228TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4229 ASSERT_TRUE(test_server_.Start());
4230
4231 TestDelegate request_delegate;
4232 AsyncLoggingNetworkDelegate network_delegate;
4233 TestURLRequestContext context(true);
4234 context.set_network_delegate(&network_delegate);
4235 context.set_net_log(&net_log_);
4236 context.Init();
4237
4238 {
4239 URLRequest r(test_server_.GetURL("auth-basic"),
[email protected]2ca01e52013-10-31 22:05:194240 DEFAULT_PRIORITY,
4241 &request_delegate,
4242 &context);
[email protected]abe1c4a2013-10-25 19:28:514243 LoadStateWithParam load_state = r.GetLoadState();
4244 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4245 EXPECT_EQ(string16(), load_state.param);
4246
4247 r.Start();
4248 base::RunLoop().Run();
4249
4250 EXPECT_EQ(200, r.GetResponseCode());
4251 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4252 EXPECT_EQ(1, network_delegate.created_requests());
4253 EXPECT_EQ(0, network_delegate.destroyed_requests());
4254 }
4255 EXPECT_EQ(1, network_delegate.destroyed_requests());
4256
4257 size_t log_position = 0;
4258 CapturingNetLog::CapturedEntryList entries;
4259 net_log_.GetEntries(&entries);
4260 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4261 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4262 // OnBeforeURLRequest and OnBeforeSendHeaders.
4263 for (size_t i = 0; i < 6; ++i) {
4264 log_position = ExpectLogContainsSomewhereAfter(
4265 entries,
4266 log_position + 1,
4267 NetLog::TYPE_URL_REQUEST_DELEGATE,
4268 NetLog::PHASE_BEGIN);
4269
4270 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4271 log_position + 1);
4272
4273 ASSERT_LT(log_position, entries.size());
4274 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4275 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4276 }
4277
4278 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4279 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4280}
4281
4282// Tests handling of delegate info from a URLRequest::Delegate.
4283TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4284 ASSERT_TRUE(test_server_.Start());
4285
4286 AsyncLoggingUrlRequestDelegate request_delegate(
4287 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4288 TestURLRequestContext context(true);
4289 context.set_network_delegate(NULL);
4290 context.set_net_log(&net_log_);
4291 context.Init();
4292
4293 {
4294 // A chunked response with delays between chunks is used to make sure that
4295 // attempts by the URLRequest delegate to log information while reading the
4296 // body are ignored. Since they are ignored, this test is robust against
4297 // the possability of multiple reads being combined in the unlikely event
4298 // that it occurs.
4299 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
[email protected]2ca01e52013-10-31 22:05:194300 DEFAULT_PRIORITY,
4301 &request_delegate,
4302 &context);
[email protected]abe1c4a2013-10-25 19:28:514303 LoadStateWithParam load_state = r.GetLoadState();
4304 r.Start();
4305 base::RunLoop().Run();
4306
4307 EXPECT_EQ(200, r.GetResponseCode());
4308 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4309 }
4310
4311 CapturingNetLog::CapturedEntryList entries;
4312 net_log_.GetEntries(&entries);
4313
4314 // The delegate info should only have been logged on header complete. Other
4315 // times it should silently be ignored.
4316
4317 size_t log_position = ExpectLogContainsSomewhereAfter(
4318 entries,
4319 0,
4320 NetLog::TYPE_URL_REQUEST_DELEGATE,
4321 NetLog::PHASE_BEGIN);
4322
4323 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4324 log_position + 1);
4325
4326 ASSERT_LT(log_position, entries.size());
4327 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4328 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4329
4330 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4331 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4332 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4333 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4334}
4335
4336// Tests handling of delegate info from a URLRequest::Delegate in the case of
4337// an HTTP redirect.
4338TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4339 ASSERT_TRUE(test_server_.Start());
4340
4341 AsyncLoggingUrlRequestDelegate request_delegate(
4342 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4343 TestURLRequestContext context(true);
4344 context.set_network_delegate(NULL);
4345 context.set_net_log(&net_log_);
4346 context.Init();
4347
4348 {
4349 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194350 DEFAULT_PRIORITY,
4351 &request_delegate,
4352 &context);
[email protected]abe1c4a2013-10-25 19:28:514353 LoadStateWithParam load_state = r.GetLoadState();
4354 r.Start();
4355 base::RunLoop().Run();
4356
4357 EXPECT_EQ(200, r.GetResponseCode());
4358 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4359 }
4360
4361 CapturingNetLog::CapturedEntryList entries;
4362 net_log_.GetEntries(&entries);
4363
4364 // Delegate info should only have been logged in OnReceivedRedirect and
4365 // OnResponseStarted.
4366 size_t log_position = 0;
4367 for (int i = 0; i < 2; ++i) {
4368 log_position = ExpectLogContainsSomewhereAfter(
4369 entries,
4370 log_position,
4371 NetLog::TYPE_URL_REQUEST_DELEGATE,
4372 NetLog::PHASE_BEGIN);
4373
4374 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4375 log_position + 1);
4376
4377 ASSERT_LT(log_position, entries.size());
4378 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4379 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4380 }
4381
4382 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4383 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4384 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4385 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4386}
4387
4388// Tests handling of delegate info from a URLRequest::Delegate in the case of
4389// an HTTP redirect, with cancellation at various points.
4390TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4391 ASSERT_TRUE(test_server_.Start());
4392
4393 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4394 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4395 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4396 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4397 };
4398
4399 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4400 ++test_case) {
4401 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4402 TestURLRequestContext context(true);
4403 CapturingNetLog net_log;
4404 context.set_network_delegate(NULL);
4405 context.set_net_log(&net_log);
4406 context.Init();
4407
4408 {
4409 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194410 DEFAULT_PRIORITY,
4411 &request_delegate,
4412 &context);
[email protected]abe1c4a2013-10-25 19:28:514413 LoadStateWithParam load_state = r.GetLoadState();
4414 r.Start();
4415 base::RunLoop().Run();
4416 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4417 }
4418
4419 CapturingNetLog::CapturedEntryList entries;
4420 net_log.GetEntries(&entries);
4421
4422 // Delegate info is always logged in both OnReceivedRedirect and
4423 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4424 // OnResponseStarted delegate call is after cancellation, but logging is
4425 // still currently supported in that call.
4426 size_t log_position = 0;
4427 for (int i = 0; i < 2; ++i) {
4428 log_position = ExpectLogContainsSomewhereAfter(
4429 entries,
4430 log_position,
4431 NetLog::TYPE_URL_REQUEST_DELEGATE,
4432 NetLog::PHASE_BEGIN);
4433
4434 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4435 log_position + 1);
4436
4437 ASSERT_LT(log_position, entries.size());
4438 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4439 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4440 }
4441
4442 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4443 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4444 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4445 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4446 }
4447}
4448
[email protected]847c0fa92012-11-06 16:37:424449namespace {
4450
4451const char kExtraHeader[] = "Allow-Snafu";
4452const char kExtraValue[] = "fubar";
4453
4454class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164455 virtual void OnReceivedRedirect(net::URLRequest* request,
4456 const GURL& new_url,
4457 bool* defer_redirect) OVERRIDE {
[email protected]847c0fa92012-11-06 16:37:424458 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4459 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4460 }
4461};
4462
4463} // namespace
4464
4465TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4466 ASSERT_TRUE(test_server_.Start());
4467
4468 GURL destination_url = test_server_.GetURL(
4469 "echoheader?" + std::string(kExtraHeader));
4470 GURL original_url = test_server_.GetURL(
4471 "server-redirect?" + destination_url.spec());
4472 RedirectWithAdditionalHeadersDelegate d;
[email protected]2ca01e52013-10-31 22:05:194473 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]847c0fa92012-11-06 16:37:424474 req.Start();
[email protected]255620da2013-08-19 13:14:294475 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424476
4477 std::string value;
4478 const HttpRequestHeaders& headers = req.extra_request_headers();
4479 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4480 EXPECT_EQ(kExtraValue, value);
4481 EXPECT_FALSE(req.is_pending());
4482 EXPECT_FALSE(req.is_redirecting());
4483 EXPECT_EQ(kExtraValue, d.data_received());
4484}
4485
[email protected]251a1b92012-11-13 11:01:094486namespace {
4487
4488const char kExtraHeaderToRemove[] = "To-Be-Removed";
4489
4490class RedirectWithHeaderRemovalDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164491 virtual void OnReceivedRedirect(net::URLRequest* request,
[email protected]251a1b92012-11-13 11:01:094492 const GURL& new_url,
[email protected]46fadfd2013-02-06 09:40:164493 bool* defer_redirect) OVERRIDE {
[email protected]251a1b92012-11-13 11:01:094494 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4495 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4496 }
4497};
4498
4499} // namespace
4500
4501TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4502 ASSERT_TRUE(test_server_.Start());
4503
4504 GURL destination_url = test_server_.GetURL(
4505 "echoheader?" + std::string(kExtraHeaderToRemove));
4506 GURL original_url = test_server_.GetURL(
4507 "server-redirect?" + destination_url.spec());
4508 RedirectWithHeaderRemovalDelegate d;
[email protected]2ca01e52013-10-31 22:05:194509 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]251a1b92012-11-13 11:01:094510 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4511 req.Start();
[email protected]255620da2013-08-19 13:14:294512 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094513
4514 std::string value;
4515 const HttpRequestHeaders& headers = req.extra_request_headers();
4516 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4517 EXPECT_FALSE(req.is_pending());
4518 EXPECT_FALSE(req.is_redirecting());
4519 EXPECT_EQ("None", d.data_received());
4520}
4521
[email protected]316c1e5e2012-09-12 15:17:444522TEST_F(URLRequestTestHTTP, CancelTest) {
4523 TestDelegate d;
4524 {
[email protected]2ca01e52013-10-31 22:05:194525 URLRequest r(GURL("http://www.google.com/"),
4526 DEFAULT_PRIORITY,
4527 &d,
4528 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444529
4530 r.Start();
4531 EXPECT_TRUE(r.is_pending());
4532
4533 r.Cancel();
4534
[email protected]255620da2013-08-19 13:14:294535 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444536
4537 // We expect to receive OnResponseStarted even though the request has been
4538 // cancelled.
4539 EXPECT_EQ(1, d.response_started_count());
4540 EXPECT_EQ(0, d.bytes_received());
4541 EXPECT_FALSE(d.received_data_before_response());
4542 }
4543}
4544
4545TEST_F(URLRequestTestHTTP, CancelTest2) {
4546 ASSERT_TRUE(test_server_.Start());
4547
4548 TestDelegate d;
4549 {
[email protected]2ca01e52013-10-31 22:05:194550 URLRequest r(test_server_.GetURL(std::string()),
4551 DEFAULT_PRIORITY,
4552 &d,
4553 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444554
4555 d.set_cancel_in_response_started(true);
4556
4557 r.Start();
4558 EXPECT_TRUE(r.is_pending());
4559
[email protected]255620da2013-08-19 13:14:294560 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444561
4562 EXPECT_EQ(1, d.response_started_count());
4563 EXPECT_EQ(0, d.bytes_received());
4564 EXPECT_FALSE(d.received_data_before_response());
4565 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4566 }
4567}
4568
4569TEST_F(URLRequestTestHTTP, CancelTest3) {
4570 ASSERT_TRUE(test_server_.Start());
4571
4572 TestDelegate d;
4573 {
[email protected]2ca01e52013-10-31 22:05:194574 URLRequest r(test_server_.GetURL(std::string()),
4575 DEFAULT_PRIORITY,
4576 &d,
4577 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444578
4579 d.set_cancel_in_received_data(true);
4580
4581 r.Start();
4582 EXPECT_TRUE(r.is_pending());
4583
[email protected]255620da2013-08-19 13:14:294584 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444585
4586 EXPECT_EQ(1, d.response_started_count());
4587 // There is no guarantee about how much data was received
4588 // before the cancel was issued. It could have been 0 bytes,
4589 // or it could have been all the bytes.
4590 // EXPECT_EQ(0, d.bytes_received());
4591 EXPECT_FALSE(d.received_data_before_response());
4592 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4593 }
4594}
4595
4596TEST_F(URLRequestTestHTTP, CancelTest4) {
4597 ASSERT_TRUE(test_server_.Start());
4598
4599 TestDelegate d;
4600 {
[email protected]2ca01e52013-10-31 22:05:194601 URLRequest r(test_server_.GetURL(std::string()),
4602 DEFAULT_PRIORITY,
4603 &d,
4604 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444605
4606 r.Start();
4607 EXPECT_TRUE(r.is_pending());
4608
4609 // The request will be implicitly canceled when it is destroyed. The
4610 // test delegate must not post a quit message when this happens because
4611 // this test doesn't actually have a message loop. The quit message would
4612 // get put on this thread's message queue and the next test would exit
4613 // early, causing problems.
4614 d.set_quit_on_complete(false);
4615 }
4616 // expect things to just cleanup properly.
4617
4618 // we won't actually get a received reponse here because we've never run the
4619 // message loop
4620 EXPECT_FALSE(d.received_data_before_response());
4621 EXPECT_EQ(0, d.bytes_received());
4622}
4623
4624TEST_F(URLRequestTestHTTP, CancelTest5) {
4625 ASSERT_TRUE(test_server_.Start());
4626
4627 // populate cache
4628 {
4629 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194630 URLRequest r(test_server_.GetURL("cachetime"),
4631 DEFAULT_PRIORITY,
4632 &d,
4633 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444634 r.Start();
[email protected]255620da2013-08-19 13:14:294635 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444636 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4637 }
4638
4639 // cancel read from cache (see bug 990242)
4640 {
4641 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194642 URLRequest r(test_server_.GetURL("cachetime"),
4643 DEFAULT_PRIORITY,
4644 &d,
4645 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444646 r.Start();
4647 r.Cancel();
[email protected]255620da2013-08-19 13:14:294648 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444649
4650 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4651 EXPECT_EQ(1, d.response_started_count());
4652 EXPECT_EQ(0, d.bytes_received());
4653 EXPECT_FALSE(d.received_data_before_response());
4654 }
4655}
4656
4657TEST_F(URLRequestTestHTTP, PostTest) {
4658 ASSERT_TRUE(test_server_.Start());
4659 HTTPUploadDataOperationTest("POST");
4660}
4661
4662TEST_F(URLRequestTestHTTP, PutTest) {
4663 ASSERT_TRUE(test_server_.Start());
4664 HTTPUploadDataOperationTest("PUT");
4665}
4666
4667TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4668 ASSERT_TRUE(test_server_.Start());
4669
4670 TestDelegate d;
4671 {
[email protected]2ca01e52013-10-31 22:05:194672 URLRequest r(
4673 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444674 r.set_method("POST");
4675
4676 r.Start();
4677 EXPECT_TRUE(r.is_pending());
4678
[email protected]255620da2013-08-19 13:14:294679 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444680
[email protected]329b68b2012-11-14 17:54:274681 ASSERT_EQ(1, d.response_started_count())
4682 << "request failed: " << r.status().status()
4683 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444684
4685 EXPECT_FALSE(d.received_data_before_response());
4686 EXPECT_TRUE(d.data_received().empty());
4687 }
4688}
4689
4690TEST_F(URLRequestTestHTTP, PostFileTest) {
4691 ASSERT_TRUE(test_server_.Start());
4692
4693 TestDelegate d;
4694 {
[email protected]2ca01e52013-10-31 22:05:194695 URLRequest r(
4696 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444697 r.set_method("POST");
4698
[email protected]6cdfd7f2013-02-08 20:40:154699 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:444700 PathService::Get(base::DIR_EXE, &dir);
4701 file_util::SetCurrentDirectory(dir);
4702
[email protected]f288ef02012-12-15 20:28:284703 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:444704
[email protected]6cdfd7f2013-02-08 20:40:154705 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:444706 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4707 path = path.Append(FILE_PATH_LITERAL("net"));
4708 path = path.Append(FILE_PATH_LITERAL("data"));
4709 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4710 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:364711 element_readers.push_back(
4712 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4713 path,
4714 0,
4715 kuint64max,
4716 base::Time()));
[email protected]96c77a72013-09-24 09:49:204717 r.set_upload(make_scoped_ptr(
4718 new UploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:444719
4720 r.Start();
4721 EXPECT_TRUE(r.is_pending());
4722
[email protected]255620da2013-08-19 13:14:294723 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444724
[email protected]329b68b2012-11-14 17:54:274725 int64 size = 0;
[email protected]56285702013-12-04 18:22:494726 ASSERT_EQ(true, base::GetFileSize(path, &size));
[email protected]4356f0f2013-04-07 00:58:174727 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:444728
[email protected]329b68b2012-11-14 17:54:274729 ASSERT_EQ(size, file_util::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:444730
[email protected]329b68b2012-11-14 17:54:274731 ASSERT_EQ(1, d.response_started_count())
4732 << "request failed: " << r.status().status()
4733 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444734
4735 EXPECT_FALSE(d.received_data_before_response());
4736
[email protected]329b68b2012-11-14 17:54:274737 EXPECT_EQ(size, d.bytes_received());
4738 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:444739 }
4740}
4741
[email protected]999dd8c2013-11-12 06:45:544742TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4743 ASSERT_TRUE(test_server_.Start());
4744
4745 TestDelegate d;
4746 {
4747 URLRequest r(test_server_.GetURL("echo"), DEFAULT_PRIORITY,
4748 &d, &default_context_);
4749 r.set_method("POST");
4750
4751 ScopedVector<UploadElementReader> element_readers;
4752
4753 element_readers.push_back(new UploadFileElementReader(
4754 base::MessageLoopProxy::current().get(),
4755 base::FilePath(FILE_PATH_LITERAL(
4756 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4757 0,
4758 kuint64max,
4759 base::Time()));
4760 r.set_upload(make_scoped_ptr(
4761 new UploadDataStream(element_readers.Pass(), 0)));
4762
4763 r.Start();
4764 EXPECT_TRUE(r.is_pending());
4765
4766 base::RunLoop().Run();
4767
4768 // TODO(tzik): Remove this #if after we stop supporting Chrome Frame.
4769 // http://crbug.com/317432
4770#if defined(CHROME_FRAME_NET_TESTS)
4771 EXPECT_FALSE(d.request_failed());
4772 EXPECT_FALSE(d.received_data_before_response());
4773 EXPECT_EQ(0, d.bytes_received());
4774 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4775 EXPECT_EQ(OK, r.status().error());
4776#else
4777 EXPECT_TRUE(d.request_failed());
4778 EXPECT_FALSE(d.received_data_before_response());
4779 EXPECT_EQ(0, d.bytes_received());
4780 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
4781 EXPECT_EQ(ERR_FILE_NOT_FOUND, r.status().error());
4782#endif // defined(CHROME_FRAME_NET_TESTS)
4783 }
4784}
4785
[email protected]316c1e5e2012-09-12 15:17:444786TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4787 ASSERT_TRUE(test_server_.Start());
4788
4789 TestDelegate d;
4790 {
[email protected]2ca01e52013-10-31 22:05:194791 URLRequest r(
4792 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444793 r.EnableChunkedUpload();
4794 r.set_method("POST");
4795 AddChunksToUpload(&r);
4796 r.Start();
4797 EXPECT_TRUE(r.is_pending());
4798
[email protected]255620da2013-08-19 13:14:294799 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444800
4801 VerifyReceivedDataMatchesChunks(&r, &d);
4802 }
4803}
4804
[email protected]329b68b2012-11-14 17:54:274805TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4806 ASSERT_TRUE(test_server_.Start());
4807
4808 TestDelegate d;
4809 {
[email protected]2ca01e52013-10-31 22:05:194810 URLRequest r(
4811 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]329b68b2012-11-14 17:54:274812 r.EnableChunkedUpload();
4813 r.set_method("POST");
4814 r.Start();
4815 EXPECT_TRUE(r.is_pending());
4816 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294817 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:274818
4819 VerifyReceivedDataMatchesChunks(&r, &d);
4820 }
4821}
4822
[email protected]316c1e5e2012-09-12 15:17:444823TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4824 ASSERT_TRUE(test_server_.Start());
4825
4826 TestDelegate d;
4827 {
[email protected]2ca01e52013-10-31 22:05:194828 URLRequest r(
4829 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444830 r.EnableChunkedUpload();
4831 r.set_method("POST");
4832 r.Start();
4833 EXPECT_TRUE(r.is_pending());
4834
[email protected]255620da2013-08-19 13:14:294835 base::RunLoop().RunUntilIdle();
[email protected]316c1e5e2012-09-12 15:17:444836 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294837 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444838
4839 VerifyReceivedDataMatchesChunks(&r, &d);
4840 }
4841}
4842
4843TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4844 ASSERT_TRUE(test_server_.Start());
4845
4846 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194847 URLRequest req(test_server_.GetURL("files/with-headers.html"),
4848 DEFAULT_PRIORITY,
4849 &d,
4850 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444851 req.Start();
[email protected]255620da2013-08-19 13:14:294852 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444853
4854 const HttpResponseHeaders* headers = req.response_headers();
4855
4856 // Simple sanity check that response_info() accesses the same data.
4857 EXPECT_EQ(headers, req.response_info().headers.get());
4858
4859 std::string header;
4860 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4861 EXPECT_EQ("private", header);
4862
4863 header.clear();
4864 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4865 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4866
4867 // The response has two "X-Multiple-Entries" headers.
4868 // This verfies our output has them concatenated together.
4869 header.clear();
4870 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4871 EXPECT_EQ("a, b", header);
4872}
4873
[email protected]242d8562012-10-30 21:20:464874TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:224875 SpawnedTestServer::SSLOptions ssl_options;
4876 SpawnedTestServer https_test_server(
4877 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:464878 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154879 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:464880 ASSERT_TRUE(https_test_server.Start());
4881
4882 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194883 URLRequest request(https_test_server.GetURL("files/hsts-headers.html"),
4884 DEFAULT_PRIORITY,
4885 &d,
4886 &default_context_);
[email protected]242d8562012-10-30 21:20:464887 request.Start();
[email protected]255620da2013-08-19 13:14:294888 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:464889
4890 TransportSecurityState* security_state =
4891 default_context_.transport_security_state();
4892 bool sni_available = true;
4893 TransportSecurityState::DomainState domain_state;
4894 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034895 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]242d8562012-10-30 21:20:464896 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4897 domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:054898 EXPECT_TRUE(domain_state.sts_include_subdomains);
[email protected]22e045f2013-09-20 03:54:034899 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:274900#if defined(OS_ANDROID)
4901 // Android's CertVerifyProc does not (yet) handle pins.
4902#else
4903 EXPECT_FALSE(domain_state.HasPublicKeyPins());
4904#endif
4905}
4906
4907// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
4908// reject HPKP headers, and a test setting only HPKP headers will fail (no
4909// DomainState present because header rejected).
4910#if defined(OS_ANDROID)
4911#define MAYBE_ProcessPKP DISABLED_ProcessPKP
4912#else
4913#define MAYBE_ProcessPKP ProcessPKP
4914#endif
4915
4916// Tests that enabling HPKP on a domain does not affect the HSTS
4917// validity/expiration.
4918TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
4919 SpawnedTestServer::SSLOptions ssl_options;
4920 SpawnedTestServer https_test_server(
4921 SpawnedTestServer::TYPE_HTTPS,
4922 ssl_options,
4923 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4924 ASSERT_TRUE(https_test_server.Start());
4925
4926 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194927 URLRequest request(https_test_server.GetURL("files/hpkp-headers.html"),
4928 DEFAULT_PRIORITY,
4929 &d,
4930 &default_context_);
[email protected]37fd55fb2013-06-29 13:13:274931 request.Start();
[email protected]255620da2013-08-19 13:14:294932 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:274933
4934 TransportSecurityState* security_state =
4935 default_context_.transport_security_state();
4936 bool sni_available = true;
4937 TransportSecurityState::DomainState domain_state;
4938 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034939 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:274940 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
4941 domain_state.upgrade_mode);
4942 EXPECT_FALSE(domain_state.sts_include_subdomains);
4943 EXPECT_FALSE(domain_state.pkp_include_subdomains);
4944 EXPECT_TRUE(domain_state.HasPublicKeyPins());
4945 EXPECT_NE(domain_state.upgrade_expiry,
4946 domain_state.dynamic_spki_hashes_expiry);
[email protected]242d8562012-10-30 21:20:464947}
4948
4949TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:224950 SpawnedTestServer::SSLOptions ssl_options;
4951 SpawnedTestServer https_test_server(
4952 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:464953 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154954 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:464955 ASSERT_TRUE(https_test_server.Start());
4956
4957 TestDelegate d;
4958 URLRequest request(
4959 https_test_server.GetURL("files/hsts-multiple-headers.html"),
[email protected]2ca01e52013-10-31 22:05:194960 DEFAULT_PRIORITY,
[email protected]242d8562012-10-30 21:20:464961 &d,
4962 &default_context_);
4963 request.Start();
[email protected]255620da2013-08-19 13:14:294964 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:464965
4966 // We should have set parameters from the first header, not the second.
4967 TransportSecurityState* security_state =
4968 default_context_.transport_security_state();
4969 bool sni_available = true;
4970 TransportSecurityState::DomainState domain_state;
4971 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034972 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]242d8562012-10-30 21:20:464973 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4974 domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:054975 EXPECT_FALSE(domain_state.sts_include_subdomains);
4976 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]242d8562012-10-30 21:20:464977}
4978
[email protected]9f972ec2013-04-10 20:24:364979TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:224980 SpawnedTestServer::SSLOptions ssl_options;
4981 SpawnedTestServer https_test_server(
4982 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:364983 ssl_options,
4984 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4985 ASSERT_TRUE(https_test_server.Start());
4986
4987 TestDelegate d;
4988 URLRequest request(
4989 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
[email protected]2ca01e52013-10-31 22:05:194990 DEFAULT_PRIORITY,
[email protected]9f972ec2013-04-10 20:24:364991 &d,
4992 &default_context_);
4993 request.Start();
[email protected]255620da2013-08-19 13:14:294994 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:364995
4996 // We should have set parameters from the first header, not the second.
4997 TransportSecurityState* security_state =
4998 default_context_.transport_security_state();
4999 bool sni_available = true;
5000 TransportSecurityState::DomainState domain_state;
5001 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:035002 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]9f972ec2013-04-10 20:24:365003 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5004 domain_state.upgrade_mode);
5005#if defined(OS_ANDROID)
5006 // Android's CertVerifyProc does not (yet) handle pins.
5007#else
5008 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5009#endif
5010 EXPECT_NE(domain_state.upgrade_expiry,
5011 domain_state.dynamic_spki_hashes_expiry);
5012
[email protected]a165f092013-06-12 16:10:055013 // Even though there is an HSTS header asserting includeSubdomains, it is
5014 // the *second* such header, and we MUST process only the first.
5015 EXPECT_FALSE(domain_state.sts_include_subdomains);
5016 // includeSubdomains does not occur in the test HPKP header.
5017 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365018}
5019
[email protected]37fd55fb2013-06-29 13:13:275020// Tests that when multiple HPKP headers are present, asserting different
5021// policies, that only the first such policy is processed.
5022TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5023 SpawnedTestServer::SSLOptions ssl_options;
5024 SpawnedTestServer https_test_server(
5025 SpawnedTestServer::TYPE_HTTPS,
5026 ssl_options,
5027 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5028 ASSERT_TRUE(https_test_server.Start());
5029
5030 TestDelegate d;
5031 URLRequest request(
5032 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
[email protected]2ca01e52013-10-31 22:05:195033 DEFAULT_PRIORITY,
[email protected]37fd55fb2013-06-29 13:13:275034 &d,
5035 &default_context_);
5036 request.Start();
[email protected]255620da2013-08-19 13:14:295037 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275038
5039 TransportSecurityState* security_state =
5040 default_context_.transport_security_state();
5041 bool sni_available = true;
5042 TransportSecurityState::DomainState domain_state;
5043 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:035044 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275045 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5046 domain_state.upgrade_mode);
5047#if defined(OS_ANDROID)
5048 // Android's CertVerifyProc does not (yet) handle pins.
5049#else
5050 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5051#endif
5052 EXPECT_NE(domain_state.upgrade_expiry,
5053 domain_state.dynamic_spki_hashes_expiry);
5054
5055 EXPECT_TRUE(domain_state.sts_include_subdomains);
5056 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5057}
5058
[email protected]316c1e5e2012-09-12 15:17:445059TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5060 ASSERT_TRUE(test_server_.Start());
5061
5062 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195063 URLRequest req(test_server_.GetURL("files/content-type-normalization.html"),
5064 DEFAULT_PRIORITY,
5065 &d,
5066 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445067 req.Start();
[email protected]255620da2013-08-19 13:14:295068 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445069
5070 std::string mime_type;
5071 req.GetMimeType(&mime_type);
5072 EXPECT_EQ("text/html", mime_type);
5073
5074 std::string charset;
5075 req.GetCharset(&charset);
5076 EXPECT_EQ("utf-8", charset);
5077 req.Cancel();
5078}
5079
[email protected]e0f35c92013-05-08 16:04:345080TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictRedirects) {
5081 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5082 GURL file_url("file:///foo.txt");
5083 GURL data_url("data:,foo");
[email protected]255620da2013-08-19 13:14:295084 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
[email protected]e0f35c92013-05-08 16:04:345085 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5086 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025087 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345088
5089 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5090 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
[email protected]588614c22013-08-16 00:09:025091 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345092}
5093
[email protected]588614c22013-08-16 00:09:025094TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445095 ASSERT_TRUE(test_server_.Start());
5096
5097 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195098 URLRequest req(test_server_.GetURL("files/redirect-to-file.html"),
5099 DEFAULT_PRIORITY,
5100 &d,
5101 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445102 req.Start();
[email protected]255620da2013-08-19 13:14:295103 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445104
5105 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5106 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5107}
5108
[email protected]588614c22013-08-16 00:09:025109TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5110 ASSERT_TRUE(test_server_.Start());
5111
5112 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195113 URLRequest req(test_server_.GetURL("files/redirect-to-data.html"),
5114 DEFAULT_PRIORITY,
5115 &d,
5116 &default_context_);
[email protected]588614c22013-08-16 00:09:025117 req.Start();
5118 base::MessageLoop::current()->Run();
5119
5120 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5121 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5122}
5123
[email protected]316c1e5e2012-09-12 15:17:445124TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5125 ASSERT_TRUE(test_server_.Start());
5126
5127 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195128 URLRequest req(test_server_.GetURL("files/redirect-to-invalid-url.html"),
5129 DEFAULT_PRIORITY,
5130 &d,
5131 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445132 req.Start();
[email protected]255620da2013-08-19 13:14:295133 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445134
5135 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5136 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
5137}
5138
5139TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5140 ASSERT_TRUE(test_server_.Start());
5141
5142 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195143 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5144 DEFAULT_PRIORITY,
5145 &d,
5146 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135147 req.SetReferrer("http://user:[email protected]/");
[email protected]316c1e5e2012-09-12 15:17:445148 req.Start();
[email protected]255620da2013-08-19 13:14:295149 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445150
5151 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5152}
5153
[email protected]99ecf6e2013-04-10 22:46:135154TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5155 ASSERT_TRUE(test_server_.Start());
5156
5157 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195158 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5159 DEFAULT_PRIORITY,
5160 &d,
5161 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135162 req.SetReferrer("http://foo.com/test#fragment");
5163 req.Start();
[email protected]255620da2013-08-19 13:14:295164 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135165
5166 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5167}
5168
5169TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5170 ASSERT_TRUE(test_server_.Start());
5171
5172 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195173 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5174 DEFAULT_PRIORITY,
5175 &d,
5176 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135177 req.SetReferrer("http://foo.com/test#fragment");
5178 req.SetReferrer("");
5179 req.Start();
[email protected]255620da2013-08-19 13:14:295180 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135181
5182 EXPECT_EQ(std::string("None"), d.data_received());
5183}
5184
[email protected]316c1e5e2012-09-12 15:17:445185TEST_F(URLRequestTestHTTP, CancelRedirect) {
5186 ASSERT_TRUE(test_server_.Start());
5187
5188 TestDelegate d;
5189 {
5190 d.set_cancel_in_received_redirect(true);
[email protected]2ca01e52013-10-31 22:05:195191 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5192 DEFAULT_PRIORITY,
5193 &d,
5194 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445195 req.Start();
[email protected]255620da2013-08-19 13:14:295196 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445197
5198 EXPECT_EQ(1, d.response_started_count());
5199 EXPECT_EQ(0, d.bytes_received());
5200 EXPECT_FALSE(d.received_data_before_response());
5201 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5202 }
5203}
5204
5205TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5206 ASSERT_TRUE(test_server_.Start());
5207
5208 TestDelegate d;
5209 {
5210 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:045211 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]2ca01e52013-10-31 22:05:195212 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:045213
[email protected]316c1e5e2012-09-12 15:17:445214 req.Start();
[email protected]255620da2013-08-19 13:14:295215 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445216
5217 EXPECT_EQ(1, d.received_redirect_count());
5218
5219 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295220 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445221
5222 EXPECT_EQ(1, d.response_started_count());
5223 EXPECT_FALSE(d.received_data_before_response());
5224 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5225
[email protected]6cdfd7f2013-02-08 20:40:155226 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445227 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5228 path = path.Append(FILE_PATH_LITERAL("net"));
5229 path = path.Append(FILE_PATH_LITERAL("data"));
5230 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5231 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5232
5233 std::string contents;
[email protected]82f84b92013-08-30 18:23:505234 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:445235 EXPECT_EQ(contents, d.data_received());
5236 }
5237}
5238
[email protected]79e1fd62013-06-20 06:50:045239TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5240 ASSERT_TRUE(test_server_.Start());
5241
5242 TestDelegate d;
5243 {
5244 d.set_quit_on_redirect(true);
5245 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]2ca01e52013-10-31 22:05:195246 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:045247
5248 EXPECT_FALSE(d.have_full_request_headers());
5249
5250 req.Start();
[email protected]255620da2013-08-19 13:14:295251 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045252
5253 EXPECT_EQ(1, d.received_redirect_count());
5254 EXPECT_TRUE(d.have_full_request_headers());
5255 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5256 d.ClearFullRequestHeaders();
5257
5258 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295259 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045260
5261 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5262 EXPECT_EQ(1, d.response_started_count());
5263 EXPECT_TRUE(d.have_full_request_headers());
5264 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5265 EXPECT_FALSE(d.received_data_before_response());
5266 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5267
5268 base::FilePath path;
5269 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5270 path = path.Append(FILE_PATH_LITERAL("net"));
5271 path = path.Append(FILE_PATH_LITERAL("data"));
5272 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5273 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5274
5275 std::string contents;
[email protected]82f84b92013-08-30 18:23:505276 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:045277 EXPECT_EQ(contents, d.data_received());
5278 }
5279}
5280
[email protected]316c1e5e2012-09-12 15:17:445281TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5282 ASSERT_TRUE(test_server_.Start());
5283
5284 TestDelegate d;
5285 {
5286 d.set_quit_on_redirect(true);
[email protected]2ca01e52013-10-31 22:05:195287 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5288 DEFAULT_PRIORITY,
5289 &d,
5290 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445291 req.Start();
[email protected]255620da2013-08-19 13:14:295292 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445293
5294 EXPECT_EQ(1, d.received_redirect_count());
5295
5296 req.Cancel();
[email protected]255620da2013-08-19 13:14:295297 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445298
5299 EXPECT_EQ(1, d.response_started_count());
5300 EXPECT_EQ(0, d.bytes_received());
5301 EXPECT_FALSE(d.received_data_before_response());
5302 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5303 }
5304}
5305
5306TEST_F(URLRequestTestHTTP, VaryHeader) {
5307 ASSERT_TRUE(test_server_.Start());
5308
[email protected]3b23a222013-05-15 21:33:255309 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:445310 {
5311 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195312 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5313 DEFAULT_PRIORITY,
5314 &d,
5315 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445316 HttpRequestHeaders headers;
5317 headers.SetHeader("foo", "1");
5318 req.SetExtraRequestHeaders(headers);
5319 req.Start();
[email protected]255620da2013-08-19 13:14:295320 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:255321
5322 LoadTimingInfo load_timing_info;
5323 req.GetLoadTimingInfo(&load_timing_info);
5324 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445325 }
5326
[email protected]3b23a222013-05-15 21:33:255327 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:445328 {
5329 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195330 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5331 DEFAULT_PRIORITY,
5332 &d,
5333 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445334 HttpRequestHeaders headers;
5335 headers.SetHeader("foo", "1");
5336 req.SetExtraRequestHeaders(headers);
5337 req.Start();
[email protected]255620da2013-08-19 13:14:295338 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445339
5340 EXPECT_TRUE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255341
5342 LoadTimingInfo load_timing_info;
5343 req.GetLoadTimingInfo(&load_timing_info);
5344 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:445345 }
5346
[email protected]3b23a222013-05-15 21:33:255347 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:445348 {
5349 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195350 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5351 DEFAULT_PRIORITY,
5352 &d,
5353 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445354 HttpRequestHeaders headers;
5355 headers.SetHeader("foo", "2");
5356 req.SetExtraRequestHeaders(headers);
5357 req.Start();
[email protected]255620da2013-08-19 13:14:295358 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445359
5360 EXPECT_FALSE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255361
5362 LoadTimingInfo load_timing_info;
5363 req.GetLoadTimingInfo(&load_timing_info);
5364 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445365 }
5366}
5367
5368TEST_F(URLRequestTestHTTP, BasicAuth) {
5369 ASSERT_TRUE(test_server_.Start());
5370
5371 // populate the cache
5372 {
5373 TestDelegate d;
5374 d.set_credentials(AuthCredentials(kUser, kSecret));
5375
[email protected]2ca01e52013-10-31 22:05:195376 URLRequest r(test_server_.GetURL("auth-basic"),
5377 DEFAULT_PRIORITY,
5378 &d,
5379 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445380 r.Start();
5381
[email protected]255620da2013-08-19 13:14:295382 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445383
5384 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5385 }
5386
5387 // repeat request with end-to-end validation. since auth-basic results in a
5388 // cachable page, we expect this test to result in a 304. in which case, the
5389 // response should be fetched from the cache.
5390 {
5391 TestDelegate d;
5392 d.set_credentials(AuthCredentials(kUser, kSecret));
5393
[email protected]2ca01e52013-10-31 22:05:195394 URLRequest r(test_server_.GetURL("auth-basic"),
5395 DEFAULT_PRIORITY,
5396 &d,
5397 &default_context_);
[email protected]bb1c4662013-11-14 00:00:075398 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:445399 r.Start();
5400
[email protected]255620da2013-08-19 13:14:295401 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445402
5403 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5404
5405 // Should be the same cached document.
5406 EXPECT_TRUE(r.was_cached());
5407 }
5408}
5409
5410// Check that Set-Cookie headers in 401 responses are respected.
5411// http://crbug.com/6450
5412TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5413 ASSERT_TRUE(test_server_.Start());
5414
5415 GURL url_requiring_auth =
5416 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5417
5418 // Request a page that will give a 401 containing a Set-Cookie header.
5419 // Verify that when the transaction is restarted, it includes the new cookie.
5420 {
[email protected]ceefd7fd2012-11-29 00:36:245421 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445422 TestURLRequestContext context(true);
5423 context.set_network_delegate(&network_delegate);
5424 context.Init();
5425
5426 TestDelegate d;
5427 d.set_credentials(AuthCredentials(kUser, kSecret));
5428
[email protected]2ca01e52013-10-31 22:05:195429 URLRequest r(url_requiring_auth, DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445430 r.Start();
5431
[email protected]255620da2013-08-19 13:14:295432 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445433
5434 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5435
5436 // Make sure we sent the cookie in the restarted transaction.
5437 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5438 != std::string::npos);
5439 }
5440
5441 // Same test as above, except this time the restart is initiated earlier
5442 // (without user intervention since identity is embedded in the URL).
5443 {
[email protected]ceefd7fd2012-11-29 00:36:245444 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445445 TestURLRequestContext context(true);
5446 context.set_network_delegate(&network_delegate);
5447 context.Init();
5448
5449 TestDelegate d;
5450
5451 GURL::Replacements replacements;
5452 std::string username("user2");
5453 std::string password("secret");
5454 replacements.SetUsernameStr(username);
5455 replacements.SetPasswordStr(password);
5456 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5457
[email protected]2ca01e52013-10-31 22:05:195458 URLRequest r(url_with_identity, DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445459 r.Start();
5460
[email protected]255620da2013-08-19 13:14:295461 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445462
5463 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5464
5465 // Make sure we sent the cookie in the restarted transaction.
5466 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5467 != std::string::npos);
5468 }
5469}
5470
[email protected]58e32bb2013-01-21 18:23:255471// Tests that load timing works as expected with auth and the cache.
5472TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5473 ASSERT_TRUE(test_server_.Start());
5474
5475 // populate the cache
5476 {
5477 TestDelegate d;
5478 d.set_credentials(AuthCredentials(kUser, kSecret));
5479
[email protected]2ca01e52013-10-31 22:05:195480 URLRequest r(test_server_.GetURL("auth-basic"),
5481 DEFAULT_PRIORITY,
5482 &d,
5483 &default_context_);
[email protected]58e32bb2013-01-21 18:23:255484 r.Start();
5485
[email protected]255620da2013-08-19 13:14:295486 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255487
5488 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5489
5490 LoadTimingInfo load_timing_info_before_auth;
5491 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5492 &load_timing_info_before_auth));
5493 TestLoadTimingNotReused(load_timing_info_before_auth,
5494 CONNECT_TIMING_HAS_DNS_TIMES);
5495
5496 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175497 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255498 // The test server does not support keep alive sockets, so the second
5499 // request with auth should use a new socket.
5500 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5501 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5502 load_timing_info.socket_log_id);
5503 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5504 load_timing_info.connect_timing.connect_start);
5505 }
5506
[email protected]3b23a222013-05-15 21:33:255507 // Repeat request with end-to-end validation. Since auth-basic results in a
5508 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:255509 // response should be fetched from the cache.
5510 {
5511 TestDelegate d;
5512 d.set_credentials(AuthCredentials(kUser, kSecret));
5513
[email protected]2ca01e52013-10-31 22:05:195514 URLRequest r(test_server_.GetURL("auth-basic"),
5515 DEFAULT_PRIORITY,
5516 &d,
5517 &default_context_);
[email protected]bb1c4662013-11-14 00:00:075518 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]58e32bb2013-01-21 18:23:255519 r.Start();
5520
[email protected]255620da2013-08-19 13:14:295521 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255522
5523 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5524
5525 // Should be the same cached document.
5526 EXPECT_TRUE(r.was_cached());
5527
[email protected]3b23a222013-05-15 21:33:255528 // Since there was a request that went over the wire, the load timing
5529 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:255530 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175531 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255532 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:255533 }
5534}
5535
[email protected]316c1e5e2012-09-12 15:17:445536// In this test, we do a POST which the server will 302 redirect.
5537// The subsequent transaction should use GET, and should not send the
5538// Content-Type header.
5539// http://code.google.com/p/chromium/issues/detail?id=843
5540TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5541 ASSERT_TRUE(test_server_.Start());
5542
5543 const char kData[] = "hello world";
5544
5545 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195546 URLRequest req(test_server_.GetURL("files/redirect-to-echoall"),
5547 DEFAULT_PRIORITY,
5548 &d,
5549 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445550 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285551 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445552
5553 // Set headers (some of which are specific to the POST).
5554 HttpRequestHeaders headers;
5555 headers.AddHeadersFromString(
5556 "Content-Type: multipart/form-data; "
5557 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5558 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5559 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5560 "Accept-Language: en-US,en\r\n"
5561 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5562 "Content-Length: 11\r\n"
5563 "Origin: http://localhost:1337/");
5564 req.SetExtraRequestHeaders(headers);
5565 req.Start();
[email protected]255620da2013-08-19 13:14:295566 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445567
5568 std::string mime_type;
5569 req.GetMimeType(&mime_type);
5570 EXPECT_EQ("text/html", mime_type);
5571
5572 const std::string& data = d.data_received();
5573
5574 // Check that the post-specific headers were stripped:
5575 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
5576 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
5577 EXPECT_FALSE(ContainsString(data, "Origin:"));
5578
5579 // These extra request headers should not have been stripped.
5580 EXPECT_TRUE(ContainsString(data, "Accept:"));
5581 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
5582 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
5583}
5584
5585// The following tests check that we handle mutating the request method for
5586// HTTP redirects as expected.
5587// See http://crbug.com/56373 and http://crbug.com/102130.
5588
5589TEST_F(URLRequestTestHTTP, Redirect301Tests) {
5590 ASSERT_TRUE(test_server_.Start());
5591
5592 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
5593
5594 HTTPRedirectMethodTest(url, "POST", "GET", true);
5595 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5596 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5597}
5598
5599TEST_F(URLRequestTestHTTP, Redirect302Tests) {
5600 ASSERT_TRUE(test_server_.Start());
5601
5602 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
5603
5604 HTTPRedirectMethodTest(url, "POST", "GET", true);
5605 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5606 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5607}
5608
5609TEST_F(URLRequestTestHTTP, Redirect303Tests) {
5610 ASSERT_TRUE(test_server_.Start());
5611
5612 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
5613
5614 HTTPRedirectMethodTest(url, "POST", "GET", true);
5615 HTTPRedirectMethodTest(url, "PUT", "GET", true);
5616 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5617}
5618
5619TEST_F(URLRequestTestHTTP, Redirect307Tests) {
5620 ASSERT_TRUE(test_server_.Start());
5621
5622 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
5623
5624 HTTPRedirectMethodTest(url, "POST", "POST", true);
5625 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5626 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5627}
5628
5629TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
5630 ASSERT_TRUE(test_server_.Start());
5631
5632 const char kData[] = "hello world";
5633
5634 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195635 URLRequest req(test_server_.GetURL("empty.html"),
5636 DEFAULT_PRIORITY,
5637 &d,
5638 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445639 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285640 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445641 HttpRequestHeaders headers;
5642 headers.SetHeader(HttpRequestHeaders::kContentLength,
5643 base::UintToString(arraysize(kData) - 1));
5644 req.SetExtraRequestHeaders(headers);
5645
5646 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:415647 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]8ccc69f2012-11-28 19:52:145648 URLRequestRedirectJob::REDIRECT_302_FOUND);
[email protected]316c1e5e2012-09-12 15:17:445649 AddTestInterceptor()->set_main_intercept_job(job);
5650
5651 req.Start();
[email protected]255620da2013-08-19 13:14:295652 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445653 EXPECT_EQ("GET", req.method());
5654}
5655
5656TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
5657 ASSERT_TRUE(test_server_.Start());
5658
5659 const char kData[] = "hello world";
5660
5661 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195662 URLRequest req(test_server_.GetURL("empty.html"),
5663 DEFAULT_PRIORITY,
5664 &d,
5665 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445666 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285667 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445668 HttpRequestHeaders headers;
5669 headers.SetHeader(HttpRequestHeaders::kContentLength,
5670 base::UintToString(arraysize(kData) - 1));
5671 req.SetExtraRequestHeaders(headers);
5672
5673 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:415674 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]316c1e5e2012-09-12 15:17:445675 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT);
5676 AddTestInterceptor()->set_main_intercept_job(job);
5677
5678 req.Start();
[email protected]255620da2013-08-19 13:14:295679 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445680 EXPECT_EQ("POST", req.method());
5681 EXPECT_EQ(kData, d.data_received());
5682}
5683
5684// Check that default A-L header is sent.
5685TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
5686 ASSERT_TRUE(test_server_.Start());
5687
[email protected]8790210c2013-12-02 05:29:535688 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:245689 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:445690 TestURLRequestContext context(true);
5691 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:435692 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:445693 context.Init();
5694
5695 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195696 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
5697 DEFAULT_PRIORITY,
5698 &d,
5699 &context);
[email protected]316c1e5e2012-09-12 15:17:445700 req.Start();
[email protected]255620da2013-08-19 13:14:295701 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445702 EXPECT_EQ("en", d.data_received());
5703}
5704
5705// Check that an empty A-L header is not sent. http://crbug.com/77365.
5706TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
5707 ASSERT_TRUE(test_server_.Start());
5708
[email protected]8790210c2013-12-02 05:29:535709 std::string empty_string; // Avoid most vexing parse on line below.
5710 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:245711 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:445712 TestURLRequestContext context(true);
5713 context.set_network_delegate(&network_delegate);
5714 context.Init();
5715 // We override the language after initialization because empty entries
5716 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:435717 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:445718
5719 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195720 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
5721 DEFAULT_PRIORITY,
5722 &d,
5723 &context);
[email protected]316c1e5e2012-09-12 15:17:445724 req.Start();
[email protected]255620da2013-08-19 13:14:295725 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445726 EXPECT_EQ("None", d.data_received());
5727}
5728
5729// Check that if request overrides the A-L header, the default is not appended.
5730// See http://crbug.com/20894
5731TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
5732 ASSERT_TRUE(test_server_.Start());
5733
5734 TestDelegate d;
5735 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
[email protected]2ca01e52013-10-31 22:05:195736 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:445737 &d,
5738 &default_context_);
5739 HttpRequestHeaders headers;
5740 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
5741 req.SetExtraRequestHeaders(headers);
5742 req.Start();
[email protected]255620da2013-08-19 13:14:295743 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445744 EXPECT_EQ(std::string("ru"), d.data_received());
5745}
5746
5747// Check that default A-E header is sent.
5748TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
5749 ASSERT_TRUE(test_server_.Start());
5750
5751 TestDelegate d;
5752 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
[email protected]2ca01e52013-10-31 22:05:195753 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:445754 &d,
5755 &default_context_);
5756 HttpRequestHeaders headers;
5757 req.SetExtraRequestHeaders(headers);
5758 req.Start();
[email protected]255620da2013-08-19 13:14:295759 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445760 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
5761}
5762
5763// Check that if request overrides the A-E header, the default is not appended.
5764// See http://crbug.com/47381
5765TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
5766 ASSERT_TRUE(test_server_.Start());
5767
5768 TestDelegate d;
5769 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
[email protected]2ca01e52013-10-31 22:05:195770 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:445771 &d,
5772 &default_context_);
5773 HttpRequestHeaders headers;
5774 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
5775 req.SetExtraRequestHeaders(headers);
5776 req.Start();
[email protected]255620da2013-08-19 13:14:295777 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445778 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
5779 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
5780}
5781
[email protected]84f05432013-03-15 01:00:125782// Check that setting the A-C header sends the proper header.
5783TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:445784 ASSERT_TRUE(test_server_.Start());
5785
5786 TestDelegate d;
5787 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
[email protected]2ca01e52013-10-31 22:05:195788 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:445789 &d,
5790 &default_context_);
5791 HttpRequestHeaders headers;
5792 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
5793 req.SetExtraRequestHeaders(headers);
5794 req.Start();
[email protected]255620da2013-08-19 13:14:295795 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445796 EXPECT_EQ(std::string("koi-8r"), d.data_received());
5797}
5798
5799// Check that default User-Agent header is sent.
5800TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
5801 ASSERT_TRUE(test_server_.Start());
5802
5803 TestDelegate d;
5804 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
[email protected]2ca01e52013-10-31 22:05:195805 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:445806 &d,
5807 &default_context_);
5808 req.Start();
[email protected]255620da2013-08-19 13:14:295809 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445810 EXPECT_EQ(req.context()->GetUserAgent(req.url()), d.data_received());
5811}
5812
5813// Check that if request overrides the User-Agent header,
5814// the default is not appended.
5815TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
5816 ASSERT_TRUE(test_server_.Start());
5817
5818 TestDelegate d;
5819 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
[email protected]2ca01e52013-10-31 22:05:195820 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:445821 &d,
5822 &default_context_);
5823 HttpRequestHeaders headers;
5824 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
5825 req.SetExtraRequestHeaders(headers);
5826 req.Start();
[email protected]255620da2013-08-19 13:14:295827 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445828 // If the net tests are being run with ChromeFrame then we need to allow for
5829 // the 'chromeframe' suffix which is added to the user agent before the
5830 // closing parentheses.
5831 EXPECT_TRUE(StartsWithASCII(d.data_received(), "Lynx (textmode", true));
5832}
5833
[email protected]ee4c30d2012-11-07 15:08:435834// Check that a NULL HttpUserAgentSettings causes the corresponding empty
5835// User-Agent header to be sent but does not send the Accept-Language and
5836// Accept-Charset headers.
5837TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
5838 ASSERT_TRUE(test_server_.Start());
5839
[email protected]ceefd7fd2012-11-29 00:36:245840 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:435841 TestURLRequestContext context(true);
5842 context.set_network_delegate(&network_delegate);
5843 context.Init();
5844 // We override the HttpUserAgentSettings after initialization because empty
5845 // entries get overridden by Init().
5846 context.set_http_user_agent_settings(NULL);
5847
5848 struct {
5849 const char* request;
5850 const char* expected_response;
5851 } tests[] = { { "echoheader?Accept-Language", "None" },
5852 { "echoheader?Accept-Charset", "None" },
5853 { "echoheader?User-Agent", "" } };
5854
5855 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
5856 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195857 URLRequest req(
5858 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, &context);
[email protected]ee4c30d2012-11-07 15:08:435859 req.Start();
[email protected]255620da2013-08-19 13:14:295860 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:435861 EXPECT_EQ(tests[i].expected_response, d.data_received())
5862 << " Request = \"" << tests[i].request << "\"";
5863 }
5864}
5865
[email protected]5033ab82013-03-22 20:17:465866// Make sure that URLRequest passes on its priority updates to
5867// newly-created jobs after the first one.
5868TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
5869 ASSERT_TRUE(test_server_.Start());
5870
5871 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195872 URLRequest req(test_server_.GetURL("empty.html"),
5873 DEFAULT_PRIORITY,
5874 &d,
5875 &default_context_);
[email protected]5033ab82013-03-22 20:17:465876 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
5877
5878 scoped_refptr<URLRequestRedirectJob> redirect_job =
5879 new URLRequestRedirectJob(
5880 &req, &default_network_delegate_, test_server_.GetURL("echo"),
5881 URLRequestRedirectJob::REDIRECT_302_FOUND);
[email protected]90499482013-06-01 00:39:505882 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:465883
5884 req.SetPriority(LOW);
5885 req.Start();
5886 EXPECT_TRUE(req.is_pending());
5887
5888 scoped_refptr<URLRequestTestJob> job =
5889 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:505890 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:465891
5892 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:295893 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:465894 EXPECT_EQ(LOW, job->priority());
5895}
5896
[email protected]73e0bba2009-02-19 22:57:095897class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:505898 public:
[email protected]ef2bf422012-05-11 03:27:095899 HTTPSRequestTest() : default_context_(true) {
5900 default_context_.set_network_delegate(&default_network_delegate_);
5901 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:505902 }
5903 virtual ~HTTPSRequestTest() {}
5904
5905 protected:
[email protected]ceefd7fd2012-11-29 00:36:245906 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095907 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:465908};
5909
[email protected]c044616e2013-02-20 02:01:265910TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225911 SpawnedTestServer test_server(
5912 SpawnedTestServer::TYPE_HTTPS,
5913 SpawnedTestServer::kLocalhost,
5914 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:115915 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:465916
[email protected]ea224582008-12-07 20:25:465917 TestDelegate d;
5918 {
[email protected]2ca01e52013-10-31 22:05:195919 URLRequest r(test_server.GetURL(std::string()),
5920 DEFAULT_PRIORITY,
5921 &d,
5922 &default_context_);
[email protected]ea224582008-12-07 20:25:465923 r.Start();
5924 EXPECT_TRUE(r.is_pending());
5925
[email protected]255620da2013-08-19 13:14:295926 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:465927
5928 EXPECT_EQ(1, d.response_started_count());
5929 EXPECT_FALSE(d.received_data_before_response());
5930 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175931 CheckSSLInfo(r.ssl_info());
[email protected]6d81b482011-02-22 19:47:195932 EXPECT_EQ(test_server.host_port_pair().host(),
5933 r.GetSocketAddress().host());
5934 EXPECT_EQ(test_server.host_port_pair().port(),
5935 r.GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:465936 }
[email protected]ea224582008-12-07 20:25:465937}
5938
[email protected]5774ada2010-07-15 06:30:545939TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225940 SpawnedTestServer::SSLOptions ssl_options(
5941 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
5942 SpawnedTestServer test_server(
5943 SpawnedTestServer::TYPE_HTTPS,
5944 ssl_options,
5945 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:115946 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:335947
5948 bool err_allowed = true;
5949 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
5950 TestDelegate d;
5951 {
5952 d.set_allow_certificate_errors(err_allowed);
[email protected]2ca01e52013-10-31 22:05:195953 URLRequest r(test_server.GetURL(std::string()),
5954 DEFAULT_PRIORITY,
5955 &d,
5956 &default_context_);
[email protected]bacff652009-03-31 17:50:335957
5958 r.Start();
5959 EXPECT_TRUE(r.is_pending());
5960
[email protected]255620da2013-08-19 13:14:295961 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:335962
5963 EXPECT_EQ(1, d.response_started_count());
5964 EXPECT_FALSE(d.received_data_before_response());
5965 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:175966 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:335967 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175968 CheckSSLInfo(r.ssl_info());
5969 } else {
[email protected]bacff652009-03-31 17:50:335970 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175971 }
[email protected]bacff652009-03-31 17:50:335972 }
5973 }
5974}
5975
[email protected]5774ada2010-07-15 06:30:545976TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225977 SpawnedTestServer::SSLOptions ssl_options(
5978 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
5979 SpawnedTestServer test_server(
5980 SpawnedTestServer::TYPE_HTTPS,
5981 ssl_options,
5982 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:115983 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:335984
5985 // Iterate from false to true, just so that we do the opposite of the
5986 // previous test in order to increase test coverage.
5987 bool err_allowed = false;
5988 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
5989 TestDelegate d;
5990 {
5991 d.set_allow_certificate_errors(err_allowed);
[email protected]2ca01e52013-10-31 22:05:195992 URLRequest r(test_server.GetURL(std::string()),
5993 DEFAULT_PRIORITY,
5994 &d,
5995 &default_context_);
[email protected]bacff652009-03-31 17:50:335996
5997 r.Start();
5998 EXPECT_TRUE(r.is_pending());
5999
[email protected]255620da2013-08-19 13:14:296000 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:336001
6002 EXPECT_EQ(1, d.response_started_count());
6003 EXPECT_FALSE(d.received_data_before_response());
6004 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:176005 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:336006 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176007 CheckSSLInfo(r.ssl_info());
6008 } else {
[email protected]bacff652009-03-31 17:50:336009 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176010 }
[email protected]bacff652009-03-31 17:50:336011 }
6012 }
6013}
[email protected]73e0bba2009-02-19 22:57:096014
[email protected]316c1e5e2012-09-12 15:17:446015// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
6016// than necessary.
6017TEST_F(HTTPSRequestTest, TLSv1Fallback) {
6018 uint16 default_version_max = SSLConfigService::default_version_max();
6019 // The OpenSSL library in use may not support TLS 1.1.
6020#if !defined(USE_OPENSSL)
6021 EXPECT_GT(default_version_max, SSL_PROTOCOL_VERSION_TLS1);
6022#endif
6023 if (default_version_max <= SSL_PROTOCOL_VERSION_TLS1)
6024 return;
6025
[email protected]ce7d0cbc2013-05-03 18:57:226026 SpawnedTestServer::SSLOptions ssl_options(
6027 SpawnedTestServer::SSLOptions::CERT_OK);
[email protected]316c1e5e2012-09-12 15:17:446028 ssl_options.tls_intolerant =
[email protected]ce7d0cbc2013-05-03 18:57:226029 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
6030 SpawnedTestServer test_server(
6031 SpawnedTestServer::TYPE_HTTPS,
6032 ssl_options,
6033 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446034 ASSERT_TRUE(test_server.Start());
6035
6036 TestDelegate d;
6037 TestURLRequestContext context(true);
6038 context.Init();
6039 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:196040 URLRequest r(
6041 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:446042 r.Start();
6043
[email protected]255620da2013-08-19 13:14:296044 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446045
6046 EXPECT_EQ(1, d.response_started_count());
6047 EXPECT_NE(0, d.bytes_received());
6048 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
6049 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6050 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6051}
6052
6053// This tests that a load of www.google.com with a certificate error sets
6054// the |certificate_errors_are_fatal| flag correctly. This flag will cause
6055// the interstitial to be fatal.
6056TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226057 SpawnedTestServer::SSLOptions ssl_options(
6058 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6059 SpawnedTestServer test_server(
6060 SpawnedTestServer::TYPE_HTTPS,
6061 ssl_options,
6062 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446063 ASSERT_TRUE(test_server.Start());
6064
6065 // We require that the URL be www.google.com in order to pick up the
6066 // preloaded HSTS entries in the TransportSecurityState. This means that we
6067 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:246068 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:446069
6070 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:246071 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446072 TestURLRequestContext context(true);
6073 context.set_network_delegate(&network_delegate);
6074 context.set_host_resolver(&host_resolver);
6075 TransportSecurityState transport_security_state;
6076 context.set_transport_security_state(&transport_security_state);
6077 context.Init();
6078
6079 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:046080 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6081 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196082 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446083 &d,
6084 &context);
6085
6086 r.Start();
6087 EXPECT_TRUE(r.is_pending());
6088
[email protected]255620da2013-08-19 13:14:296089 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446090
6091 EXPECT_EQ(1, d.response_started_count());
6092 EXPECT_FALSE(d.received_data_before_response());
6093 EXPECT_TRUE(d.have_certificate_errors());
6094 EXPECT_TRUE(d.certificate_errors_are_fatal());
6095}
6096
6097// This tests that cached HTTPS page loads do not cause any updates to the
6098// TransportSecurityState.
6099TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6100 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6101 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:226102 SpawnedTestServer::SSLOptions ssl_options(
6103 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6104 SpawnedTestServer test_server(
6105 SpawnedTestServer::TYPE_HTTPS,
6106 ssl_options,
6107 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446108 ASSERT_TRUE(test_server.Start());
6109
6110 // We require that the URL be www.google.com in order to pick up the
6111 // preloaded and dynamic HSTS and public key pin entries in the
6112 // TransportSecurityState. This means that we have to use a
6113 // MockHostResolver in order to direct www.google.com to the testserver.
[email protected]ceefd7fd2012-11-29 00:36:246114 // By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:446115
6116 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:246117 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446118 TestURLRequestContext context(true);
6119 context.set_network_delegate(&network_delegate);
6120 context.set_host_resolver(&host_resolver);
6121 TransportSecurityState transport_security_state;
6122 TransportSecurityState::DomainState domain_state;
[email protected]22e045f2013-09-20 03:54:036123 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
6124 &domain_state));
[email protected]316c1e5e2012-09-12 15:17:446125 context.set_transport_security_state(&transport_security_state);
6126 context.Init();
6127
6128 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:046129 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6130 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196131 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446132 &d,
6133 &context);
6134
6135 r.Start();
6136 EXPECT_TRUE(r.is_pending());
6137
[email protected]255620da2013-08-19 13:14:296138 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446139
6140 EXPECT_EQ(1, d.response_started_count());
6141 EXPECT_FALSE(d.received_data_before_response());
6142 EXPECT_TRUE(d.have_certificate_errors());
6143 EXPECT_TRUE(d.certificate_errors_are_fatal());
6144
6145 // Get a fresh copy of the state, and check that it hasn't been updated.
6146 TransportSecurityState::DomainState new_domain_state;
[email protected]22e045f2013-09-20 03:54:036147 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
6148 &new_domain_state));
[email protected]316c1e5e2012-09-12 15:17:446149 EXPECT_EQ(new_domain_state.upgrade_mode, domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:056150 EXPECT_EQ(new_domain_state.sts_include_subdomains,
6151 domain_state.sts_include_subdomains);
6152 EXPECT_EQ(new_domain_state.pkp_include_subdomains,
6153 domain_state.pkp_include_subdomains);
[email protected]316c1e5e2012-09-12 15:17:446154 EXPECT_TRUE(FingerprintsEqual(new_domain_state.static_spki_hashes,
6155 domain_state.static_spki_hashes));
6156 EXPECT_TRUE(FingerprintsEqual(new_domain_state.dynamic_spki_hashes,
6157 domain_state.dynamic_spki_hashes));
6158 EXPECT_TRUE(FingerprintsEqual(new_domain_state.bad_static_spki_hashes,
6159 domain_state.bad_static_spki_hashes));
6160}
6161
[email protected]8ccc69f2012-11-28 19:52:146162// Make sure HSTS preserves a POST request's method and body.
6163TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6164 static const char kData[] = "hello world";
6165
[email protected]ce7d0cbc2013-05-03 18:57:226166 SpawnedTestServer::SSLOptions ssl_options(
6167 SpawnedTestServer::SSLOptions::CERT_OK);
6168 SpawnedTestServer test_server(
6169 SpawnedTestServer::TYPE_HTTPS,
6170 ssl_options,
6171 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:146172 ASSERT_TRUE(test_server.Start());
6173
6174
6175 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6176 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:226177 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6178 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:146179 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:146180
6181 // Force https for www.somewhere.com.
6182 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:206183 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6184 bool include_subdomains = false;
6185 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6186 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:146187
6188 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6189
6190 TestURLRequestContext context(true);
6191 context.set_host_resolver(&host_resolver);
6192 context.set_transport_security_state(&transport_security_state);
6193 context.set_network_delegate(&network_delegate);
6194 context.Init();
6195
6196 TestDelegate d;
6197 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6198 // cause a certificate error. Ignore the error.
6199 d.set_allow_certificate_errors(true);
6200
[email protected]7d3cbc92013-03-18 22:33:046201 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6202 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196203 DEFAULT_PRIORITY,
[email protected]8ccc69f2012-11-28 19:52:146204 &d,
6205 &context);
6206 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:286207 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]8ccc69f2012-11-28 19:52:146208
6209 req.Start();
[email protected]255620da2013-08-19 13:14:296210 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:146211
6212 EXPECT_EQ("https", req.url().scheme());
6213 EXPECT_EQ("POST", req.method());
6214 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:406215
6216 LoadTimingInfo load_timing_info;
6217 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6218 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6219 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:146220}
6221
[email protected]316c1e5e2012-09-12 15:17:446222TEST_F(HTTPSRequestTest, SSLv3Fallback) {
[email protected]ce7d0cbc2013-05-03 18:57:226223 SpawnedTestServer::SSLOptions ssl_options(
6224 SpawnedTestServer::SSLOptions::CERT_OK);
6225 ssl_options.tls_intolerant =
6226 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6227 SpawnedTestServer test_server(
6228 SpawnedTestServer::TYPE_HTTPS,
6229 ssl_options,
6230 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446231 ASSERT_TRUE(test_server.Start());
6232
6233 TestDelegate d;
6234 TestURLRequestContext context(true);
6235 context.Init();
6236 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:196237 URLRequest r(
6238 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:446239 r.Start();
6240
[email protected]255620da2013-08-19 13:14:296241 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446242
6243 EXPECT_EQ(1, d.response_started_count());
6244 EXPECT_NE(0, d.bytes_received());
6245 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
6246 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6247 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6248}
6249
6250namespace {
6251
6252class SSLClientAuthTestDelegate : public TestDelegate {
6253 public:
6254 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6255 }
6256 virtual void OnCertificateRequested(
6257 URLRequest* request,
[email protected]46fadfd2013-02-06 09:40:166258 SSLCertRequestInfo* cert_request_info) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:446259 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:346260 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:446261 }
6262 int on_certificate_requested_count() {
6263 return on_certificate_requested_count_;
6264 }
6265 private:
6266 int on_certificate_requested_count_;
6267};
6268
6269} // namespace
6270
6271// TODO(davidben): Test the rest of the code. Specifically,
6272// - Filtering which certificates to select.
6273// - Sending a certificate back.
6274// - Getting a certificate request in an SSL renegotiation sending the
6275// HTTP request.
6276TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226277 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446278 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:226279 SpawnedTestServer test_server(
6280 SpawnedTestServer::TYPE_HTTPS,
6281 ssl_options,
6282 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446283 ASSERT_TRUE(test_server.Start());
6284
6285 SSLClientAuthTestDelegate d;
6286 {
[email protected]2ca01e52013-10-31 22:05:196287 URLRequest r(test_server.GetURL(std::string()),
6288 DEFAULT_PRIORITY,
6289 &d,
6290 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446291
6292 r.Start();
6293 EXPECT_TRUE(r.is_pending());
6294
[email protected]255620da2013-08-19 13:14:296295 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446296
6297 EXPECT_EQ(1, d.on_certificate_requested_count());
6298 EXPECT_FALSE(d.received_data_before_response());
6299 EXPECT_EQ(0, d.bytes_received());
6300
6301 // Send no certificate.
6302 // TODO(davidben): Get temporary client cert import (with keys) working on
6303 // all platforms so we can test sending a cert as well.
6304 r.ContinueWithCertificate(NULL);
6305
[email protected]255620da2013-08-19 13:14:296306 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446307
6308 EXPECT_EQ(1, d.response_started_count());
6309 EXPECT_FALSE(d.received_data_before_response());
6310 EXPECT_NE(0, d.bytes_received());
6311 }
6312}
6313
6314TEST_F(HTTPSRequestTest, ResumeTest) {
6315 // Test that we attempt a session resume when making two connections to the
6316 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:226317 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446318 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:226319 SpawnedTestServer test_server(
6320 SpawnedTestServer::TYPE_HTTPS,
6321 ssl_options,
6322 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446323 ASSERT_TRUE(test_server.Start());
6324
6325 SSLClientSocket::ClearSessionCache();
6326
6327 {
6328 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196329 URLRequest r(test_server.GetURL("ssl-session-cache"),
6330 DEFAULT_PRIORITY,
6331 &d,
6332 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446333
6334 r.Start();
6335 EXPECT_TRUE(r.is_pending());
6336
[email protected]255620da2013-08-19 13:14:296337 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446338
6339 EXPECT_EQ(1, d.response_started_count());
6340 }
6341
6342 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6343 CloseAllConnections();
6344
6345 {
6346 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196347 URLRequest r(test_server.GetURL("ssl-session-cache"),
6348 DEFAULT_PRIORITY,
6349 &d,
6350 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446351
6352 r.Start();
6353 EXPECT_TRUE(r.is_pending());
6354
[email protected]255620da2013-08-19 13:14:296355 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446356
6357 // The response will look like;
6358 // insert abc
6359 // lookup abc
6360 // insert xyz
6361 //
6362 // With a newline at the end which makes the split think that there are
6363 // four lines.
6364
6365 EXPECT_EQ(1, d.response_started_count());
6366 std::vector<std::string> lines;
6367 base::SplitString(d.data_received(), '\n', &lines);
6368 ASSERT_EQ(4u, lines.size()) << d.data_received();
6369
6370 std::string session_id;
6371
6372 for (size_t i = 0; i < 2; i++) {
6373 std::vector<std::string> parts;
6374 base::SplitString(lines[i], '\t', &parts);
6375 ASSERT_EQ(2u, parts.size());
6376 if (i == 0) {
6377 EXPECT_EQ("insert", parts[0]);
6378 session_id = parts[1];
6379 } else {
6380 EXPECT_EQ("lookup", parts[0]);
6381 EXPECT_EQ(session_id, parts[1]);
6382 }
6383 }
6384 }
6385}
6386
6387TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6388 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6389 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:226390 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446391 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:226392 SpawnedTestServer test_server(
6393 SpawnedTestServer::TYPE_HTTPS,
6394 ssl_options,
6395 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446396 ASSERT_TRUE(test_server.Start());
6397
6398 SSLClientSocket::ClearSessionCache();
6399
6400 {
6401 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196402 URLRequest r(test_server.GetURL("ssl-session-cache"),
6403 DEFAULT_PRIORITY,
6404 &d,
6405 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446406
6407 r.Start();
6408 EXPECT_TRUE(r.is_pending());
6409
[email protected]255620da2013-08-19 13:14:296410 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446411
6412 EXPECT_EQ(1, d.response_started_count());
6413 }
6414
6415 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6416 HttpNetworkSession::Params params;
6417 params.host_resolver = default_context_.host_resolver();
6418 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:116419 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:446420 params.proxy_service = default_context_.proxy_service();
6421 params.ssl_config_service = default_context_.ssl_config_service();
6422 params.http_auth_handler_factory =
6423 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:416424 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:446425 params.http_server_properties = default_context_.http_server_properties();
6426 params.ssl_session_cache_shard = "alternate";
6427
6428 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
6429 new net::HttpNetworkSession(params),
6430 net::HttpCache::DefaultBackend::InMemory(0)));
6431
6432 default_context_.set_http_transaction_factory(cache.get());
6433
6434 {
6435 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196436 URLRequest r(test_server.GetURL("ssl-session-cache"),
6437 DEFAULT_PRIORITY,
6438 &d,
6439 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446440
6441 r.Start();
6442 EXPECT_TRUE(r.is_pending());
6443
[email protected]255620da2013-08-19 13:14:296444 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446445
6446 // The response will look like;
6447 // insert abc
6448 // insert xyz
6449 //
6450 // With a newline at the end which makes the split think that there are
6451 // three lines.
6452
6453 EXPECT_EQ(1, d.response_started_count());
6454 std::vector<std::string> lines;
6455 base::SplitString(d.data_received(), '\n', &lines);
6456 ASSERT_EQ(3u, lines.size());
6457
6458 std::string session_id;
6459 for (size_t i = 0; i < 2; i++) {
6460 std::vector<std::string> parts;
6461 base::SplitString(lines[i], '\t', &parts);
6462 ASSERT_EQ(2u, parts.size());
6463 EXPECT_EQ("insert", parts[0]);
6464 if (i == 0) {
6465 session_id = parts[1];
6466 } else {
6467 EXPECT_NE(session_id, parts[1]);
6468 }
6469 }
6470 }
6471}
6472
[email protected]a13234c2012-03-20 21:45:026473class TestSSLConfigService : public SSLConfigService {
[email protected]dffe8242012-03-20 15:14:276474 public:
[email protected]3a86a712013-07-30 07:16:206475 TestSSLConfigService(bool ev_enabled,
6476 bool online_rev_checking,
6477 bool rev_checking_required_local_anchors)
[email protected]a13234c2012-03-20 21:45:026478 : ev_enabled_(ev_enabled),
[email protected]3a86a712013-07-30 07:16:206479 online_rev_checking_(online_rev_checking),
6480 rev_checking_required_local_anchors_(
6481 rev_checking_required_local_anchors) {}
[email protected]a13234c2012-03-20 21:45:026482
[email protected]a9813302012-04-28 09:29:286483 // SSLConfigService:
6484 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
[email protected]dffe8242012-03-20 15:14:276485 *config = SSLConfig();
[email protected]a13234c2012-03-20 21:45:026486 config->rev_checking_enabled = online_rev_checking_;
6487 config->verify_ev_cert = ev_enabled_;
[email protected]3a86a712013-07-30 07:16:206488 config->rev_checking_required_local_anchors =
6489 rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:276490 }
[email protected]a13234c2012-03-20 21:45:026491
[email protected]a9813302012-04-28 09:29:286492 protected:
6493 virtual ~TestSSLConfigService() {}
6494
[email protected]a13234c2012-03-20 21:45:026495 private:
6496 const bool ev_enabled_;
6497 const bool online_rev_checking_;
[email protected]3a86a712013-07-30 07:16:206498 const bool rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:276499};
6500
6501// This the fingerprint of the "Testing CA" certificate used by the testserver.
6502// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:266503static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:276504 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
6505 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
6506
[email protected]51523f52013-07-31 21:57:286507// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
6508// testserver.
6509static const SHA256HashValue kOCSPTestCertSPKI = { {
6510 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
6511 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
6512 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
6513 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
6514} };
6515
[email protected]dffe8242012-03-20 15:14:276516// This is the policy OID contained in the certificates that testserver
6517// generates.
6518static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
6519
6520class HTTPSOCSPTest : public HTTPSRequestTest {
6521 public:
6522 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:096523 : context_(true),
[email protected]b6f2de32012-08-17 04:35:086524 ev_test_policy_(
6525 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
6526 kOCSPTestCertFingerprint,
6527 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:026528 }
6529
6530 virtual void SetUp() OVERRIDE {
[email protected]ef2bf422012-05-11 03:27:096531 SetupContext(&context_);
6532 context_.Init();
[email protected]dffe8242012-03-20 15:14:276533
6534 scoped_refptr<net::X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:206535 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
[email protected]dffe8242012-03-20 15:14:276536 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
[email protected]90499482013-06-01 00:39:506537 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:276538
[email protected]a592c0432012-12-01 18:10:296539#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:096540 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:276541 EnsureNSSHttpIOInit();
6542#endif
6543 }
6544
[email protected]ce7d0cbc2013-05-03 18:57:226545 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:276546 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:536547 // We always overwrite out_cert_status.
6548 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:226549 SpawnedTestServer test_server(
6550 SpawnedTestServer::TYPE_HTTPS,
6551 ssl_options,
6552 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:276553 ASSERT_TRUE(test_server.Start());
6554
6555 TestDelegate d;
6556 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:196557 URLRequest r(
6558 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context_);
[email protected]dffe8242012-03-20 15:14:276559 r.Start();
6560
[email protected]255620da2013-08-19 13:14:296561 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:276562
6563 EXPECT_EQ(1, d.response_started_count());
6564 *out_cert_status = r.ssl_info().cert_status;
6565 }
6566
[email protected]46fadfd2013-02-06 09:40:166567 virtual ~HTTPSOCSPTest() {
[email protected]a592c0432012-12-01 18:10:296568#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:276569 ShutdownNSSHttpIO();
6570#endif
6571 }
6572
[email protected]a13234c2012-03-20 21:45:026573 protected:
6574 // SetupContext configures the URLRequestContext that will be used for making
6575 // connetions to testserver. This can be overridden in test subclasses for
6576 // different behaviour.
6577 virtual void SetupContext(URLRequestContext* context) {
6578 context->set_ssl_config_service(
6579 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:206580 true /* online revocation checking */,
6581 false /* require rev. checking for local
6582 anchors */));
[email protected]a13234c2012-03-20 21:45:026583 }
6584
[email protected]dffe8242012-03-20 15:14:276585 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:096586 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:086587 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:276588};
6589
[email protected]a13234c2012-03-20 21:45:026590static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:016591#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:026592 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
6593 // have that ability on other platforms.
6594 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
6595#else
6596 return 0;
6597#endif
6598}
6599
[email protected]3a86a712013-07-30 07:16:206600// SystemSupportsHardFailRevocationChecking returns true iff the current
6601// operating system supports revocation checking and can distinguish between
6602// situations where a given certificate lacks any revocation information (eg:
6603// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
6604// revocation information cannot be obtained (eg: the CRL was unreachable).
6605// If it does not, then tests which rely on 'hard fail' behaviour should be
6606// skipped.
6607static bool SystemSupportsHardFailRevocationChecking() {
6608#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
6609 return true;
6610#else
6611 return false;
6612#endif
6613}
6614
[email protected]a13234c2012-03-20 21:45:026615// SystemUsesChromiumEVMetadata returns true iff the current operating system
6616// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
6617// several tests are effected because our testing EV certificate won't be
6618// recognised as EV.
6619static bool SystemUsesChromiumEVMetadata() {
[email protected]5c504192012-03-27 19:00:576620#if defined(USE_OPENSSL)
6621 // http://crbug.com/117478 - OpenSSL does not support EV validation.
6622 return false;
[email protected]a592c0432012-12-01 18:10:296623#elif defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]a13234c2012-03-20 21:45:026624 // On OS X, we use the system to tell us whether a certificate is EV or not
6625 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:016626 return false;
6627#else
6628 return true;
6629#endif
6630}
6631
[email protected]b6f2de32012-08-17 04:35:086632static bool SystemSupportsOCSP() {
[email protected]5c504192012-03-27 19:00:576633#if defined(USE_OPENSSL)
6634 // http://crbug.com/117478 - OpenSSL does not support OCSP.
6635 return false;
6636#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:026637 return base::win::GetVersion() >= base::win::VERSION_VISTA;
6638#elif defined(OS_ANDROID)
6639 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
6640 return false;
6641#else
6642 return true;
6643#endif
6644}
6645
[email protected]dffe8242012-03-20 15:14:276646TEST_F(HTTPSOCSPTest, Valid) {
6647 if (!SystemSupportsOCSP()) {
6648 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6649 return;
6650 }
6651
[email protected]ce7d0cbc2013-05-03 18:57:226652 SpawnedTestServer::SSLOptions ssl_options(
6653 SpawnedTestServer::SSLOptions::CERT_AUTO);
6654 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:276655
[email protected]924e9f92012-12-16 22:00:536656 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126657 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:276658
6659 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6660
[email protected]a13234c2012-03-20 21:45:026661 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6662 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:276663
6664 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6665}
6666
6667TEST_F(HTTPSOCSPTest, Revoked) {
6668 if (!SystemSupportsOCSP()) {
6669 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6670 return;
6671 }
6672
[email protected]ce7d0cbc2013-05-03 18:57:226673 SpawnedTestServer::SSLOptions ssl_options(
6674 SpawnedTestServer::SSLOptions::CERT_AUTO);
6675 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:276676
6677 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126678 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:276679
[email protected]a592c0432012-12-01 18:10:296680#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:276681 // Doesn't pass on OS X yet for reasons that need to be investigated.
6682 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
6683#endif
6684 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6685 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6686}
6687
6688TEST_F(HTTPSOCSPTest, Invalid) {
6689 if (!SystemSupportsOCSP()) {
6690 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6691 return;
6692 }
6693
[email protected]ce7d0cbc2013-05-03 18:57:226694 SpawnedTestServer::SSLOptions ssl_options(
6695 SpawnedTestServer::SSLOptions::CERT_AUTO);
6696 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:276697
[email protected]924e9f92012-12-16 22:00:536698 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126699 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:276700
[email protected]a13234c2012-03-20 21:45:026701 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:276702 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:276703
6704 // Without a positive OCSP response, we shouldn't show the EV status.
6705 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6706 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6707}
[email protected]a13234c2012-03-20 21:45:026708
[email protected]3a86a712013-07-30 07:16:206709class HTTPSHardFailTest : public HTTPSOCSPTest {
6710 protected:
6711 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
6712 context->set_ssl_config_service(
6713 new TestSSLConfigService(false /* check for EV */,
6714 false /* online revocation checking */,
6715 true /* require rev. checking for local
6716 anchors */));
6717 }
6718};
6719
6720
6721TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
6722 if (!SystemSupportsOCSP()) {
6723 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6724 return;
6725 }
6726
6727 if (!SystemSupportsHardFailRevocationChecking()) {
6728 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
6729 << "revocation checking";
6730 return;
6731 }
6732
6733 SpawnedTestServer::SSLOptions ssl_options(
6734 SpawnedTestServer::SSLOptions::CERT_AUTO);
6735 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
6736
6737 CertStatus cert_status;
6738 DoConnection(ssl_options, &cert_status);
6739
6740 EXPECT_EQ(CERT_STATUS_REVOKED,
6741 cert_status & CERT_STATUS_REVOKED);
6742
6743 // Without a positive OCSP response, we shouldn't show the EV status.
6744 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6745}
6746
[email protected]a13234c2012-03-20 21:45:026747class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
6748 protected:
6749 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
6750 context->set_ssl_config_service(
6751 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:206752 false /* online revocation checking */,
6753 false /* require rev. checking for local
6754 anchors */));
[email protected]a13234c2012-03-20 21:45:026755 }
6756};
6757
6758TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
6759 if (!SystemSupportsOCSP()) {
6760 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6761 return;
6762 }
6763
[email protected]ce7d0cbc2013-05-03 18:57:226764 SpawnedTestServer::SSLOptions ssl_options(
6765 SpawnedTestServer::SSLOptions::CERT_AUTO);
6766 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026767 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
6768
[email protected]924e9f92012-12-16 22:00:536769 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126770 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026771
6772 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
6773 cert_status & CERT_STATUS_ALL_ERRORS);
6774
6775 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:086776 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6777 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026778}
6779
[email protected]be0fff62013-08-29 23:37:486780TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
6781 if (!SystemSupportsOCSP()) {
6782 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6783 return;
6784 }
6785
6786 SpawnedTestServer::SSLOptions ssl_options(
6787 SpawnedTestServer::SSLOptions::CERT_AUTO);
6788 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
6789 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
6790
6791 CertStatus cert_status;
6792 DoConnection(ssl_options, &cert_status);
6793
6794 // Currently only works for Windows. When using NSS or OS X, it's not
6795 // possible to determine whether the check failed because of actual
6796 // revocation or because there was an OCSP failure.
6797#if defined(OS_WIN)
6798 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
6799#else
6800 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6801#endif
6802
6803 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6804 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6805 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
6806}
6807
[email protected]a13234c2012-03-20 21:45:026808TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
6809 if (!SystemSupportsOCSP()) {
6810 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6811 return;
6812 }
6813
[email protected]ce7d0cbc2013-05-03 18:57:226814 SpawnedTestServer::SSLOptions ssl_options(
6815 SpawnedTestServer::SSLOptions::CERT_AUTO);
6816 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:026817 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
6818
6819 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126820 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026821
6822 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6823
6824 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6825 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:086826 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6827 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026828}
6829
6830TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
6831 if (!SystemSupportsOCSP()) {
6832 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6833 return;
6834 }
6835
[email protected]ce7d0cbc2013-05-03 18:57:226836 SpawnedTestServer::SSLOptions ssl_options(
6837 SpawnedTestServer::SSLOptions::CERT_AUTO);
6838 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026839 SSLConfigService::SetCRLSet(
6840 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
6841
6842 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126843 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026844
6845 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
6846 cert_status & CERT_STATUS_ALL_ERRORS);
6847
6848 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:086849 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6850 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026851}
6852
[email protected]51523f52013-07-31 21:57:286853TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
6854 if (!SystemSupportsOCSP()) {
6855 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6856 return;
6857 }
6858
6859 SpawnedTestServer::SSLOptions ssl_options(
6860 SpawnedTestServer::SSLOptions::CERT_AUTO);
6861 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
6862 SSLConfigService::SetCRLSet(
6863 scoped_refptr<CRLSet>(CRLSet::ForTesting(
6864 false, &kOCSPTestCertSPKI, "")));
6865
6866 CertStatus cert_status;
6867 DoConnection(ssl_options, &cert_status);
6868
6869 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
6870 // revocation check for EV.
6871 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6872 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6873 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
6874 EXPECT_FALSE(
6875 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
6876}
6877
6878TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
6879 if (!SystemSupportsOCSP()) {
6880 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6881 return;
6882 }
6883
[email protected]ce7d0cbc2013-05-03 18:57:226884 SpawnedTestServer::SSLOptions ssl_options(
6885 SpawnedTestServer::SSLOptions::CERT_AUTO);
6886 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026887 SSLConfigService::SetCRLSet(
6888 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
6889
[email protected]51523f52013-07-31 21:57:286890 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:126891 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026892
[email protected]51523f52013-07-31 21:57:286893 // Even with a fresh CRLSet, we should still do online revocation checks when
6894 // the certificate chain isn't covered by the CRLSet, which it isn't in this
6895 // test.
6896 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
6897 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:026898
[email protected]51523f52013-07-31 21:57:286899 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:026900 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:286901 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026902}
6903
[email protected]b6f2de32012-08-17 04:35:086904TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
6905 // Test that when EV verification is requested, but online revocation
6906 // checking is disabled, and the leaf certificate is not in fact EV, that
6907 // no revocation checking actually happens.
6908 if (!SystemSupportsOCSP()) {
6909 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6910 return;
6911 }
6912
6913 // Unmark the certificate's OID as EV, which should disable revocation
6914 // checking (as per the user preference)
6915 ev_test_policy_.reset();
6916
[email protected]ce7d0cbc2013-05-03 18:57:226917 SpawnedTestServer::SSLOptions ssl_options(
6918 SpawnedTestServer::SSLOptions::CERT_AUTO);
6919 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:086920 SSLConfigService::SetCRLSet(
6921 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
6922
6923 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126924 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:086925
6926 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6927
6928 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6929 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6930}
6931
[email protected]a13234c2012-03-20 21:45:026932class HTTPSCRLSetTest : public HTTPSOCSPTest {
6933 protected:
6934 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
6935 context->set_ssl_config_service(
6936 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:206937 false /* online revocation checking */,
6938 false /* require rev. checking for local
6939 anchors */));
[email protected]a13234c2012-03-20 21:45:026940 }
6941};
6942
6943TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:226944 SpawnedTestServer::SSLOptions ssl_options(
6945 SpawnedTestServer::SSLOptions::CERT_AUTO);
6946 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026947 SSLConfigService::SetCRLSet(
6948 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
6949
[email protected]924e9f92012-12-16 22:00:536950 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126951 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026952
6953 // If we're not trying EV verification then, even if the CRLSet has expired,
6954 // we don't fall back to online revocation checks.
6955 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6956 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6957 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6958}
[email protected]51523f52013-07-31 21:57:286959
6960TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
6961#if defined(USE_OPENSSL)
6962 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
6963 return;
6964#endif
6965
6966 SpawnedTestServer::SSLOptions ssl_options(
6967 SpawnedTestServer::SSLOptions::CERT_AUTO);
6968 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
6969 ssl_options.cert_serial = 10;
6970 SSLConfigService::SetCRLSet(
6971 scoped_refptr<CRLSet>(CRLSet::ForTesting(
6972 false, &kOCSPTestCertSPKI, "\x0a")));
6973
6974 CertStatus cert_status = 0;
6975 DoConnection(ssl_options, &cert_status);
6976
6977 // If the certificate is recorded as revoked in the CRLSet, that should be
6978 // reflected without online revocation checking.
6979 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
6980 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6981 EXPECT_FALSE(
6982 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
6983}
[email protected]316c1e5e2012-09-12 15:17:446984#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:276985
[email protected]316c1e5e2012-09-12 15:17:446986#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:316987class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:116988 public:
[email protected]d9fca99a2012-02-24 16:16:206989 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:226990 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:156991 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:116992 }
6993
[email protected]b89ca032009-08-31 21:41:316994 protected:
[email protected]ce7d0cbc2013-05-03 18:57:226995 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:316996};
6997
[email protected]d2a133182012-08-05 16:44:086998// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:096999TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:087000 ASSERT_TRUE(test_server_.Start());
7001
[email protected]9d5730b2012-08-24 17:42:497002 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:347003 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:087004
7005 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:087006 job_factory.SetProtocolHandler(
7007 "ftp",
[email protected]e0f35c92013-05-08 16:04:347008 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:087009 default_context_.set_job_factory(&job_factory);
7010
7011 TestDelegate d;
7012 {
[email protected]2ca01e52013-10-31 22:05:197013 URLRequest r(url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]d2a133182012-08-05 16:44:087014 r.Start();
7015 EXPECT_TRUE(r.is_pending());
7016
[email protected]255620da2013-08-19 13:14:297017 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:087018
7019 EXPECT_FALSE(r.is_pending());
7020 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
7021 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
7022 }
7023}
7024
[email protected]5accf7332009-11-24 03:41:387025// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127026TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:117027 ASSERT_TRUE(test_server_.Start());
7028
[email protected]a25e90e2009-09-09 17:05:377029 TestDelegate d;
7030 {
[email protected]2ca01e52013-10-31 22:05:197031 URLRequest r(
7032 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]a25e90e2009-09-09 17:05:377033 r.Start();
7034 EXPECT_TRUE(r.is_pending());
7035
[email protected]255620da2013-08-19 13:14:297036 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:377037
7038 EXPECT_FALSE(r.is_pending());
7039 EXPECT_EQ(1, d.response_started_count());
7040 EXPECT_FALSE(d.received_data_before_response());
7041 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:197042 EXPECT_EQ(test_server_.host_port_pair().host(),
7043 r.GetSocketAddress().host());
7044 EXPECT_EQ(test_server_.host_port_pair().port(),
7045 r.GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:377046 }
7047}
7048
[email protected]7df70012010-02-04 00:09:557049// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127050TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:117051 ASSERT_TRUE(test_server_.Start());
7052
[email protected]6cdfd7f2013-02-08 20:40:157053 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277054 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027055 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277056 TestDelegate d;
7057 {
[email protected]2ca01e52013-10-31 22:05:197058 URLRequest r(test_server_.GetURL("/LICENSE"),
7059 DEFAULT_PRIORITY,
7060 &d,
7061 &default_context_);
[email protected]dd265012009-01-08 20:45:277062 r.Start();
7063 EXPECT_TRUE(r.is_pending());
7064
[email protected]255620da2013-08-19 13:14:297065 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277066
7067 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497068 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277069
[email protected]ba2f3342009-07-30 18:08:427070 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277071 EXPECT_EQ(1, d.response_started_count());
7072 EXPECT_FALSE(d.received_data_before_response());
7073 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:197074 EXPECT_EQ(test_server_.host_port_pair().host(),
7075 r.GetSocketAddress().host());
7076 EXPECT_EQ(test_server_.host_port_pair().port(),
7077 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:277078 }
7079}
7080
[email protected]e9ecbd12009-12-20 18:44:407081// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127082TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:117083 ASSERT_TRUE(test_server_.Start());
7084
[email protected]6cdfd7f2013-02-08 20:40:157085 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277086 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027087 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277088 TestDelegate d;
7089 {
[email protected]ef2bf422012-05-11 03:27:097090 URLRequest r(
[email protected]95409e12010-08-17 20:07:117091 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]2ca01e52013-10-31 22:05:197092 DEFAULT_PRIORITY,
[email protected]94e2bbe2012-06-22 15:26:137093 &d,
7094 &default_context_);
[email protected]dd265012009-01-08 20:45:277095 r.Start();
7096 EXPECT_TRUE(r.is_pending());
7097
[email protected]255620da2013-08-19 13:14:297098 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277099
7100 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497101 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277102
[email protected]ba2f3342009-07-30 18:08:427103 EXPECT_FALSE(r.is_pending());
[email protected]6d81b482011-02-22 19:47:197104 EXPECT_EQ(test_server_.host_port_pair().host(),
7105 r.GetSocketAddress().host());
7106 EXPECT_EQ(test_server_.host_port_pair().port(),
7107 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:277108 EXPECT_EQ(1, d.response_started_count());
7109 EXPECT_FALSE(d.received_data_before_response());
7110 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:257111
7112 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:177113 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257114 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:277115 }
7116}
7117
[email protected]49abd652010-08-05 05:04:537118// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127119TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:117120 ASSERT_TRUE(test_server_.Start());
7121
[email protected]6cdfd7f2013-02-08 20:40:157122 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277123 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027124 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277125 TestDelegate d;
7126 {
[email protected]2ca01e52013-10-31 22:05:197127 URLRequest r(test_server_.GetURLWithUserAndPassword(
7128 "/LICENSE", "chrome", "wrong_password"),
7129 DEFAULT_PRIORITY,
7130 &d,
7131 &default_context_);
[email protected]dd265012009-01-08 20:45:277132 r.Start();
7133 EXPECT_TRUE(r.is_pending());
7134
[email protected]255620da2013-08-19 13:14:297135 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277136
7137 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497138 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277139
[email protected]ba2f3342009-07-30 18:08:427140 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277141 EXPECT_EQ(1, d.response_started_count());
7142 EXPECT_FALSE(d.received_data_before_response());
7143 EXPECT_EQ(d.bytes_received(), 0);
7144 }
7145}
7146
[email protected]cde4e80d2009-10-16 19:58:157147// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127148TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:117149 ASSERT_TRUE(test_server_.Start());
7150
[email protected]6cdfd7f2013-02-08 20:40:157151 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:587152 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7153 app_path = app_path.AppendASCII("LICENSE");
7154 TestDelegate d;
7155 // Set correct login credentials. The delegate will be asked for them when
7156 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587157 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:587158 {
[email protected]2ca01e52013-10-31 22:05:197159 URLRequest r(test_server_.GetURLWithUserAndPassword(
7160 "/LICENSE", "chrome", "wrong_password"),
7161 DEFAULT_PRIORITY,
7162 &d,
7163 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:587164 r.Start();
7165 EXPECT_TRUE(r.is_pending());
7166
[email protected]255620da2013-08-19 13:14:297167 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:587168
7169 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497170 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:587171
7172 EXPECT_FALSE(r.is_pending());
7173 EXPECT_EQ(1, d.response_started_count());
7174 EXPECT_FALSE(d.received_data_before_response());
7175 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7176 }
7177}
7178
[email protected]49abd652010-08-05 05:04:537179// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127180TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:117181 ASSERT_TRUE(test_server_.Start());
7182
[email protected]6cdfd7f2013-02-08 20:40:157183 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277184 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027185 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277186 TestDelegate d;
7187 {
[email protected]2ca01e52013-10-31 22:05:197188 URLRequest r(test_server_.GetURLWithUserAndPassword(
7189 "/LICENSE", "wrong_user", "chrome"),
7190 DEFAULT_PRIORITY,
7191 &d,
7192 &default_context_);
[email protected]dd265012009-01-08 20:45:277193 r.Start();
7194 EXPECT_TRUE(r.is_pending());
7195
[email protected]255620da2013-08-19 13:14:297196 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277197
7198 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497199 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277200
[email protected]ba2f3342009-07-30 18:08:427201 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277202 EXPECT_EQ(1, d.response_started_count());
7203 EXPECT_FALSE(d.received_data_before_response());
7204 EXPECT_EQ(d.bytes_received(), 0);
7205 }
7206}
[email protected]8b8a197d2009-08-26 15:57:587207
[email protected]cde4e80d2009-10-16 19:58:157208// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127209TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:117210 ASSERT_TRUE(test_server_.Start());
7211
[email protected]6cdfd7f2013-02-08 20:40:157212 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:587213 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7214 app_path = app_path.AppendASCII("LICENSE");
7215 TestDelegate d;
7216 // Set correct login credentials. The delegate will be asked for them when
7217 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587218 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:587219 {
[email protected]2ca01e52013-10-31 22:05:197220 URLRequest r(test_server_.GetURLWithUserAndPassword(
7221 "/LICENSE", "wrong_user", "chrome"),
7222 DEFAULT_PRIORITY,
7223 &d,
7224 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:587225 r.Start();
7226 EXPECT_TRUE(r.is_pending());
7227
[email protected]255620da2013-08-19 13:14:297228 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:587229
7230 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497231 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:587232
7233 EXPECT_FALSE(r.is_pending());
7234 EXPECT_EQ(1, d.response_started_count());
7235 EXPECT_FALSE(d.received_data_before_response());
7236 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7237 }
7238}
[email protected]60a3df52009-09-22 16:13:247239
[email protected]cde4e80d2009-10-16 19:58:157240// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127241TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:117242 ASSERT_TRUE(test_server_.Start());
7243
[email protected]6cdfd7f2013-02-08 20:40:157244 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:247245 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7246 app_path = app_path.AppendASCII("LICENSE");
7247
7248 scoped_ptr<TestDelegate> d(new TestDelegate);
7249 {
7250 // Pass correct login identity in the URL.
[email protected]ef2bf422012-05-11 03:27:097251 URLRequest r(
[email protected]2ca01e52013-10-31 22:05:197252 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7253 DEFAULT_PRIORITY,
[email protected]94e2bbe2012-06-22 15:26:137254 d.get(),
7255 &default_context_);
[email protected]60a3df52009-09-22 16:13:247256 r.Start();
7257 EXPECT_TRUE(r.is_pending());
7258
[email protected]255620da2013-08-19 13:14:297259 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247260
7261 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497262 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247263
7264 EXPECT_FALSE(r.is_pending());
7265 EXPECT_EQ(1, d->response_started_count());
7266 EXPECT_FALSE(d->received_data_before_response());
7267 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7268 }
7269
7270 d.reset(new TestDelegate);
7271 {
7272 // This request should use cached identity from previous request.
[email protected]2ca01e52013-10-31 22:05:197273 URLRequest r(test_server_.GetURL("/LICENSE"),
7274 DEFAULT_PRIORITY,
7275 d.get(),
7276 &default_context_);
[email protected]60a3df52009-09-22 16:13:247277 r.Start();
7278 EXPECT_TRUE(r.is_pending());
7279
[email protected]255620da2013-08-19 13:14:297280 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247281
7282 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497283 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247284
7285 EXPECT_FALSE(r.is_pending());
7286 EXPECT_EQ(1, d->response_started_count());
7287 EXPECT_FALSE(d->received_data_before_response());
7288 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7289 }
7290}
7291
[email protected]cde4e80d2009-10-16 19:58:157292// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127293TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:117294 ASSERT_TRUE(test_server_.Start());
7295
[email protected]6cdfd7f2013-02-08 20:40:157296 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:247297 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7298 app_path = app_path.AppendASCII("LICENSE");
7299
7300 scoped_ptr<TestDelegate> d(new TestDelegate);
7301 // Set correct login credentials. The delegate will be asked for them when
7302 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587303 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:247304 {
[email protected]2ca01e52013-10-31 22:05:197305 URLRequest r(test_server_.GetURLWithUserAndPassword(
7306 "/LICENSE", "chrome", "wrong_password"),
7307 DEFAULT_PRIORITY,
7308 d.get(),
7309 &default_context_);
[email protected]60a3df52009-09-22 16:13:247310 r.Start();
7311 EXPECT_TRUE(r.is_pending());
7312
[email protected]255620da2013-08-19 13:14:297313 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247314
7315 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497316 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247317
7318 EXPECT_FALSE(r.is_pending());
7319 EXPECT_EQ(1, d->response_started_count());
7320 EXPECT_FALSE(d->received_data_before_response());
7321 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7322 }
7323
7324 // Use a new delegate without explicit credentials. The cached ones should be
7325 // used.
7326 d.reset(new TestDelegate);
7327 {
7328 // Don't pass wrong credentials in the URL, they would override valid cached
7329 // ones.
[email protected]2ca01e52013-10-31 22:05:197330 URLRequest r(test_server_.GetURL("/LICENSE"),
7331 DEFAULT_PRIORITY,
7332 d.get(),
7333 &default_context_);
[email protected]60a3df52009-09-22 16:13:247334 r.Start();
7335 EXPECT_TRUE(r.is_pending());
7336
[email protected]255620da2013-08-19 13:14:297337 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247338
7339 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497340 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247341
7342 EXPECT_FALSE(r.is_pending());
7343 EXPECT_EQ(1, d->response_started_count());
7344 EXPECT_FALSE(d->received_data_before_response());
7345 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7346 }
7347}
[email protected]316c1e5e2012-09-12 15:17:447348#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:517349
7350} // namespace net