blob: cec9049a6b4261aa47fbbf4a15cb52445ac04464 [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"
[email protected]a8fed1742013-12-27 02:14:2447#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1148#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0649#include "net/cookies/cookie_monster.h"
50#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5251#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5352#include "net/dns/mock_host_resolver.h"
[email protected]ba2f3342009-07-30 18:08:4253#include "net/ftp/ftp_network_layer.h"
[email protected]b7572ea2013-11-26 20:16:3854#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5255#include "net/http/http_cache.h"
56#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1957#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2558#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2159#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0060#include "net/http/http_util.h"
[email protected]dffe8242012-03-20 15:14:2761#include "net/ocsp/nss_ocsp.h"
[email protected]63de95b2008-12-10 04:11:2762#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1963#include "net/socket/ssl_client_socket.h"
[email protected]536fd0b2013-03-14 17:41:5764#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1165#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2166#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3467#include "net/url_request/data_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]bcb84f8b2009-08-31 16:20:1470#include "net/url_request/url_request_http_job.h"
[email protected]9d5730b2012-08-24 17:42:4971#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5172#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4773#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4474#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5275#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1576#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5277
[email protected]02494ec2014-05-07 15:05:2978#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:5579#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:2980#include "net/url_request/file_protocol_handler.h"
81#include "net/url_request/url_request_file_dir_job.h"
82#endif
83
84#if !defined(DISABLE_FTP_SUPPORT)
85#include "net/url_request/ftp_protocol_handler.h"
86#endif
87
[email protected]dffe8242012-03-20 15:14:2788#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:4889#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:5690#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:2791#include "base/win/windows_version.h"
92#endif
93
[email protected]ad65a3e2013-12-25 18:18:0194using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:3395using base::Time;
96
[email protected]7461a402011-03-24 23:19:5197namespace net {
98
initial.commit586acc5fe2008-07-26 22:42:5299namespace {
100
[email protected]42cba2fb2013-03-29 19:58:57101const base::string16 kChrome(ASCIIToUTF16("chrome"));
102const base::string16 kSecret(ASCIIToUTF16("secret"));
103const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44104
[email protected]2bba3252013-04-08 19:50:59105// Tests load timing information in the case a fresh connection was used, with
106// no proxy.
[email protected]58e32bb2013-01-21 18:23:25107void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
108 int connect_timing_flags) {
109 EXPECT_FALSE(load_timing_info.socket_reused);
110 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
111
112 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
113 EXPECT_FALSE(load_timing_info.request_start.is_null());
114
115 EXPECT_LE(load_timing_info.request_start,
116 load_timing_info.connect_timing.connect_start);
117 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
118 connect_timing_flags);
119 EXPECT_LE(load_timing_info.connect_timing.connect_end,
120 load_timing_info.send_start);
121 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
122 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
123
[email protected]58e32bb2013-01-21 18:23:25124 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
125 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
126}
127
[email protected]2bba3252013-04-08 19:50:59128// Same as above, but with proxy times.
129void TestLoadTimingNotReusedWithProxy(
130 const net::LoadTimingInfo& load_timing_info,
131 int connect_timing_flags) {
132 EXPECT_FALSE(load_timing_info.socket_reused);
133 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
134
135 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
136 EXPECT_FALSE(load_timing_info.request_start.is_null());
137
138 EXPECT_LE(load_timing_info.request_start,
139 load_timing_info.proxy_resolve_start);
140 EXPECT_LE(load_timing_info.proxy_resolve_start,
141 load_timing_info.proxy_resolve_end);
142 EXPECT_LE(load_timing_info.proxy_resolve_end,
143 load_timing_info.connect_timing.connect_start);
144 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
145 connect_timing_flags);
146 EXPECT_LE(load_timing_info.connect_timing.connect_end,
147 load_timing_info.send_start);
148 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
149 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
150}
151
152// Same as above, but with a reused socket and proxy times.
153void TestLoadTimingReusedWithProxy(
154 const net::LoadTimingInfo& load_timing_info) {
155 EXPECT_TRUE(load_timing_info.socket_reused);
156 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
157
158 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
159 EXPECT_FALSE(load_timing_info.request_start.is_null());
160
161 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
162
163 EXPECT_LE(load_timing_info.request_start,
164 load_timing_info.proxy_resolve_start);
165 EXPECT_LE(load_timing_info.proxy_resolve_start,
166 load_timing_info.proxy_resolve_end);
167 EXPECT_LE(load_timing_info.proxy_resolve_end,
168 load_timing_info.send_start);
169 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
170 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
171}
172
[email protected]3b23a222013-05-15 21:33:25173// Tests load timing information in the case of a cache hit, when no cache
174// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17175base::StringPiece TestNetResourceProvider(int key) {
176 return "header";
177}
178
179void FillBuffer(char* buffer, size_t len) {
180 static bool called = false;
181 if (!called) {
182 called = true;
183 int seed = static_cast<int>(Time::Now().ToInternalValue());
184 srand(seed);
185 }
186
187 for (size_t i = 0; i < len; i++) {
188 buffer[i] = static_cast<char>(rand());
189 if (!buffer[i])
190 buffer[i] = 'g';
191 }
192}
193
194#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25195void TestLoadTimingCacheHitNoNetwork(
196 const net::LoadTimingInfo& load_timing_info) {
197 EXPECT_FALSE(load_timing_info.socket_reused);
198 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
199
200 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
201 EXPECT_FALSE(load_timing_info.request_start.is_null());
202
203 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
204 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
205 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
206 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
207
208 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
209 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
210}
211
212// Tests load timing in the case that there is no HTTP response. This can be
213// used to test in the case of errors or non-HTTP requests.
214void TestLoadTimingNoHttpResponse(
[email protected]58e32bb2013-01-21 18:23:25215 const net::LoadTimingInfo& load_timing_info) {
216 EXPECT_FALSE(load_timing_info.socket_reused);
217 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
218
219 // Only the request times should be non-null.
220 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
221 EXPECT_FALSE(load_timing_info.request_start.is_null());
222
223 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
224
225 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
226 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
227 EXPECT_TRUE(load_timing_info.send_start.is_null());
228 EXPECT_TRUE(load_timing_info.send_end.is_null());
229 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
230}
231
[email protected]71c64f62008-11-15 04:36:51232// Do a case-insensitive search through |haystack| for |needle|.
233bool ContainsString(const std::string& haystack, const char* needle) {
234 std::string::const_iterator it =
235 std::search(haystack.begin(),
236 haystack.end(),
237 needle,
238 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35239 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51240 return it != haystack.end();
241}
242
[email protected]f288ef02012-12-15 20:28:28243UploadDataStream* CreateSimpleUploadData(const char* data) {
244 scoped_ptr<UploadElementReader> reader(
245 new UploadBytesElementReader(data, strlen(data)));
246 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23247}
248
[email protected]96adadb2010-08-28 01:16:17249// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51250void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17251 // -1 means unknown. 0 means no encryption.
252 EXPECT_GT(ssl_info.security_bits, 0);
253
254 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
[email protected]7461a402011-03-24 23:19:51255 int cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17256 ssl_info.connection_status);
257 EXPECT_NE(0, cipher_suite);
258}
259
[email protected]79e1fd62013-06-20 06:50:04260void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
261 const GURL& host_url) {
262 std::string sent_value;
263
264 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
265 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
266
267 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
268 EXPECT_EQ("keep-alive", sent_value);
269}
270
[email protected]ede03212012-09-07 12:52:26271bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27272 size_t size = a.size();
273
274 if (size != b.size())
275 return false;
276
277 for (size_t i = 0; i < size; ++i) {
278 if (!a[i].Equals(b[i]))
279 return false;
280 }
281
282 return true;
283}
[email protected]e3a85452013-11-14 01:46:17284#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27285
[email protected]dc5a5cf2012-09-26 02:49:30286// A network delegate that allows the user to choose a subset of request stages
287// to block in. When blocking, the delegate can do one of the following:
288// * synchronously return a pre-specified error code, or
289// * asynchronously return that value via an automatically called callback,
290// or
291// * block and wait for the user to do a callback.
292// Additionally, the user may also specify a redirect URL -- then each request
293// with the current URL different from the redirect target will be redirected
294// to that target, in the on-before-URL-request stage, independent of whether
295// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12296class BlockingNetworkDelegate : public TestNetworkDelegate {
297 public:
[email protected]dc5a5cf2012-09-26 02:49:30298 // Stages in which the delegate can block.
299 enum Stage {
[email protected]9045b8822012-01-13 20:35:35300 NOT_BLOCKED = 0,
301 ON_BEFORE_URL_REQUEST = 1 << 0,
302 ON_BEFORE_SEND_HEADERS = 1 << 1,
303 ON_HEADERS_RECEIVED = 1 << 2,
304 ON_AUTH_REQUIRED = 1 << 3
305 };
306
[email protected]dc5a5cf2012-09-26 02:49:30307 // Behavior during blocked stages. During other stages, just
308 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
309 enum BlockMode {
310 SYNCHRONOUS, // No callback, returns specified return values.
311 AUTO_CALLBACK, // |this| posts a task to run the callback using the
312 // specified return codes.
313 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
314 // |auth_retval_| are ignored. In every blocking stage the
315 // message loop is quit.
316 };
317
318 // Creates a delegate which does not block at all.
319 explicit BlockingNetworkDelegate(BlockMode block_mode);
320
321 // For users to trigger a callback returning |response|.
322 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
323 // Only call if |block_mode_| == USER_CALLBACK.
324 void DoCallback(int response);
325 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
326
327 // Setters.
328 void set_retval(int retval) {
329 ASSERT_NE(USER_CALLBACK, block_mode_);
330 ASSERT_NE(ERR_IO_PENDING, retval);
331 ASSERT_NE(OK, retval);
332 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35333 }
334
[email protected]dc5a5cf2012-09-26 02:49:30335 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
336 // |auth_credentials_| will be passed with the response.
337 void set_auth_retval(AuthRequiredResponse auth_retval) {
338 ASSERT_NE(USER_CALLBACK, block_mode_);
339 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
340 auth_retval_ = auth_retval;
341 }
342 void set_auth_credentials(const AuthCredentials& auth_credentials) {
343 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35344 }
345
[email protected]dc5a5cf2012-09-26 02:49:30346 void set_redirect_url(const GURL& url) {
347 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35348 }
349
[email protected]dc5a5cf2012-09-26 02:49:30350 void set_block_on(int block_on) {
351 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35352 }
353
[email protected]dc5a5cf2012-09-26 02:49:30354 // Allows the user to check in which state did we block.
355 Stage stage_blocked_for_callback() const {
356 EXPECT_EQ(USER_CALLBACK, block_mode_);
357 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35358 }
359
360 private:
[email protected]dc5a5cf2012-09-26 02:49:30361 void RunCallback(int response, const CompletionCallback& callback);
362 void RunAuthCallback(AuthRequiredResponse response,
363 const AuthCallback& callback);
364
[email protected]9045b8822012-01-13 20:35:35365 // TestNetworkDelegate implementation.
366 virtual int OnBeforeURLRequest(URLRequest* request,
367 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30368 GURL* new_url) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35369
370 virtual int OnBeforeSendHeaders(URLRequest* request,
371 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30372 HttpRequestHeaders* headers) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35373
374 virtual int OnHeadersReceived(
375 URLRequest* request,
376 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32377 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16378 scoped_refptr<HttpResponseHeaders>* override_response_headers,
379 GURL* allowed_unsafe_redirect_url) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35380
381 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
382 URLRequest* request,
383 const AuthChallengeInfo& auth_info,
384 const AuthCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30385 AuthCredentials* credentials) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35386
[email protected]dc5a5cf2012-09-26 02:49:30387 // Resets the callbacks and |stage_blocked_for_callback_|.
388 void Reset();
[email protected]9045b8822012-01-13 20:35:35389
[email protected]dc5a5cf2012-09-26 02:49:30390 // Checks whether we should block in |stage|. If yes, returns an error code
391 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
392 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
393
394 // Configuration parameters, can be adjusted by public methods:
395 const BlockMode block_mode_;
396
397 // Values returned on blocking stages when mode is SYNCHRONOUS or
398 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
399 int retval_; // To be returned in non-auth stages.
400 AuthRequiredResponse auth_retval_;
401
[email protected]5f714132014-03-26 10:41:16402 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30403 int block_on_; // Bit mask: in which stages to block.
404
405 // |auth_credentials_| will be copied to |*target_auth_credential_| on
406 // callback.
407 AuthCredentials auth_credentials_;
408 AuthCredentials* target_auth_credentials_;
409
410 // Internal variables, not set by not the user:
411 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
412 // USER_CALLBACK).
413 Stage stage_blocked_for_callback_;
414
415 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35416 CompletionCallback callback_;
417 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30418
419 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
420
421 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35422};
423
[email protected]dc5a5cf2012-09-26 02:49:30424BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
425 : block_mode_(block_mode),
426 retval_(OK),
427 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
428 block_on_(0),
429 target_auth_credentials_(NULL),
430 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32431 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30432}
433
434void BlockingNetworkDelegate::DoCallback(int response) {
435 ASSERT_EQ(USER_CALLBACK, block_mode_);
436 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
437 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
438 CompletionCallback callback = callback_;
439 Reset();
440 RunCallback(response, callback);
441}
442
443void BlockingNetworkDelegate::DoAuthCallback(
444 NetworkDelegate::AuthRequiredResponse response) {
445 ASSERT_EQ(USER_CALLBACK, block_mode_);
446 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
447 AuthCallback auth_callback = auth_callback_;
448 Reset();
449 RunAuthCallback(response, auth_callback);
450}
451
452void BlockingNetworkDelegate::RunCallback(int response,
453 const CompletionCallback& callback) {
454 callback.Run(response);
455}
456
457void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
458 const AuthCallback& callback) {
459 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
460 ASSERT_TRUE(target_auth_credentials_ != NULL);
461 *target_auth_credentials_ = auth_credentials_;
462 }
463 callback.Run(response);
464}
465
466int BlockingNetworkDelegate::OnBeforeURLRequest(
467 URLRequest* request,
468 const CompletionCallback& callback,
469 GURL* new_url) {
470 if (redirect_url_ == request->url())
471 return OK; // We've already seen this request and redirected elsewhere.
472
473 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
474
475 if (!redirect_url_.is_empty())
476 *new_url = redirect_url_;
477
478 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
479}
480
481int BlockingNetworkDelegate::OnBeforeSendHeaders(
482 URLRequest* request,
483 const CompletionCallback& callback,
484 HttpRequestHeaders* headers) {
485 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
486
487 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
488}
489
490int BlockingNetworkDelegate::OnHeadersReceived(
491 URLRequest* request,
492 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32493 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16494 scoped_refptr<HttpResponseHeaders>* override_response_headers,
495 GURL* allowed_unsafe_redirect_url) {
496 TestNetworkDelegate::OnHeadersReceived(request,
497 callback,
498 original_response_headers,
499 override_response_headers,
500 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30501
502 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
503}
504
505NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
506 URLRequest* request,
507 const AuthChallengeInfo& auth_info,
508 const AuthCallback& callback,
509 AuthCredentials* credentials) {
510 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
511 credentials);
512 // Check that the user has provided callback for the previous blocked stage.
513 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
514
515 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
516 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
517 }
518
519 target_auth_credentials_ = credentials;
520
521 switch (block_mode_) {
522 case SYNCHRONOUS:
523 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
524 *target_auth_credentials_ = auth_credentials_;
525 return auth_retval_;
526
527 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34528 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30529 FROM_HERE,
530 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
531 weak_factory_.GetWeakPtr(), auth_retval_, callback));
532 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
533
534 case USER_CALLBACK:
535 auth_callback_ = callback;
536 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34537 base::MessageLoop::current()->PostTask(FROM_HERE,
538 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30539 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
540 }
541 NOTREACHED();
542 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
543}
544
545void BlockingNetworkDelegate::Reset() {
546 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
547 stage_blocked_for_callback_ = NOT_BLOCKED;
548 callback_.Reset();
549 auth_callback_.Reset();
550}
551
552int BlockingNetworkDelegate::MaybeBlockStage(
553 BlockingNetworkDelegate::Stage stage,
554 const CompletionCallback& callback) {
555 // Check that the user has provided callback for the previous blocked stage.
556 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
557
558 if ((block_on_ & stage) == 0) {
559 return OK;
560 }
561
562 switch (block_mode_) {
563 case SYNCHRONOUS:
564 EXPECT_NE(OK, retval_);
565 return retval_;
566
567 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34568 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30569 FROM_HERE,
570 base::Bind(&BlockingNetworkDelegate::RunCallback,
571 weak_factory_.GetWeakPtr(), retval_, callback));
572 return ERR_IO_PENDING;
573
574 case USER_CALLBACK:
575 callback_ = callback;
576 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34577 base::MessageLoop::current()->PostTask(FROM_HERE,
578 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30579 return ERR_IO_PENDING;
580 }
581 NOTREACHED();
582 return 0;
583}
584
[email protected]d5a4dd62012-05-23 01:41:04585class TestURLRequestContextWithProxy : public TestURLRequestContext {
586 public:
587 // Does not own |delegate|.
588 TestURLRequestContextWithProxy(const std::string& proxy,
589 NetworkDelegate* delegate)
590 : TestURLRequestContext(true) {
591 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
592 set_network_delegate(delegate);
593 Init();
594 }
595 virtual ~TestURLRequestContextWithProxy() {}
596};
597
598} // namespace
599
[email protected]a592c0432012-12-01 18:10:29600// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48601class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00602 public:
[email protected]ef2bf422012-05-11 03:27:09603 URLRequestTest() : default_context_(true) {
604 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25605 default_context_.set_net_log(&net_log_);
[email protected]e0f35c92013-05-08 16:04:34606 job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
[email protected]02494ec2014-05-07 15:05:29607#if !defined(DISABLE_FILE_SUPPORT)
[email protected]255620da2013-08-19 13:14:29608 job_factory_.SetProtocolHandler(
609 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
[email protected]02494ec2014-05-07 15:05:29610#endif
[email protected]e0f35c92013-05-08 16:04:34611 default_context_.set_job_factory(&job_factory_);
[email protected]ef2bf422012-05-11 03:27:09612 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:50613 }
[email protected]e4034ad2013-09-20 08:36:18614 virtual ~URLRequestTest() {
615 // URLRequestJobs may post clean-up tasks on destruction.
616 base::RunLoop().RunUntilIdle();
617 }
[email protected]87a09a92011-07-14 15:50:50618
[email protected]3c5ca8c2011-09-29 01:14:51619 // Adds the TestJobInterceptor to the default context.
620 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23621 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
[email protected]e0f35c92013-05-08 16:04:34622 job_factory_.SetProtocolHandler("http", NULL);
623 job_factory_.SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23624 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51625 }
626
[email protected]87a09a92011-07-14 15:50:50627 protected:
[email protected]58e32bb2013-01-21 18:23:25628 CapturingNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24629 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]e0f35c92013-05-08 16:04:34630 URLRequestJobFactoryImpl job_factory_;
[email protected]ef2bf422012-05-11 03:27:09631 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48632};
633
[email protected]316c1e5e2012-09-12 15:17:44634TEST_F(URLRequestTest, AboutBlankTest) {
635 TestDelegate d;
636 {
[email protected]2ca01e52013-10-31 22:05:19637 URLRequest r(GURL("about:blank"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44638
639 r.Start();
640 EXPECT_TRUE(r.is_pending());
641
[email protected]255620da2013-08-19 13:14:29642 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44643
644 EXPECT_TRUE(!r.is_pending());
645 EXPECT_FALSE(d.received_data_before_response());
646 EXPECT_EQ(d.bytes_received(), 0);
647 EXPECT_EQ("", r.GetSocketAddress().host());
648 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04649
650 HttpRequestHeaders headers;
651 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44652 }
653}
654
655TEST_F(URLRequestTest, DataURLImageTest) {
656 TestDelegate d;
657 {
658 // Use our nice little Chrome logo.
[email protected]2ca01e52013-10-31 22:05:19659 URLRequest r(
660 GURL(
[email protected]316c1e5e2012-09-12 15:17:44661 "data:image/png;base64,"
662 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
663 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
664 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
665 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
666 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
667 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
668 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
669 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
670 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
671 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
672 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
673 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
674 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
675 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
676 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
677 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
678 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
679 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
[email protected]2ca01e52013-10-31 22:05:19680 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:44681 &d,
682 &default_context_);
683
684 r.Start();
685 EXPECT_TRUE(r.is_pending());
686
[email protected]255620da2013-08-19 13:14:29687 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44688
689 EXPECT_TRUE(!r.is_pending());
690 EXPECT_FALSE(d.received_data_before_response());
691 EXPECT_EQ(d.bytes_received(), 911);
692 EXPECT_EQ("", r.GetSocketAddress().host());
693 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04694
695 HttpRequestHeaders headers;
696 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44697 }
698}
699
[email protected]5ecf7cb282014-05-11 01:49:55700#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44701TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15702 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44703 PathService::Get(base::FILE_EXE, &app_path);
704 GURL app_url = FilePathToFileURL(app_path);
705
706 TestDelegate d;
707 {
[email protected]2ca01e52013-10-31 22:05:19708 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44709
710 r.Start();
711 EXPECT_TRUE(r.is_pending());
712
[email protected]255620da2013-08-19 13:14:29713 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44714
715 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49716 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44717
718 EXPECT_TRUE(!r.is_pending());
719 EXPECT_EQ(1, d.response_started_count());
720 EXPECT_FALSE(d.received_data_before_response());
721 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
722 EXPECT_EQ("", r.GetSocketAddress().host());
723 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04724
725 HttpRequestHeaders headers;
726 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44727 }
728}
729
[email protected]ba40bb762012-12-17 07:11:04730TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15731 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04732 PathService::Get(base::FILE_EXE, &app_path);
733 GURL app_url = FilePathToFileURL(app_path);
734
735 TestDelegate d;
736 {
[email protected]2ca01e52013-10-31 22:05:19737 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]ba40bb762012-12-17 07:11:04738
739 r.Start();
740 EXPECT_TRUE(r.is_pending());
741 r.Cancel();
742 }
[email protected]79e1fd62013-06-20 06:50:04743 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04744 // destroyed.
[email protected]255620da2013-08-19 13:14:29745 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04746}
747
[email protected]316c1e5e2012-09-12 15:17:44748TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
749 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17750 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44751 FillBuffer(buffer.get(), buffer_size);
752
[email protected]6cdfd7f2013-02-08 20:40:15753 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52754 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44755 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30756 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44757
758 int64 file_size;
[email protected]56285702013-12-04 18:22:49759 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44760
761 const size_t first_byte_position = 500;
762 const size_t last_byte_position = buffer_size - first_byte_position;
763 const size_t content_length = last_byte_position - first_byte_position + 1;
764 std::string partial_buffer_string(buffer.get() + first_byte_position,
765 buffer.get() + last_byte_position + 1);
766
767 TestDelegate d;
768 {
[email protected]2ca01e52013-10-31 22:05:19769 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44770
771 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38772 headers.SetHeader(
773 HttpRequestHeaders::kRange,
774 net::HttpByteRange::Bounded(
775 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]316c1e5e2012-09-12 15:17:44776 r.SetExtraRequestHeaders(headers);
777 r.Start();
778 EXPECT_TRUE(r.is_pending());
779
[email protected]255620da2013-08-19 13:14:29780 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44781 EXPECT_TRUE(!r.is_pending());
782 EXPECT_EQ(1, d.response_started_count());
783 EXPECT_FALSE(d.received_data_before_response());
784 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
785 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
786 EXPECT_TRUE(partial_buffer_string == d.data_received());
787 }
788
[email protected]dd3aa792013-07-16 19:10:23789 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44790}
791
792TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
793 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17794 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44795 FillBuffer(buffer.get(), buffer_size);
796
[email protected]6cdfd7f2013-02-08 20:40:15797 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52798 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44799 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30800 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44801
802 int64 file_size;
[email protected]56285702013-12-04 18:22:49803 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44804
805 const size_t first_byte_position = 500;
806 const size_t last_byte_position = buffer_size - 1;
807 const size_t content_length = last_byte_position - first_byte_position + 1;
808 std::string partial_buffer_string(buffer.get() + first_byte_position,
809 buffer.get() + last_byte_position + 1);
810
811 TestDelegate d;
812 {
[email protected]2ca01e52013-10-31 22:05:19813 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44814
815 HttpRequestHeaders headers;
816 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]b7572ea2013-11-26 20:16:38817 net::HttpByteRange::RightUnbounded(
818 first_byte_position).GetHeaderValue());
[email protected]316c1e5e2012-09-12 15:17:44819 r.SetExtraRequestHeaders(headers);
820 r.Start();
821 EXPECT_TRUE(r.is_pending());
822
[email protected]255620da2013-08-19 13:14:29823 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44824 EXPECT_TRUE(!r.is_pending());
825 EXPECT_EQ(1, d.response_started_count());
826 EXPECT_FALSE(d.received_data_before_response());
827 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
828 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
829 EXPECT_TRUE(partial_buffer_string == d.data_received());
830 }
831
[email protected]dd3aa792013-07-16 19:10:23832 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44833}
834
835TEST_F(URLRequestTest, FileTestMultipleRanges) {
836 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17837 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44838 FillBuffer(buffer.get(), buffer_size);
839
[email protected]6cdfd7f2013-02-08 20:40:15840 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52841 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44842 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30843 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44844
845 int64 file_size;
[email protected]56285702013-12-04 18:22:49846 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44847
848 TestDelegate d;
849 {
[email protected]2ca01e52013-10-31 22:05:19850 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44851
852 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38853 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]316c1e5e2012-09-12 15:17:44854 r.SetExtraRequestHeaders(headers);
855 r.Start();
856 EXPECT_TRUE(r.is_pending());
857
[email protected]255620da2013-08-19 13:14:29858 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44859 EXPECT_TRUE(d.request_failed());
860 }
861
[email protected]dd3aa792013-07-16 19:10:23862 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44863}
864
[email protected]3ca8b362013-11-11 22:18:07865TEST_F(URLRequestTest, AllowFileURLs) {
866 base::ScopedTempDir temp_dir;
867 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
868 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52869 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07870 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30871 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]3ca8b362013-11-11 22:18:07872 GURL test_file_url = net::FilePathToFileURL(test_file);
873
874 {
875 TestDelegate d;
876 TestNetworkDelegate network_delegate;
877 network_delegate.set_can_access_files(true);
878 default_context_.set_network_delegate(&network_delegate);
879 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
880 r.Start();
881 base::RunLoop().Run();
882 EXPECT_FALSE(d.request_failed());
883 EXPECT_EQ(test_data, d.data_received());
884 }
885
886 {
887 TestDelegate d;
888 TestNetworkDelegate network_delegate;
889 network_delegate.set_can_access_files(false);
890 default_context_.set_network_delegate(&network_delegate);
891 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
892 r.Start();
893 base::RunLoop().Run();
894 EXPECT_TRUE(d.request_failed());
895 EXPECT_EQ("", d.data_received());
896 }
897}
898
[email protected]316c1e5e2012-09-12 15:17:44899
900TEST_F(URLRequestTest, FileDirCancelTest) {
901 // Put in mock resource provider.
902 NetModule::SetResourceProvider(TestNetResourceProvider);
903
904 TestDelegate d;
905 {
[email protected]6cdfd7f2013-02-08 20:40:15906 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44907 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
908 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
909 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
910
[email protected]2ca01e52013-10-31 22:05:19911 URLRequest req(
912 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44913 req.Start();
914 EXPECT_TRUE(req.is_pending());
915
916 d.set_cancel_in_received_data_pending(true);
917
[email protected]255620da2013-08-19 13:14:29918 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44919 }
920
921 // Take out mock resource provider.
922 NetModule::SetResourceProvider(NULL);
923}
924
[email protected]5f9581402013-10-30 13:08:32925TEST_F(URLRequestTest, FileDirOutputSanity) {
926 // Verify the general sanity of the the output of the file:
927 // directory lister by checking for the output of a known existing
928 // file.
929 const char sentinel_name[] = "filedir-sentinel";
930
931 base::FilePath path;
932 PathService::Get(base::DIR_SOURCE_ROOT, &path);
933 path = path.Append(FILE_PATH_LITERAL("net"));
934 path = path.Append(FILE_PATH_LITERAL("data"));
935 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
936
937 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:19938 URLRequest req(
939 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]5f9581402013-10-30 13:08:32940 req.Start();
941 base::RunLoop().Run();
942
943 // Generate entry for the sentinel file.
944 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:58945 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:49946 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:32947 EXPECT_GT(info.size, 0);
948 std::string sentinel_output = GetDirectoryListingEntry(
949 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
950 std::string(sentinel_name),
951 false /* is_dir */,
952 info.size,
953 info.last_modified);
954
955 ASSERT_LT(0, d.bytes_received());
956 ASSERT_FALSE(d.request_failed());
957 ASSERT_TRUE(req.status().is_success());
958 // Check for the entry generated for the "sentinel" file.
959 const std::string& data = d.data_received();
960 ASSERT_NE(data.find(sentinel_output), std::string::npos);
961}
962
[email protected]316c1e5e2012-09-12 15:17:44963TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
964 // There is an implicit redirect when loading a file path that matches a
965 // directory and does not end with a slash. Ensure that following such
966 // redirects does not crash. See http://crbug.com/18686.
967
[email protected]6cdfd7f2013-02-08 20:40:15968 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:44969 PathService::Get(base::DIR_SOURCE_ROOT, &path);
970 path = path.Append(FILE_PATH_LITERAL("net"));
971 path = path.Append(FILE_PATH_LITERAL("data"));
972 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
973
974 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:19975 URLRequest req(
976 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44977 req.Start();
[email protected]255620da2013-08-19 13:14:29978 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44979
980 ASSERT_EQ(1, d.received_redirect_count());
981 ASSERT_LT(0, d.bytes_received());
982 ASSERT_FALSE(d.request_failed());
983 ASSERT_TRUE(req.status().is_success());
984}
985
986#if defined(OS_WIN)
987// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
988TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
989 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:19990 URLRequest req(GURL("file:///"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44991 req.Start();
[email protected]255620da2013-08-19 13:14:29992 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44993
994 ASSERT_EQ(1, d.received_redirect_count());
995 ASSERT_FALSE(req.status().is_success());
996}
[email protected]5ecf7cb282014-05-11 01:49:55997#endif // defined(OS_WIN)
998
999#endif // !defined(DISABLE_FILE_SUPPORT)
1000
1001TEST_F(URLRequestTest, InvalidUrlTest) {
1002 TestDelegate d;
1003 {
1004 URLRequest r(GURL("invalid url"), DEFAULT_PRIORITY, &d, &default_context_);
1005
1006 r.Start();
1007 EXPECT_TRUE(r.is_pending());
1008
1009 base::RunLoop().Run();
1010 EXPECT_TRUE(d.request_failed());
1011 }
1012}
1013
1014#if defined(OS_WIN)
1015TEST_F(URLRequestTest, ResolveShortcutTest) {
1016 base::FilePath app_path;
1017 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1018 app_path = app_path.AppendASCII("net");
1019 app_path = app_path.AppendASCII("data");
1020 app_path = app_path.AppendASCII("url_request_unittest");
1021 app_path = app_path.AppendASCII("with-headers.html");
1022
1023 std::wstring lnk_path = app_path.value() + L".lnk";
1024
1025 base::win::ScopedCOMInitializer com_initializer;
1026
1027 // Temporarily create a shortcut for test
1028 {
1029 base::win::ScopedComPtr<IShellLink> shell;
1030 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1031 CLSCTX_INPROC_SERVER)));
1032 base::win::ScopedComPtr<IPersistFile> persist;
1033 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1034 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1035 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1036 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1037 }
1038
1039 TestDelegate d;
1040 {
1041 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)),
1042 DEFAULT_PRIORITY,
1043 &d,
1044 &default_context_);
1045
1046 r.Start();
1047 EXPECT_TRUE(r.is_pending());
1048
1049 base::RunLoop().Run();
1050
1051 WIN32_FILE_ATTRIBUTE_DATA data;
1052 GetFileAttributesEx(app_path.value().c_str(),
1053 GetFileExInfoStandard, &data);
1054 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1055 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1056 FILE_ATTRIBUTE_NORMAL, NULL);
1057 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1058 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1059 DWORD read_size;
1060 BOOL result;
1061 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1062 &read_size, NULL);
1063 std::string content(buffer.get(), read_size);
1064 CloseHandle(file);
1065
1066 EXPECT_TRUE(!r.is_pending());
1067 EXPECT_EQ(1, d.received_redirect_count());
1068 EXPECT_EQ(content, d.data_received());
1069 }
1070
1071 // Clean the shortcut
1072 DeleteFile(lnk_path.c_str());
1073}
1074#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441075
1076// Custom URLRequestJobs for use with interceptor tests
1077class RestartTestJob : public URLRequestTestJob {
1078 public:
1079 RestartTestJob(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 this->NotifyRestartRequired();
1084 }
1085 private:
[email protected]46fadfd2013-02-06 09:40:161086 virtual ~RestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441087};
1088
1089class CancelTestJob : public URLRequestTestJob {
1090 public:
1091 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1092 : URLRequestTestJob(request, network_delegate, true) {}
1093 protected:
[email protected]46fadfd2013-02-06 09:40:161094 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441095 request_->Cancel();
1096 }
1097 private:
[email protected]46fadfd2013-02-06 09:40:161098 virtual ~CancelTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441099};
1100
1101class CancelThenRestartTestJob : public URLRequestTestJob {
1102 public:
1103 explicit CancelThenRestartTestJob(URLRequest* request,
1104 NetworkDelegate* network_delegate)
1105 : URLRequestTestJob(request, network_delegate, true) {
1106 }
1107 protected:
[email protected]46fadfd2013-02-06 09:40:161108 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441109 request_->Cancel();
1110 this->NotifyRestartRequired();
1111 }
1112 private:
[email protected]46fadfd2013-02-06 09:40:161113 virtual ~CancelThenRestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441114};
1115
1116// An Interceptor for use with interceptor tests
1117class TestInterceptor : URLRequest::Interceptor {
1118 public:
1119 TestInterceptor()
1120 : intercept_main_request_(false), restart_main_request_(false),
1121 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1122 simulate_main_network_error_(false),
1123 intercept_redirect_(false), cancel_redirect_request_(false),
1124 intercept_final_response_(false), cancel_final_request_(false),
1125 did_intercept_main_(false), did_restart_main_(false),
1126 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1127 did_simulate_error_main_(false),
1128 did_intercept_redirect_(false), did_cancel_redirect_(false),
1129 did_intercept_final_(false), did_cancel_final_(false) {
1130 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1131 }
1132
[email protected]46fadfd2013-02-06 09:40:161133 virtual ~TestInterceptor() {
[email protected]316c1e5e2012-09-12 15:17:441134 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1135 }
1136
[email protected]46fadfd2013-02-06 09:40:161137 virtual URLRequestJob* MaybeIntercept(
1138 URLRequest* request,
1139 NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441140 if (restart_main_request_) {
1141 restart_main_request_ = false;
1142 did_restart_main_ = true;
1143 return new RestartTestJob(request, network_delegate);
1144 }
1145 if (cancel_main_request_) {
1146 cancel_main_request_ = false;
1147 did_cancel_main_ = true;
1148 return new CancelTestJob(request, network_delegate);
1149 }
1150 if (cancel_then_restart_main_request_) {
1151 cancel_then_restart_main_request_ = false;
1152 did_cancel_then_restart_main_ = true;
1153 return new CancelThenRestartTestJob(request, network_delegate);
1154 }
1155 if (simulate_main_network_error_) {
1156 simulate_main_network_error_ = false;
1157 did_simulate_error_main_ = true;
1158 // will error since the requeted url is not one of its canned urls
1159 return new URLRequestTestJob(request, network_delegate, true);
1160 }
1161 if (!intercept_main_request_)
1162 return NULL;
1163 intercept_main_request_ = false;
1164 did_intercept_main_ = true;
[email protected]2bba3252013-04-08 19:50:591165 URLRequestTestJob* job = new URLRequestTestJob(request,
1166 network_delegate,
1167 main_headers_,
1168 main_data_,
1169 true);
1170 job->set_load_timing_info(main_request_load_timing_info_);
1171 return job;
[email protected]316c1e5e2012-09-12 15:17:441172 }
1173
1174 virtual URLRequestJob* MaybeInterceptRedirect(
1175 URLRequest* request,
1176 NetworkDelegate* network_delegate,
[email protected]46fadfd2013-02-06 09:40:161177 const GURL& location) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441178 if (cancel_redirect_request_) {
1179 cancel_redirect_request_ = false;
1180 did_cancel_redirect_ = true;
1181 return new CancelTestJob(request, network_delegate);
1182 }
1183 if (!intercept_redirect_)
1184 return NULL;
1185 intercept_redirect_ = false;
1186 did_intercept_redirect_ = true;
1187 return new URLRequestTestJob(request,
1188 network_delegate,
1189 redirect_headers_,
1190 redirect_data_,
1191 true);
1192 }
1193
1194 virtual URLRequestJob* MaybeInterceptResponse(
[email protected]46fadfd2013-02-06 09:40:161195 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441196 if (cancel_final_request_) {
1197 cancel_final_request_ = false;
1198 did_cancel_final_ = true;
1199 return new CancelTestJob(request, network_delegate);
1200 }
1201 if (!intercept_final_response_)
1202 return NULL;
1203 intercept_final_response_ = false;
1204 did_intercept_final_ = true;
1205 return new URLRequestTestJob(request,
1206 network_delegate,
1207 final_headers_,
1208 final_data_,
1209 true);
1210 }
1211
[email protected]2bba3252013-04-08 19:50:591212 // Whether to intercept the main request, and if so the response to return and
1213 // the LoadTimingInfo to use.
[email protected]316c1e5e2012-09-12 15:17:441214 bool intercept_main_request_;
1215 std::string main_headers_;
1216 std::string main_data_;
[email protected]2bba3252013-04-08 19:50:591217 LoadTimingInfo main_request_load_timing_info_;
[email protected]316c1e5e2012-09-12 15:17:441218
1219 // Other actions we take at MaybeIntercept time
1220 bool restart_main_request_;
1221 bool cancel_main_request_;
1222 bool cancel_then_restart_main_request_;
1223 bool simulate_main_network_error_;
1224
1225 // Whether to intercept redirects, and if so the response to return.
1226 bool intercept_redirect_;
1227 std::string redirect_headers_;
1228 std::string redirect_data_;
1229
1230 // Other actions we can take at MaybeInterceptRedirect time
1231 bool cancel_redirect_request_;
1232
1233 // Whether to intercept final response, and if so the response to return.
1234 bool intercept_final_response_;
1235 std::string final_headers_;
1236 std::string final_data_;
1237
1238 // Other actions we can take at MaybeInterceptResponse time
1239 bool cancel_final_request_;
1240
1241 // If we did something or not
1242 bool did_intercept_main_;
1243 bool did_restart_main_;
1244 bool did_cancel_main_;
1245 bool did_cancel_then_restart_main_;
1246 bool did_simulate_error_main_;
1247 bool did_intercept_redirect_;
1248 bool did_cancel_redirect_;
1249 bool did_intercept_final_;
1250 bool did_cancel_final_;
1251
1252 // Static getters for canned response header and data strings
1253
1254 static std::string ok_data() {
1255 return URLRequestTestJob::test_data_1();
1256 }
1257
1258 static std::string ok_headers() {
1259 return URLRequestTestJob::test_headers();
1260 }
1261
1262 static std::string redirect_data() {
1263 return std::string();
1264 }
1265
1266 static std::string redirect_headers() {
1267 return URLRequestTestJob::test_redirect_headers();
1268 }
1269
1270 static std::string error_data() {
1271 return std::string("ohhh nooooo mr. bill!");
1272 }
1273
1274 static std::string error_headers() {
1275 return URLRequestTestJob::test_error_headers();
1276 }
1277};
1278
1279TEST_F(URLRequestTest, Intercept) {
1280 TestInterceptor interceptor;
1281
1282 // intercept the main request and respond with a simple response
1283 interceptor.intercept_main_request_ = true;
1284 interceptor.main_headers_ = TestInterceptor::ok_headers();
1285 interceptor.main_data_ = TestInterceptor::ok_data();
1286
1287 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191288 URLRequest req(GURL("http://test_intercept/foo"),
1289 DEFAULT_PRIORITY,
1290 &d,
1291 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441292 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1293 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1294 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1295 req.SetUserData(NULL, user_data0);
1296 req.SetUserData(&user_data1, user_data1);
1297 req.SetUserData(&user_data2, user_data2);
1298 req.set_method("GET");
1299 req.Start();
[email protected]255620da2013-08-19 13:14:291300 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441301
1302 // Make sure we can retrieve our specific user data
1303 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1304 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1305 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1306
1307 // Check the interceptor got called as expected
1308 EXPECT_TRUE(interceptor.did_intercept_main_);
1309
1310 // Check we got one good response
1311 EXPECT_TRUE(req.status().is_success());
1312 EXPECT_EQ(200, req.response_headers()->response_code());
1313 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1314 EXPECT_EQ(1, d.response_started_count());
1315 EXPECT_EQ(0, d.received_redirect_count());
1316}
1317
1318TEST_F(URLRequestTest, InterceptRedirect) {
1319 TestInterceptor interceptor;
1320
1321 // intercept the main request and respond with a redirect
1322 interceptor.intercept_main_request_ = true;
1323 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1324 interceptor.main_data_ = TestInterceptor::redirect_data();
1325
1326 // intercept that redirect and respond a final OK response
1327 interceptor.intercept_redirect_ = true;
1328 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1329 interceptor.redirect_data_ = TestInterceptor::ok_data();
1330
1331 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191332 URLRequest req(GURL("http://test_intercept/foo"),
1333 DEFAULT_PRIORITY,
1334 &d,
1335 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441336 req.set_method("GET");
1337 req.Start();
[email protected]255620da2013-08-19 13:14:291338 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441339
1340 // Check the interceptor got called as expected
1341 EXPECT_TRUE(interceptor.did_intercept_main_);
1342 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1343
1344 // Check we got one good response
1345 EXPECT_TRUE(req.status().is_success());
1346 if (req.status().is_success()) {
1347 EXPECT_EQ(200, req.response_headers()->response_code());
1348 }
1349 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1350 EXPECT_EQ(1, d.response_started_count());
1351 EXPECT_EQ(0, d.received_redirect_count());
1352}
1353
1354TEST_F(URLRequestTest, InterceptServerError) {
1355 TestInterceptor interceptor;
1356
1357 // intercept the main request to generate a server error response
1358 interceptor.intercept_main_request_ = true;
1359 interceptor.main_headers_ = TestInterceptor::error_headers();
1360 interceptor.main_data_ = TestInterceptor::error_data();
1361
1362 // intercept that error and respond with an OK response
1363 interceptor.intercept_final_response_ = true;
1364 interceptor.final_headers_ = TestInterceptor::ok_headers();
1365 interceptor.final_data_ = TestInterceptor::ok_data();
1366
1367 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191368 URLRequest req(GURL("http://test_intercept/foo"),
1369 DEFAULT_PRIORITY,
1370 &d,
1371 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441372 req.set_method("GET");
1373 req.Start();
[email protected]255620da2013-08-19 13:14:291374 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441375
1376 // Check the interceptor got called as expected
1377 EXPECT_TRUE(interceptor.did_intercept_main_);
1378 EXPECT_TRUE(interceptor.did_intercept_final_);
1379
1380 // Check we got one good response
1381 EXPECT_TRUE(req.status().is_success());
1382 EXPECT_EQ(200, req.response_headers()->response_code());
1383 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1384 EXPECT_EQ(1, d.response_started_count());
1385 EXPECT_EQ(0, d.received_redirect_count());
1386}
1387
1388TEST_F(URLRequestTest, InterceptNetworkError) {
1389 TestInterceptor interceptor;
1390
1391 // intercept the main request to simulate a network error
1392 interceptor.simulate_main_network_error_ = true;
1393
1394 // intercept that error and respond with an OK response
1395 interceptor.intercept_final_response_ = true;
1396 interceptor.final_headers_ = TestInterceptor::ok_headers();
1397 interceptor.final_data_ = TestInterceptor::ok_data();
1398
1399 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191400 URLRequest req(GURL("http://test_intercept/foo"),
1401 DEFAULT_PRIORITY,
1402 &d,
1403 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441404 req.set_method("GET");
1405 req.Start();
[email protected]255620da2013-08-19 13:14:291406 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441407
1408 // Check the interceptor got called as expected
1409 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1410 EXPECT_TRUE(interceptor.did_intercept_final_);
1411
1412 // Check we received one good response
1413 EXPECT_TRUE(req.status().is_success());
1414 EXPECT_EQ(200, req.response_headers()->response_code());
1415 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1416 EXPECT_EQ(1, d.response_started_count());
1417 EXPECT_EQ(0, d.received_redirect_count());
1418}
1419
1420TEST_F(URLRequestTest, InterceptRestartRequired) {
1421 TestInterceptor interceptor;
1422
1423 // restart the main request
1424 interceptor.restart_main_request_ = true;
1425
1426 // then intercept the new main request and respond with an OK response
1427 interceptor.intercept_main_request_ = true;
1428 interceptor.main_headers_ = TestInterceptor::ok_headers();
1429 interceptor.main_data_ = TestInterceptor::ok_data();
1430
1431 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191432 URLRequest req(GURL("http://test_intercept/foo"),
1433 DEFAULT_PRIORITY,
1434 &d,
1435 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441436 req.set_method("GET");
1437 req.Start();
[email protected]255620da2013-08-19 13:14:291438 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441439
1440 // Check the interceptor got called as expected
1441 EXPECT_TRUE(interceptor.did_restart_main_);
1442 EXPECT_TRUE(interceptor.did_intercept_main_);
1443
1444 // Check we received one good response
1445 EXPECT_TRUE(req.status().is_success());
1446 if (req.status().is_success()) {
1447 EXPECT_EQ(200, req.response_headers()->response_code());
1448 }
1449 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1450 EXPECT_EQ(1, d.response_started_count());
1451 EXPECT_EQ(0, d.received_redirect_count());
1452}
1453
1454TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1455 TestInterceptor interceptor;
1456
1457 // intercept the main request and cancel from within the restarted job
1458 interceptor.cancel_main_request_ = true;
1459
1460 // setup to intercept final response and override it with an OK response
1461 interceptor.intercept_final_response_ = true;
1462 interceptor.final_headers_ = TestInterceptor::ok_headers();
1463 interceptor.final_data_ = TestInterceptor::ok_data();
1464
1465 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191466 URLRequest req(GURL("http://test_intercept/foo"),
1467 DEFAULT_PRIORITY,
1468 &d,
1469 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441470 req.set_method("GET");
1471 req.Start();
[email protected]255620da2013-08-19 13:14:291472 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441473
1474 // Check the interceptor got called as expected
1475 EXPECT_TRUE(interceptor.did_cancel_main_);
1476 EXPECT_FALSE(interceptor.did_intercept_final_);
1477
1478 // Check we see a canceled request
1479 EXPECT_FALSE(req.status().is_success());
1480 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1481}
1482
1483TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1484 TestInterceptor interceptor;
1485
1486 // intercept the main request and respond with a redirect
1487 interceptor.intercept_main_request_ = true;
1488 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1489 interceptor.main_data_ = TestInterceptor::redirect_data();
1490
1491 // intercept the redirect and cancel from within that job
1492 interceptor.cancel_redirect_request_ = true;
1493
1494 // setup to intercept final response and override it with an OK response
1495 interceptor.intercept_final_response_ = true;
1496 interceptor.final_headers_ = TestInterceptor::ok_headers();
1497 interceptor.final_data_ = TestInterceptor::ok_data();
1498
1499 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191500 URLRequest req(GURL("http://test_intercept/foo"),
1501 DEFAULT_PRIORITY,
1502 &d,
1503 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441504 req.set_method("GET");
1505 req.Start();
[email protected]255620da2013-08-19 13:14:291506 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441507
1508 // Check the interceptor got called as expected
1509 EXPECT_TRUE(interceptor.did_intercept_main_);
1510 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1511 EXPECT_FALSE(interceptor.did_intercept_final_);
1512
1513 // Check we see a canceled request
1514 EXPECT_FALSE(req.status().is_success());
1515 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1516}
1517
1518TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1519 TestInterceptor interceptor;
1520
1521 // intercept the main request to simulate a network error
1522 interceptor.simulate_main_network_error_ = true;
1523
1524 // setup to intercept final response and cancel from within that job
1525 interceptor.cancel_final_request_ = true;
1526
1527 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191528 URLRequest req(GURL("http://test_intercept/foo"),
1529 DEFAULT_PRIORITY,
1530 &d,
1531 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441532 req.set_method("GET");
1533 req.Start();
[email protected]255620da2013-08-19 13:14:291534 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441535
1536 // Check the interceptor got called as expected
1537 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1538 EXPECT_TRUE(interceptor.did_cancel_final_);
1539
1540 // Check we see a canceled request
1541 EXPECT_FALSE(req.status().is_success());
1542 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1543}
1544
1545TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1546 TestInterceptor interceptor;
1547
1548 // intercept the main request and cancel then restart from within that job
1549 interceptor.cancel_then_restart_main_request_ = true;
1550
1551 // setup to intercept final response and override it with an OK response
1552 interceptor.intercept_final_response_ = true;
1553 interceptor.final_headers_ = TestInterceptor::ok_headers();
1554 interceptor.final_data_ = TestInterceptor::ok_data();
1555
1556 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191557 URLRequest req(GURL("http://test_intercept/foo"),
1558 DEFAULT_PRIORITY,
1559 &d,
1560 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441561 req.set_method("GET");
1562 req.Start();
[email protected]255620da2013-08-19 13:14:291563 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441564
1565 // Check the interceptor got called as expected
1566 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1567 EXPECT_FALSE(interceptor.did_intercept_final_);
1568
1569 // Check we see a canceled request
1570 EXPECT_FALSE(req.status().is_success());
1571 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1572}
1573
[email protected]2bba3252013-04-08 19:50:591574LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1575 URLRequestContext* context) {
1576 TestInterceptor interceptor;
1577 interceptor.intercept_main_request_ = true;
1578 interceptor.main_request_load_timing_info_ = job_load_timing;
1579 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191580 URLRequest req(
1581 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, context);
[email protected]2bba3252013-04-08 19:50:591582 req.Start();
[email protected]255620da2013-08-19 13:14:291583 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591584
1585 LoadTimingInfo resulting_load_timing;
1586 req.GetLoadTimingInfo(&resulting_load_timing);
1587
1588 // None of these should be modified by the URLRequest.
1589 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1590 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1591 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1592 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1593 EXPECT_EQ(job_load_timing.receive_headers_end,
1594 resulting_load_timing.receive_headers_end);
1595
1596 return resulting_load_timing;
1597}
1598
1599// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1600// reused. |connect_time_flags| is used to indicate if there should be dns
1601// or SSL times, and |used_proxy| is used for proxy times.
1602LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1603 int connect_time_flags,
1604 bool used_proxy) {
1605 LoadTimingInfo load_timing;
1606 load_timing.socket_log_id = 1;
1607
1608 if (used_proxy) {
1609 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1610 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1611 }
1612
1613 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1614 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1615 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1616 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1617 }
1618 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1619 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1620 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1621 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1622 }
1623 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1624
1625 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1626 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1627 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1628 return load_timing;
1629}
1630
1631// Same as above, but in the case of a reused socket.
1632LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1633 bool used_proxy) {
1634 LoadTimingInfo load_timing;
1635 load_timing.socket_log_id = 1;
1636 load_timing.socket_reused = true;
1637
1638 if (used_proxy) {
1639 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1640 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1641 }
1642
1643 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1644 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1645 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1646 return load_timing;
1647}
1648
1649// Basic test that the intercept + load timing tests work.
1650TEST_F(URLRequestTest, InterceptLoadTiming) {
1651 base::TimeTicks now = base::TimeTicks::Now();
1652 LoadTimingInfo job_load_timing =
1653 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1654
[email protected]2ca01e52013-10-31 22:05:191655 LoadTimingInfo load_timing_result =
1656 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591657
1658 // Nothing should have been changed by the URLRequest.
1659 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1660 load_timing_result.proxy_resolve_start);
1661 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1662 load_timing_result.proxy_resolve_end);
1663 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1664 load_timing_result.connect_timing.dns_start);
1665 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1666 load_timing_result.connect_timing.dns_end);
1667 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1668 load_timing_result.connect_timing.connect_start);
1669 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1670 load_timing_result.connect_timing.connect_end);
1671 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1672 load_timing_result.connect_timing.ssl_start);
1673 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1674 load_timing_result.connect_timing.ssl_end);
1675
1676 // Redundant sanity check.
1677 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1678}
1679
1680// Another basic test, with proxy and SSL times, but no DNS times.
1681TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1682 base::TimeTicks now = base::TimeTicks::Now();
1683 LoadTimingInfo job_load_timing =
1684 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1685
[email protected]2ca01e52013-10-31 22:05:191686 LoadTimingInfo load_timing_result =
1687 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591688
1689 // Nothing should have been changed by the URLRequest.
1690 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1691 load_timing_result.proxy_resolve_start);
1692 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1693 load_timing_result.proxy_resolve_end);
1694 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1695 load_timing_result.connect_timing.dns_start);
1696 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1697 load_timing_result.connect_timing.dns_end);
1698 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1699 load_timing_result.connect_timing.connect_start);
1700 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1701 load_timing_result.connect_timing.connect_end);
1702 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1703 load_timing_result.connect_timing.ssl_start);
1704 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1705 load_timing_result.connect_timing.ssl_end);
1706
1707 // Redundant sanity check.
1708 TestLoadTimingNotReusedWithProxy(load_timing_result,
1709 CONNECT_TIMING_HAS_SSL_TIMES);
1710}
1711
1712// Make sure that URLRequest correctly adjusts proxy times when they're before
1713// |request_start|, due to already having a connected socket. This happens in
1714// the case of reusing a SPDY session or HTTP pipeline. The connected socket is
1715// not considered reused in this test (May be a preconnect).
1716//
1717// To mix things up from the test above, assumes DNS times but no SSL times.
1718TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1719 base::TimeTicks now = base::TimeTicks::Now();
1720 LoadTimingInfo job_load_timing =
1721 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1722 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1723 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1724 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1725 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1726 job_load_timing.connect_timing.connect_start =
1727 now - base::TimeDelta::FromDays(2);
1728 job_load_timing.connect_timing.connect_end =
1729 now - base::TimeDelta::FromDays(1);
1730
[email protected]2ca01e52013-10-31 22:05:191731 LoadTimingInfo load_timing_result =
1732 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591733
1734 // Proxy times, connect times, and DNS times should all be replaced with
1735 // request_start.
1736 EXPECT_EQ(load_timing_result.request_start,
1737 load_timing_result.proxy_resolve_start);
1738 EXPECT_EQ(load_timing_result.request_start,
1739 load_timing_result.proxy_resolve_end);
1740 EXPECT_EQ(load_timing_result.request_start,
1741 load_timing_result.connect_timing.dns_start);
1742 EXPECT_EQ(load_timing_result.request_start,
1743 load_timing_result.connect_timing.dns_end);
1744 EXPECT_EQ(load_timing_result.request_start,
1745 load_timing_result.connect_timing.connect_start);
1746 EXPECT_EQ(load_timing_result.request_start,
1747 load_timing_result.connect_timing.connect_end);
1748
1749 // Other times should have been left null.
1750 TestLoadTimingNotReusedWithProxy(load_timing_result,
1751 CONNECT_TIMING_HAS_DNS_TIMES);
1752}
1753
1754// Same as above, but in the reused case.
1755TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1756 base::TimeTicks now = base::TimeTicks::Now();
1757 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1758 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1759 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1760
[email protected]2ca01e52013-10-31 22:05:191761 LoadTimingInfo load_timing_result =
1762 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591763
1764 // Proxy times and connect times should all be replaced with request_start.
1765 EXPECT_EQ(load_timing_result.request_start,
1766 load_timing_result.proxy_resolve_start);
1767 EXPECT_EQ(load_timing_result.request_start,
1768 load_timing_result.proxy_resolve_end);
1769
1770 // Other times should have been left null.
1771 TestLoadTimingReusedWithProxy(load_timing_result);
1772}
1773
1774// Make sure that URLRequest correctly adjusts connect times when they're before
1775// |request_start|, due to reusing a connected socket. The connected socket is
1776// not considered reused in this test (May be a preconnect).
1777//
1778// To mix things up, the request has SSL times, but no DNS times.
1779TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1780 base::TimeTicks now = base::TimeTicks::Now();
1781 LoadTimingInfo job_load_timing =
1782 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1783 job_load_timing.connect_timing.connect_start =
1784 now - base::TimeDelta::FromDays(1);
1785 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1786 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1787 job_load_timing.connect_timing.connect_end =
1788 now - base::TimeDelta::FromDays(4);
1789
[email protected]2ca01e52013-10-31 22:05:191790 LoadTimingInfo load_timing_result =
1791 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591792
1793 // Connect times, and SSL times should be replaced with request_start.
1794 EXPECT_EQ(load_timing_result.request_start,
1795 load_timing_result.connect_timing.connect_start);
1796 EXPECT_EQ(load_timing_result.request_start,
1797 load_timing_result.connect_timing.ssl_start);
1798 EXPECT_EQ(load_timing_result.request_start,
1799 load_timing_result.connect_timing.ssl_end);
1800 EXPECT_EQ(load_timing_result.request_start,
1801 load_timing_result.connect_timing.connect_end);
1802
1803 // Other times should have been left null.
1804 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1805}
1806
1807// Make sure that URLRequest correctly adjusts connect times when they're before
1808// |request_start|, due to reusing a connected socket in the case that there
1809// are also proxy times. The connected socket is not considered reused in this
1810// test (May be a preconnect).
1811//
1812// In this test, there are no SSL or DNS times.
1813TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1814 base::TimeTicks now = base::TimeTicks::Now();
1815 LoadTimingInfo job_load_timing =
1816 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1817 job_load_timing.connect_timing.connect_start =
1818 now - base::TimeDelta::FromDays(1);
1819 job_load_timing.connect_timing.connect_end =
1820 now - base::TimeDelta::FromDays(2);
1821
[email protected]2ca01e52013-10-31 22:05:191822 LoadTimingInfo load_timing_result =
1823 RunLoadTimingTest(job_load_timing, &default_context_);
[email protected]2bba3252013-04-08 19:50:591824
1825 // Connect times should be replaced with proxy_resolve_end.
1826 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1827 load_timing_result.connect_timing.connect_start);
1828 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1829 load_timing_result.connect_timing.connect_end);
1830
1831 // Other times should have been left null.
1832 TestLoadTimingNotReusedWithProxy(load_timing_result,
1833 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1834}
1835
[email protected]316c1e5e2012-09-12 15:17:441836// Check that two different URL requests have different identifiers.
1837TEST_F(URLRequestTest, Identifiers) {
1838 TestDelegate d;
1839 TestURLRequestContext context;
[email protected]2ca01e52013-10-31 22:05:191840 TestURLRequest req(
1841 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1842 TestURLRequest other_req(
1843 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:441844
1845 ASSERT_NE(req.identifier(), other_req.identifier());
1846}
1847
1848// Check that a failure to connect to the proxy is reported to the network
1849// delegate.
1850TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1851 MockHostResolver host_resolver;
1852 host_resolver.rules()->AddSimulatedFailure("*");
1853
[email protected]ceefd7fd2012-11-29 00:36:241854 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:441855 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1856
1857 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191858 URLRequest req(GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:441859 req.set_method("GET");
1860
1861 req.Start();
[email protected]255620da2013-08-19 13:14:291862 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441863
1864 // Check we see a failed request.
1865 EXPECT_FALSE(req.status().is_success());
1866 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1867 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1868
1869 EXPECT_EQ(1, network_delegate.error_count());
1870 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1871 EXPECT_EQ(1, network_delegate.completed_requests());
1872}
1873
1874// Make sure that net::NetworkDelegate::NotifyCompleted is called if
1875// content is empty.
1876TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1877 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191878 URLRequest req(GURL("data:,"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441879 req.Start();
[email protected]255620da2013-08-19 13:14:291880 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441881 EXPECT_EQ("", d.data_received());
1882 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1883}
1884
[email protected]5033ab82013-03-22 20:17:461885// Make sure that SetPriority actually sets the URLRequest's priority
1886// correctly, both before and after start.
1887TEST_F(URLRequestTest, SetPriorityBasic) {
1888 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191889 URLRequest req(GURL("http://test_intercept/foo"),
1890 DEFAULT_PRIORITY,
1891 &d,
1892 &default_context_);
[email protected]5033ab82013-03-22 20:17:461893 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1894
1895 req.SetPriority(LOW);
1896 EXPECT_EQ(LOW, req.priority());
1897
1898 req.Start();
1899 EXPECT_EQ(LOW, req.priority());
1900
1901 req.SetPriority(MEDIUM);
1902 EXPECT_EQ(MEDIUM, req.priority());
1903}
1904
1905// Make sure that URLRequest calls SetPriority on a job before calling
1906// Start on it.
1907TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1908 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191909 URLRequest req(GURL("http://test_intercept/foo"),
1910 DEFAULT_PRIORITY,
1911 &d,
1912 &default_context_);
[email protected]5033ab82013-03-22 20:17:461913 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1914
1915 scoped_refptr<URLRequestTestJob> job =
1916 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501917 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461918 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1919
1920 req.SetPriority(LOW);
1921
1922 req.Start();
1923 EXPECT_EQ(LOW, job->priority());
1924}
1925
1926// Make sure that URLRequest passes on its priority updates to its
1927// job.
1928TEST_F(URLRequestTest, SetJobPriority) {
1929 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191930 URLRequest req(GURL("http://test_intercept/foo"),
1931 DEFAULT_PRIORITY,
1932 &d,
1933 &default_context_);
[email protected]5033ab82013-03-22 20:17:461934
1935 scoped_refptr<URLRequestTestJob> job =
1936 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501937 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461938
1939 req.SetPriority(LOW);
1940 req.Start();
1941 EXPECT_EQ(LOW, job->priority());
1942
1943 req.SetPriority(MEDIUM);
1944 EXPECT_EQ(MEDIUM, req.priority());
1945 EXPECT_EQ(MEDIUM, job->priority());
1946}
1947
[email protected]bb1c4662013-11-14 00:00:071948// Setting the IGNORE_LIMITS load flag should be okay if the priority
1949// is MAXIMUM_PRIORITY.
1950TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1951 TestDelegate d;
1952 URLRequest req(GURL("http://test_intercept/foo"),
1953 MAXIMUM_PRIORITY,
1954 &d,
1955 &default_context_);
1956 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1957
1958 scoped_refptr<URLRequestTestJob> job =
1959 new URLRequestTestJob(&req, &default_network_delegate_);
1960 AddTestInterceptor()->set_main_intercept_job(job.get());
1961
1962 req.SetLoadFlags(LOAD_IGNORE_LIMITS);
1963 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1964
1965 req.SetPriority(MAXIMUM_PRIORITY);
1966 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1967
1968 req.Start();
1969 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1970 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1971}
1972
[email protected]ce7d0cbc2013-05-03 18:57:221973// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:441974#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:221975// A subclass of SpawnedTestServer that uses a statically-configured hostname.
1976// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:441977// http://crbug.com/114369
[email protected]cd6f2522014-01-16 18:27:351978// TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
[email protected]ce7d0cbc2013-05-03 18:57:221979class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:441980 public:
[email protected]6cdfd7f2013-02-08 20:40:151981 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:221982 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1983 ScopedCustomUrlRequestTestHttpHost::value(),
1984 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:441985 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:221986 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1987 ScopedCustomUrlRequestTestHttpHost::value(),
1988 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:441989};
1990
[email protected]f2f31b32013-01-16 23:24:091991TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:441992 LocalHttpTestServer test_server;
1993 ASSERT_TRUE(test_server.Start());
1994
1995 TestURLRequestContext context;
1996 scoped_refptr<DelayedCookieMonster> delayed_cm =
1997 new DelayedCookieMonster();
1998 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:501999 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442000
2001 // Set up a cookie.
2002 {
2003 TestNetworkDelegate network_delegate;
2004 context.set_network_delegate(&network_delegate);
2005 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192006 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2007 DEFAULT_PRIORITY,
2008 &d,
2009 &context);
[email protected]316c1e5e2012-09-12 15:17:442010 req.Start();
[email protected]255620da2013-08-19 13:14:292011 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442012 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2013 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2014 EXPECT_EQ(1, network_delegate.set_cookie_count());
2015 }
2016
2017 // Verify that the cookie is set.
2018 {
2019 TestNetworkDelegate network_delegate;
2020 context.set_network_delegate(&network_delegate);
2021 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192022 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2023 DEFAULT_PRIORITY,
2024 &d,
2025 &context);
[email protected]316c1e5e2012-09-12 15:17:442026 req.Start();
[email protected]255620da2013-08-19 13:14:292027 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442028
2029 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2030 != std::string::npos);
2031 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2032 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2033 }
2034}
2035
[email protected]f2f31b32013-01-16 23:24:092036TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442037 LocalHttpTestServer test_server;
2038 ASSERT_TRUE(test_server.Start());
2039
2040 // Set up a cookie.
2041 {
2042 TestNetworkDelegate network_delegate;
2043 default_context_.set_network_delegate(&network_delegate);
2044 TestDelegate d;
2045 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192046 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442047 &d,
2048 &default_context_);
2049 req.Start();
[email protected]255620da2013-08-19 13:14:292050 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442051 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2052 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2053 }
2054
2055 // Verify that the cookie is set.
2056 {
2057 TestNetworkDelegate network_delegate;
2058 default_context_.set_network_delegate(&network_delegate);
2059 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192060 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2061 DEFAULT_PRIORITY,
2062 &d,
2063 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442064 req.Start();
[email protected]255620da2013-08-19 13:14:292065 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442066
2067 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2068 != std::string::npos);
2069 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2070 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2071 }
2072
2073 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2074 {
2075 TestNetworkDelegate network_delegate;
2076 default_context_.set_network_delegate(&network_delegate);
2077 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192078 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2079 DEFAULT_PRIORITY,
2080 &d,
2081 &default_context_);
[email protected]bb1c4662013-11-14 00:00:072082 req.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]316c1e5e2012-09-12 15:17:442083 req.Start();
[email protected]255620da2013-08-19 13:14:292084 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442085
2086 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2087 == std::string::npos);
2088
2089 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2090 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2091 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2092 }
2093}
2094
2095TEST_F(URLRequestTest, DoNotSaveCookies) {
2096 LocalHttpTestServer test_server;
2097 ASSERT_TRUE(test_server.Start());
2098
2099 // Set up a cookie.
2100 {
2101 TestNetworkDelegate network_delegate;
2102 default_context_.set_network_delegate(&network_delegate);
2103 TestDelegate d;
2104 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192105 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442106 &d,
2107 &default_context_);
2108 req.Start();
[email protected]255620da2013-08-19 13:14:292109 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442110
2111 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2112 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2113 EXPECT_EQ(1, network_delegate.set_cookie_count());
2114 }
2115
2116 // Try to set-up another cookie and update the previous cookie.
2117 {
2118 TestNetworkDelegate network_delegate;
2119 default_context_.set_network_delegate(&network_delegate);
2120 TestDelegate d;
2121 URLRequest req(
2122 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192123 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442124 &d,
2125 &default_context_);
[email protected]bb1c4662013-11-14 00:00:072126 req.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
[email protected]316c1e5e2012-09-12 15:17:442127 req.Start();
2128
[email protected]255620da2013-08-19 13:14:292129 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442130
2131 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2132 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2133 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2134 EXPECT_EQ(0, network_delegate.set_cookie_count());
2135 }
2136
2137 // Verify the cookies weren't saved or updated.
2138 {
2139 TestNetworkDelegate network_delegate;
2140 default_context_.set_network_delegate(&network_delegate);
2141 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192142 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2143 DEFAULT_PRIORITY,
2144 &d,
2145 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442146 req.Start();
[email protected]255620da2013-08-19 13:14:292147 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442148
2149 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2150 == std::string::npos);
2151 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2152 != std::string::npos);
2153
2154 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2155 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2156 EXPECT_EQ(0, network_delegate.set_cookie_count());
2157 }
2158}
2159
2160TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2161 LocalHttpTestServer test_server;
2162 ASSERT_TRUE(test_server.Start());
2163
2164 // Set up a cookie.
2165 {
2166 TestNetworkDelegate network_delegate;
2167 default_context_.set_network_delegate(&network_delegate);
2168 TestDelegate d;
2169 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192170 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442171 &d,
2172 &default_context_);
2173 req.Start();
[email protected]255620da2013-08-19 13:14:292174 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442175
2176 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2177 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2178 }
2179
2180 // Verify that the cookie is set.
2181 {
2182 TestNetworkDelegate network_delegate;
2183 default_context_.set_network_delegate(&network_delegate);
2184 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192185 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2186 DEFAULT_PRIORITY,
2187 &d,
2188 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442189 req.Start();
[email protected]255620da2013-08-19 13:14:292190 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442191
2192 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2193 != std::string::npos);
2194
2195 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2196 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2197 }
2198
2199 // Verify that the cookie isn't sent.
2200 {
2201 TestNetworkDelegate network_delegate;
2202 default_context_.set_network_delegate(&network_delegate);
2203 TestDelegate d;
2204 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]2ca01e52013-10-31 22:05:192205 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2206 DEFAULT_PRIORITY,
2207 &d,
2208 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442209 req.Start();
[email protected]255620da2013-08-19 13:14:292210 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442211
2212 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2213 == std::string::npos);
2214
[email protected]22e045f2013-09-20 03:54:032215 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442216 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2217 }
2218}
2219
2220TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2221 LocalHttpTestServer test_server;
2222 ASSERT_TRUE(test_server.Start());
2223
2224 // Set up a cookie.
2225 {
2226 TestNetworkDelegate network_delegate;
2227 default_context_.set_network_delegate(&network_delegate);
2228 TestDelegate d;
2229 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192230 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442231 &d,
2232 &default_context_);
2233 req.Start();
[email protected]255620da2013-08-19 13:14:292234 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442235
2236 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2237 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2238 }
2239
2240 // Try to set-up another cookie and update the previous cookie.
2241 {
2242 TestNetworkDelegate network_delegate;
2243 default_context_.set_network_delegate(&network_delegate);
2244 TestDelegate d;
2245 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2246 URLRequest req(
2247 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192248 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442249 &d,
2250 &default_context_);
2251 req.Start();
2252
[email protected]255620da2013-08-19 13:14:292253 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442254
2255 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2256 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2257 }
2258
2259 // Verify the cookies weren't saved or updated.
2260 {
2261 TestNetworkDelegate network_delegate;
2262 default_context_.set_network_delegate(&network_delegate);
2263 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192264 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2265 DEFAULT_PRIORITY,
2266 &d,
2267 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442268 req.Start();
[email protected]255620da2013-08-19 13:14:292269 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442270
2271 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2272 == std::string::npos);
2273 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2274 != std::string::npos);
2275
2276 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2277 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2278 }
2279}
2280
2281TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2282 LocalHttpTestServer test_server;
2283 ASSERT_TRUE(test_server.Start());
2284
2285 // Set up an empty cookie.
2286 {
2287 TestNetworkDelegate network_delegate;
2288 default_context_.set_network_delegate(&network_delegate);
2289 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192290 URLRequest req(test_server.GetURL("set-cookie"),
2291 DEFAULT_PRIORITY,
2292 &d,
2293 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442294 req.Start();
[email protected]255620da2013-08-19 13:14:292295 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442296
2297 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2298 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2299 EXPECT_EQ(0, network_delegate.set_cookie_count());
2300 }
2301}
2302
2303TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2304 LocalHttpTestServer test_server;
2305 ASSERT_TRUE(test_server.Start());
2306
2307 // Set up a cookie.
2308 {
2309 TestNetworkDelegate network_delegate;
2310 default_context_.set_network_delegate(&network_delegate);
2311 TestDelegate d;
2312 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192313 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442314 &d,
2315 &default_context_);
2316 req.Start();
[email protected]255620da2013-08-19 13:14:292317 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442318
2319 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2320 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2321 }
2322
2323 // Verify that the cookie is set.
2324 {
2325 TestNetworkDelegate network_delegate;
2326 default_context_.set_network_delegate(&network_delegate);
2327 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192328 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2329 DEFAULT_PRIORITY,
2330 &d,
2331 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442332 req.Start();
[email protected]255620da2013-08-19 13:14:292333 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442334
2335 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2336 != std::string::npos);
2337
2338 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2339 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2340 }
2341
2342 // Verify that the cookie isn't sent.
2343 {
2344 TestNetworkDelegate network_delegate;
2345 default_context_.set_network_delegate(&network_delegate);
2346 TestDelegate d;
2347 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]2ca01e52013-10-31 22:05:192348 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2349 DEFAULT_PRIORITY,
2350 &d,
2351 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442352 req.Start();
[email protected]255620da2013-08-19 13:14:292353 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442354
2355 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2356 == std::string::npos);
2357
[email protected]22e045f2013-09-20 03:54:032358 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442359 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2360 }
2361}
2362
2363TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2364 LocalHttpTestServer test_server;
2365 ASSERT_TRUE(test_server.Start());
2366
2367 // Set up a cookie.
2368 {
2369 TestNetworkDelegate network_delegate;
2370 default_context_.set_network_delegate(&network_delegate);
2371 TestDelegate d;
2372 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192373 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442374 &d,
2375 &default_context_);
2376 req.Start();
[email protected]255620da2013-08-19 13:14:292377 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442378
2379 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2380 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2381 }
2382
2383 // Try to set-up another cookie and update the previous cookie.
2384 {
2385 TestNetworkDelegate network_delegate;
2386 default_context_.set_network_delegate(&network_delegate);
2387 TestDelegate d;
2388 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2389 URLRequest req(
2390 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192391 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442392 &d,
2393 &default_context_);
2394 req.Start();
2395
[email protected]255620da2013-08-19 13:14:292396 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442397
2398 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2399 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2400 }
2401
2402 // Verify the cookies weren't saved or updated.
2403 {
2404 TestNetworkDelegate network_delegate;
2405 default_context_.set_network_delegate(&network_delegate);
2406 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192407 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2408 DEFAULT_PRIORITY,
2409 &d,
2410 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442411 req.Start();
[email protected]255620da2013-08-19 13:14:292412 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442413
2414 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2415 == std::string::npos);
2416 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2417 != std::string::npos);
2418
2419 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2420 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2421 }
2422}
2423
[email protected]5095cd72012-11-01 10:29:162424// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2425// value for the |fixed_date| argument given to the constructor.
2426class FixedDateNetworkDelegate : public TestNetworkDelegate {
2427 public:
2428 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2429 : fixed_date_(fixed_date) {}
2430 virtual ~FixedDateNetworkDelegate() {}
2431
2432 // net::NetworkDelegate implementation
2433 virtual int OnHeadersReceived(
2434 net::URLRequest* request,
2435 const net::CompletionCallback& callback,
2436 const net::HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:162437 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2438 GURL* allowed_unsafe_redirect_url) OVERRIDE;
[email protected]5095cd72012-11-01 10:29:162439
2440 private:
2441 std::string fixed_date_;
2442
2443 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2444};
2445
2446int FixedDateNetworkDelegate::OnHeadersReceived(
2447 net::URLRequest* request,
2448 const net::CompletionCallback& callback,
2449 const net::HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:162450 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2451 GURL* allowed_unsafe_redirect_url) {
[email protected]5095cd72012-11-01 10:29:162452 net::HttpResponseHeaders* new_response_headers =
2453 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2454
2455 new_response_headers->RemoveHeader("Date");
2456 new_response_headers->AddHeader("Date: " + fixed_date_);
2457
2458 *override_response_headers = new_response_headers;
2459 return TestNetworkDelegate::OnHeadersReceived(request,
2460 callback,
2461 original_response_headers,
[email protected]5f714132014-03-26 10:41:162462 override_response_headers,
2463 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162464}
2465
2466// Test that cookie expiration times are adjusted for server/client clock
2467// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2468// headers by defaulting to GMT. (crbug.com/135131)
2469TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2470 LocalHttpTestServer test_server;
2471 ASSERT_TRUE(test_server.Start());
2472
2473 // Set up an expired cookie.
2474 {
2475 TestNetworkDelegate network_delegate;
2476 default_context_.set_network_delegate(&network_delegate);
2477 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192478 URLRequest req(
2479 test_server.GetURL(
2480 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2481 DEFAULT_PRIORITY,
[email protected]5095cd72012-11-01 10:29:162482 &d,
2483 &default_context_);
2484 req.Start();
[email protected]255620da2013-08-19 13:14:292485 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162486 }
2487 // Verify that the cookie is not set.
2488 {
2489 TestNetworkDelegate network_delegate;
2490 default_context_.set_network_delegate(&network_delegate);
2491 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192492 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2493 DEFAULT_PRIORITY,
2494 &d,
2495 &default_context_);
[email protected]5095cd72012-11-01 10:29:162496 req.Start();
[email protected]255620da2013-08-19 13:14:292497 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162498
2499 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2500 }
2501 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2502 {
2503 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2504 default_context_.set_network_delegate(&network_delegate);
2505 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192506 URLRequest req(
2507 test_server.GetURL(
2508 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2509 DEFAULT_PRIORITY,
[email protected]5095cd72012-11-01 10:29:162510 &d,
2511 &default_context_);
2512 req.Start();
[email protected]255620da2013-08-19 13:14:292513 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162514 }
2515 // Verify that the cookie is set.
2516 {
2517 TestNetworkDelegate network_delegate;
2518 default_context_.set_network_delegate(&network_delegate);
2519 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192520 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2521 DEFAULT_PRIORITY,
2522 &d,
2523 &default_context_);
[email protected]5095cd72012-11-01 10:29:162524 req.Start();
[email protected]255620da2013-08-19 13:14:292525 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162526
2527 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2528 }
2529}
2530
2531
[email protected]316c1e5e2012-09-12 15:17:442532// Check that it is impossible to change the referrer in the extra headers of
2533// an URLRequest.
2534TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2535 LocalHttpTestServer test_server;
2536 ASSERT_TRUE(test_server.Start());
2537
2538 // If extra headers contain referer and the request contains a referer,
2539 // only the latter shall be respected.
2540 {
2541 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192542 URLRequest req(test_server.GetURL("echoheader?Referer"),
2543 DEFAULT_PRIORITY,
2544 &d,
2545 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:132546 req.SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442547
2548 HttpRequestHeaders headers;
2549 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2550 req.SetExtraRequestHeaders(headers);
2551
2552 req.Start();
[email protected]255620da2013-08-19 13:14:292553 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442554
2555 EXPECT_EQ("http://foo.com/", d.data_received());
2556 }
2557
2558 // If extra headers contain a referer but the request does not, no referer
2559 // shall be sent in the header.
2560 {
2561 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192562 URLRequest req(test_server.GetURL("echoheader?Referer"),
2563 DEFAULT_PRIORITY,
2564 &d,
2565 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442566
2567 HttpRequestHeaders headers;
2568 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2569 req.SetExtraRequestHeaders(headers);
[email protected]bb1c4662013-11-14 00:00:072570 req.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442571
2572 req.Start();
[email protected]255620da2013-08-19 13:14:292573 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442574
2575 EXPECT_EQ("None", d.data_received());
2576 }
2577}
2578
[email protected]b89290212009-08-14 22:37:352579class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112580 public:
2581 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152582 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112583 "net/data/url_request_unittest"))) {
2584 }
2585
[email protected]b89290212009-08-14 22:37:352586 protected:
[email protected]21184962011-10-26 00:50:302587 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2588 // |request_method| is the method to use for the initial request.
2589 // |redirect_method| is the method that is expected to be used for the second
2590 // request, after redirection.
2591 // If |include_data| is true, data is uploaded with the request. The
2592 // response body is expected to match it exactly, if and only if
2593 // |request_method| == |redirect_method|.
2594 void HTTPRedirectMethodTest(const GURL& redirect_url,
2595 const std::string& request_method,
2596 const std::string& redirect_method,
2597 bool include_data) {
2598 static const char kData[] = "hello world";
2599 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192600 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]21184962011-10-26 00:50:302601 req.set_method(request_method);
2602 if (include_data) {
[email protected]f288ef02012-12-15 20:28:282603 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]21184962011-10-26 00:50:302604 HttpRequestHeaders headers;
2605 headers.SetHeader(HttpRequestHeaders::kContentLength,
2606 base::UintToString(arraysize(kData) - 1));
2607 req.SetExtraRequestHeaders(headers);
2608 }
2609 req.Start();
[email protected]255620da2013-08-19 13:14:292610 base::RunLoop().Run();
[email protected]21184962011-10-26 00:50:302611 EXPECT_EQ(redirect_method, req.method());
2612 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2613 EXPECT_EQ(OK, req.status().error());
2614 if (include_data) {
2615 if (request_method == redirect_method) {
2616 EXPECT_EQ(kData, d.data_received());
2617 } else {
2618 EXPECT_NE(kData, d.data_received());
2619 }
2620 }
2621 if (HasFailure())
2622 LOG(WARNING) << "Request method was: " << request_method;
2623 }
2624
[email protected]762d2db2010-01-11 19:03:012625 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012626 const int kMsgSize = 20000; // multiple of 10
2627 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482628 char* uploadBytes = new char[kMsgSize+1];
2629 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012630 char marker = 'a';
2631 for (int idx = 0; idx < kMsgSize/10; idx++) {
2632 memcpy(ptr, "----------", 10);
2633 ptr += 10;
2634 if (idx % 100 == 0) {
2635 ptr--;
2636 *ptr++ = marker;
2637 if (++marker > 'z')
2638 marker = 'a';
2639 }
2640 }
2641 uploadBytes[kMsgSize] = '\0';
2642
[email protected]762d2db2010-01-11 19:03:012643 for (int i = 0; i < kIterations; ++i) {
2644 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192645 URLRequest r(
2646 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]762d2db2010-01-11 19:03:012647 r.set_method(method.c_str());
2648
[email protected]f288ef02012-12-15 20:28:282649 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
[email protected]762d2db2010-01-11 19:03:012650
2651 r.Start();
2652 EXPECT_TRUE(r.is_pending());
2653
[email protected]255620da2013-08-19 13:14:292654 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012655
[email protected]329b68b2012-11-14 17:54:272656 ASSERT_EQ(1, d.response_started_count())
2657 << "request failed: " << r.status().status()
2658 << ", os error: " << r.status().error();
[email protected]762d2db2010-01-11 19:03:012659
2660 EXPECT_FALSE(d.received_data_before_response());
2661 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012662 }
2663 delete[] uploadBytes;
2664 }
2665
[email protected]ef2bf422012-05-11 03:27:092666 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222667 r->AppendChunkToUpload("a", 1, false);
2668 r->AppendChunkToUpload("bcd", 3, false);
2669 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2670 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2671 r->AppendChunkToUpload("0", 1, false);
2672 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112673 }
2674
[email protected]ef2bf422012-05-11 03:27:092675 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112676 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272677 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112678 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2679
[email protected]329b68b2012-11-14 17:54:272680 ASSERT_EQ(1, d->response_started_count())
2681 << "request failed: " << r->status().status()
2682 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112683
2684 EXPECT_FALSE(d->received_data_before_response());
2685
[email protected]329b68b2012-11-14 17:54:272686 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2687 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112688 }
2689
[email protected]ede03212012-09-07 12:52:262690 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342691 TestDelegate d;
2692 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2693 base::IntToString(num_cookies)),
[email protected]2ca01e52013-10-31 22:05:192694 DEFAULT_PRIORITY,
2695 &d,
2696 &default_context_);
[email protected]263163f2012-06-14 22:40:342697
2698 r.Start();
2699 EXPECT_TRUE(r.is_pending());
2700
[email protected]255620da2013-08-19 13:14:292701 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342702
2703 bool is_success = r.status().is_success();
2704
[email protected]ede03212012-09-07 12:52:262705 if (!is_success) {
[email protected]cd6f2522014-01-16 18:27:352706 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:342707 // The test server appears to be unable to handle subsequent requests
2708 // after this error is triggered. Force it to restart.
2709 EXPECT_TRUE(test_server_.Stop());
2710 EXPECT_TRUE(test_server_.Start());
2711 }
2712
2713 return is_success;
2714 }
2715
[email protected]1700c6a2012-02-22 18:07:072716 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352717};
2718
[email protected]95409e12010-08-17 20:07:112719// In this unit test, we're using the HTTPTestServer as a proxy server and
2720// issuing a CONNECT request with the magic host name "www.redirect.com".
2721// The HTTPTestServer will return a 302 response, which we should not
2722// follow.
[email protected]f2f31b32013-01-16 23:24:092723TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112724 ASSERT_TRUE(test_server_.Start());
2725
[email protected]ceefd7fd2012-11-29 00:36:242726 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042727 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192728 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502729
[email protected]d1ec59082009-02-11 02:48:152730 TestDelegate d;
2731 {
[email protected]2ca01e52013-10-31 22:05:192732 URLRequest r(
2733 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]d1ec59082009-02-11 02:48:152734 r.Start();
2735 EXPECT_TRUE(r.is_pending());
2736
[email protected]255620da2013-08-19 13:14:292737 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:152738
[email protected]7461a402011-03-24 23:19:512739 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052740 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:082741 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152742 // We should not have followed the redirect.
2743 EXPECT_EQ(0, d.received_redirect_count());
2744 }
2745}
2746
[email protected]8202d0c2011-02-23 08:31:142747// This is the same as the previous test, but checks that the network delegate
2748// registers the error.
[email protected]c044616e2013-02-20 02:01:262749TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142750 ASSERT_TRUE(test_server_.Start());
2751
[email protected]ceefd7fd2012-11-29 00:36:242752 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042753 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192754 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502755
[email protected]8202d0c2011-02-23 08:31:142756 TestDelegate d;
2757 {
[email protected]2ca01e52013-10-31 22:05:192758 URLRequest r(
2759 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]8202d0c2011-02-23 08:31:142760 r.Start();
2761 EXPECT_TRUE(r.is_pending());
2762
[email protected]255620da2013-08-19 13:14:292763 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:142764
[email protected]7461a402011-03-24 23:19:512765 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052766 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]8202d0c2011-02-23 08:31:142767 EXPECT_EQ(1, d.response_started_count());
2768 // We should not have followed the redirect.
2769 EXPECT_EQ(0, d.received_redirect_count());
2770
2771 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052772 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142773 }
2774}
2775
[email protected]dc5a5cf2012-09-26 02:49:302776// Tests that we can block and asynchronously return OK in various stages.
2777TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2778 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2779 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2780 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2781 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2782 };
2783 static const size_t blocking_stages_length = arraysize(blocking_stages);
2784
2785 ASSERT_TRUE(test_server_.Start());
2786
2787 TestDelegate d;
2788 BlockingNetworkDelegate network_delegate(
2789 BlockingNetworkDelegate::USER_CALLBACK);
2790 network_delegate.set_block_on(
2791 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2792 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2793 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2794
2795 TestURLRequestContext context(true);
2796 context.set_network_delegate(&network_delegate);
2797 context.Init();
2798
2799 {
[email protected]2ca01e52013-10-31 22:05:192800 URLRequest r(
2801 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, &context);
[email protected]dc5a5cf2012-09-26 02:49:302802
2803 r.Start();
2804 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:292805 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302806 EXPECT_EQ(blocking_stages[i],
2807 network_delegate.stage_blocked_for_callback());
2808 network_delegate.DoCallback(OK);
2809 }
[email protected]255620da2013-08-19 13:14:292810 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302811 EXPECT_EQ(200, r.GetResponseCode());
2812 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2813 EXPECT_EQ(1, network_delegate.created_requests());
2814 EXPECT_EQ(0, network_delegate.destroyed_requests());
2815 }
2816 EXPECT_EQ(1, network_delegate.destroyed_requests());
2817}
2818
[email protected]4c76d7c2011-04-15 19:14:122819// Tests that the network delegate can block and cancel a request.
2820TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2821 ASSERT_TRUE(test_server_.Start());
2822
2823 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302824 BlockingNetworkDelegate network_delegate(
2825 BlockingNetworkDelegate::AUTO_CALLBACK);
2826 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2827 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:122828
[email protected]d5a4dd62012-05-23 01:41:042829 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192830 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502831
[email protected]4c76d7c2011-04-15 19:14:122832 {
[email protected]2ca01e52013-10-31 22:05:192833 URLRequest r(
2834 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122835
2836 r.Start();
[email protected]255620da2013-08-19 13:14:292837 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122838
2839 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052840 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122841 EXPECT_EQ(1, network_delegate.created_requests());
2842 EXPECT_EQ(0, network_delegate.destroyed_requests());
2843 }
2844 EXPECT_EQ(1, network_delegate.destroyed_requests());
2845}
2846
[email protected]b4438d32012-09-27 06:15:302847// Helper function for NetworkDelegateCancelRequestAsynchronously and
2848// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2849// delegate operating in |block_mode| and a request for |url|. It blocks the
2850// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2851void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2852 BlockingNetworkDelegate::Stage stage,
2853 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:362854 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:302855 BlockingNetworkDelegate network_delegate(block_mode);
2856 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2857 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:362858
[email protected]b4438d32012-09-27 06:15:302859 TestURLRequestContext context(true);
2860 context.set_network_delegate(&network_delegate);
2861 context.Init();
[email protected]3cd384c602011-08-31 16:12:362862
2863 {
[email protected]2ca01e52013-10-31 22:05:192864 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]3cd384c602011-08-31 16:12:362865
2866 r.Start();
[email protected]255620da2013-08-19 13:14:292867 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:362868
2869 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]b4438d32012-09-27 06:15:302870 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
[email protected]3cd384c602011-08-31 16:12:362871 EXPECT_EQ(1, network_delegate.created_requests());
2872 EXPECT_EQ(0, network_delegate.destroyed_requests());
2873 }
2874 EXPECT_EQ(1, network_delegate.destroyed_requests());
2875}
2876
[email protected]b4438d32012-09-27 06:15:302877// The following 3 tests check that the network delegate can cancel a request
2878// synchronously in various stages of the request.
2879TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2880 ASSERT_TRUE(test_server_.Start());
2881 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2882 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452883 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302884}
2885
2886TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2887 ASSERT_TRUE(test_server_.Start());
2888 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2889 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452890 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302891}
2892
2893TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2894 ASSERT_TRUE(test_server_.Start());
2895 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2896 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452897 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302898}
2899
2900// The following 3 tests check that the network delegate can cancel a request
2901// asynchronously in various stages of the request.
2902TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2903 ASSERT_TRUE(test_server_.Start());
2904 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2905 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452906 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302907}
2908
2909TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2910 ASSERT_TRUE(test_server_.Start());
2911 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2912 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452913 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302914}
2915
2916TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2917 ASSERT_TRUE(test_server_.Start());
2918 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2919 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452920 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302921}
2922
[email protected]4c76d7c2011-04-15 19:14:122923// Tests that the network delegate can block and redirect a request to a new
2924// URL.
2925TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2926 ASSERT_TRUE(test_server_.Start());
2927
2928 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302929 BlockingNetworkDelegate network_delegate(
2930 BlockingNetworkDelegate::AUTO_CALLBACK);
2931 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:122932 GURL redirect_url(test_server_.GetURL("simple.html"));
2933 network_delegate.set_redirect_url(redirect_url);
2934
[email protected]d5a4dd62012-05-23 01:41:042935 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192936 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502937
[email protected]4c76d7c2011-04-15 19:14:122938 {
[email protected]8f1ac082011-04-19 21:14:132939 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:192940 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122941
2942 r.Start();
[email protected]255620da2013-08-19 13:14:292943 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122944
2945 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052946 EXPECT_EQ(0, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122947 EXPECT_EQ(redirect_url, r.url());
[email protected]8f1ac082011-04-19 21:14:132948 EXPECT_EQ(original_url, r.original_url());
2949 EXPECT_EQ(2U, r.url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:122950 EXPECT_EQ(1, network_delegate.created_requests());
2951 EXPECT_EQ(0, network_delegate.destroyed_requests());
2952 }
2953 EXPECT_EQ(1, network_delegate.destroyed_requests());
2954}
2955
[email protected]b813ed72012-04-05 08:21:362956// Tests that the network delegate can block and redirect a request to a new
2957// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2958TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2959 ASSERT_TRUE(test_server_.Start());
2960
2961 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302962 BlockingNetworkDelegate network_delegate(
2963 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:362964 GURL redirect_url(test_server_.GetURL("simple.html"));
2965 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:362966
[email protected]d5a4dd62012-05-23 01:41:042967 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192968 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:362969
2970 {
2971 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:192972 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]b813ed72012-04-05 08:21:362973
2974 r.Start();
[email protected]255620da2013-08-19 13:14:292975 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:362976
2977 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2978 EXPECT_EQ(0, r.status().error());
2979 EXPECT_EQ(redirect_url, r.url());
2980 EXPECT_EQ(original_url, r.original_url());
2981 EXPECT_EQ(2U, r.url_chain().size());
2982 EXPECT_EQ(1, network_delegate.created_requests());
2983 EXPECT_EQ(0, network_delegate.destroyed_requests());
2984 }
2985 EXPECT_EQ(1, network_delegate.destroyed_requests());
2986}
2987
[email protected]3c5ca8c2011-09-29 01:14:512988// Tests that redirects caused by the network delegate preserve POST data.
2989TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2990 ASSERT_TRUE(test_server_.Start());
2991
2992 const char kData[] = "hello world";
2993
2994 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302995 BlockingNetworkDelegate network_delegate(
2996 BlockingNetworkDelegate::AUTO_CALLBACK);
2997 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:512998 GURL redirect_url(test_server_.GetURL("echo"));
2999 network_delegate.set_redirect_url(redirect_url);
3000
[email protected]ef2bf422012-05-11 03:27:093001 TestURLRequestContext context(true);
3002 context.set_network_delegate(&network_delegate);
3003 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513004
3005 {
3006 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:193007 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]3c5ca8c2011-09-29 01:14:513008 r.set_method("POST");
[email protected]f288ef02012-12-15 20:28:283009 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]3c5ca8c2011-09-29 01:14:513010 HttpRequestHeaders headers;
3011 headers.SetHeader(HttpRequestHeaders::kContentLength,
3012 base::UintToString(arraysize(kData) - 1));
3013 r.SetExtraRequestHeaders(headers);
[email protected]3c5ca8c2011-09-29 01:14:513014 r.Start();
[email protected]255620da2013-08-19 13:14:293015 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513016
3017 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3018 EXPECT_EQ(0, r.status().error());
3019 EXPECT_EQ(redirect_url, r.url());
3020 EXPECT_EQ(original_url, r.original_url());
3021 EXPECT_EQ(2U, r.url_chain().size());
3022 EXPECT_EQ(1, network_delegate.created_requests());
3023 EXPECT_EQ(0, network_delegate.destroyed_requests());
3024 EXPECT_EQ("POST", r.method());
3025 EXPECT_EQ(kData, d.data_received());
3026 }
3027 EXPECT_EQ(1, network_delegate.destroyed_requests());
3028}
3029
[email protected]5f714132014-03-26 10:41:163030// Tests that the network delegate can block and redirect a request to a new
3031// URL during OnHeadersReceived.
3032TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3033 ASSERT_TRUE(test_server_.Start());
3034
3035 TestDelegate d;
3036 BlockingNetworkDelegate network_delegate(
3037 BlockingNetworkDelegate::AUTO_CALLBACK);
3038 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3039 GURL redirect_url(test_server_.GetURL("simple.html"));
3040 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3041
3042 TestURLRequestContextWithProxy context(
3043 test_server_.host_port_pair().ToString(), &network_delegate);
3044
3045 {
3046 GURL original_url(test_server_.GetURL("empty.html"));
3047 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
3048
3049 r.Start();
3050 base::RunLoop().Run();
3051
3052 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3053 EXPECT_EQ(net::OK, r.status().error());
3054 EXPECT_EQ(redirect_url, r.url());
3055 EXPECT_EQ(original_url, r.original_url());
3056 EXPECT_EQ(2U, r.url_chain().size());
3057 EXPECT_EQ(2, network_delegate.created_requests());
3058 EXPECT_EQ(0, network_delegate.destroyed_requests());
3059 }
3060 EXPECT_EQ(1, network_delegate.destroyed_requests());
3061}
3062
[email protected]c2911d72011-10-03 22:16:363063// Tests that the network delegate can synchronously complete OnAuthRequired
3064// by taking no action. This indicates that the NetworkDelegate does not want to
3065// handle the challenge, and is passing the buck along to the
3066// URLRequest::Delegate.
3067TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3068 ASSERT_TRUE(test_server_.Start());
3069
3070 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303071 BlockingNetworkDelegate network_delegate(
3072 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363073
[email protected]ef2bf422012-05-11 03:27:093074 TestURLRequestContext context(true);
3075 context.set_network_delegate(&network_delegate);
3076 context.Init();
[email protected]c2911d72011-10-03 22:16:363077
[email protected]f3cf9802011-10-28 18:44:583078 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363079
3080 {
3081 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193082 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363083 r.Start();
[email protected]79e1fd62013-06-20 06:50:043084
[email protected]255620da2013-08-19 13:14:293085 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043086
3087 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3088 EXPECT_EQ(0, r.status().error());
3089 EXPECT_EQ(200, r.GetResponseCode());
3090 EXPECT_TRUE(d.auth_required_called());
3091 EXPECT_EQ(1, network_delegate.created_requests());
3092 EXPECT_EQ(0, network_delegate.destroyed_requests());
3093 }
3094 EXPECT_EQ(1, network_delegate.destroyed_requests());
3095}
3096
3097TEST_F(URLRequestTestHTTP,
3098 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3099 ASSERT_TRUE(test_server_.Start());
3100
3101 TestDelegate d;
3102 BlockingNetworkDelegate network_delegate(
3103 BlockingNetworkDelegate::SYNCHRONOUS);
3104
3105 TestURLRequestContext context(true);
3106 context.set_network_delegate(&network_delegate);
3107 context.Init();
3108
3109 d.set_credentials(AuthCredentials(kUser, kSecret));
3110
3111 {
3112 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193113 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]79e1fd62013-06-20 06:50:043114 r.Start();
3115
3116 {
3117 HttpRequestHeaders headers;
3118 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3119 EXPECT_FALSE(headers.HasHeader("Authorization"));
3120 }
3121
[email protected]255620da2013-08-19 13:14:293122 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363123
3124 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3125 EXPECT_EQ(0, r.status().error());
3126 EXPECT_EQ(200, r.GetResponseCode());
3127 EXPECT_TRUE(d.auth_required_called());
3128 EXPECT_EQ(1, network_delegate.created_requests());
3129 EXPECT_EQ(0, network_delegate.destroyed_requests());
3130 }
3131 EXPECT_EQ(1, network_delegate.destroyed_requests());
3132}
3133
3134// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403135// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363136TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3137 ASSERT_TRUE(test_server_.Start());
3138
3139 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303140 BlockingNetworkDelegate network_delegate(
3141 BlockingNetworkDelegate::SYNCHRONOUS);
3142 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363143 network_delegate.set_auth_retval(
3144 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3145
[email protected]f3cf9802011-10-28 18:44:583146 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363147
[email protected]ef2bf422012-05-11 03:27:093148 TestURLRequestContext context(true);
3149 context.set_network_delegate(&network_delegate);
3150 context.Init();
[email protected]c2911d72011-10-03 22:16:363151
3152 {
3153 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193154 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363155 r.Start();
[email protected]255620da2013-08-19 13:14:293156 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363157
3158 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3159 EXPECT_EQ(0, r.status().error());
3160 EXPECT_EQ(200, r.GetResponseCode());
3161 EXPECT_FALSE(d.auth_required_called());
3162 EXPECT_EQ(1, network_delegate.created_requests());
3163 EXPECT_EQ(0, network_delegate.destroyed_requests());
3164 }
3165 EXPECT_EQ(1, network_delegate.destroyed_requests());
3166}
3167
[email protected]79e1fd62013-06-20 06:50:043168// Same as above, but also tests that GetFullRequestHeaders returns the proper
3169// headers (for the first or second request) when called at the proper times.
3170TEST_F(URLRequestTestHTTP,
3171 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3172 ASSERT_TRUE(test_server_.Start());
3173
3174 TestDelegate d;
3175 BlockingNetworkDelegate network_delegate(
3176 BlockingNetworkDelegate::SYNCHRONOUS);
3177 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3178 network_delegate.set_auth_retval(
3179 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3180
3181 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3182
3183 TestURLRequestContext context(true);
3184 context.set_network_delegate(&network_delegate);
3185 context.Init();
3186
3187 {
3188 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193189 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]79e1fd62013-06-20 06:50:043190 r.Start();
[email protected]255620da2013-08-19 13:14:293191 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043192
3193 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3194 EXPECT_EQ(0, r.status().error());
3195 EXPECT_EQ(200, r.GetResponseCode());
3196 EXPECT_FALSE(d.auth_required_called());
3197 EXPECT_EQ(1, network_delegate.created_requests());
3198 EXPECT_EQ(0, network_delegate.destroyed_requests());
3199
3200 {
3201 HttpRequestHeaders headers;
3202 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3203 EXPECT_TRUE(headers.HasHeader("Authorization"));
3204 }
3205 }
3206 EXPECT_EQ(1, network_delegate.destroyed_requests());
3207}
3208
[email protected]c2911d72011-10-03 22:16:363209// Tests that the network delegate can synchronously complete OnAuthRequired
3210// by cancelling authentication.
3211TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3212 ASSERT_TRUE(test_server_.Start());
3213
3214 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303215 BlockingNetworkDelegate network_delegate(
3216 BlockingNetworkDelegate::SYNCHRONOUS);
3217 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363218 network_delegate.set_auth_retval(
3219 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3220
[email protected]ef2bf422012-05-11 03:27:093221 TestURLRequestContext context(true);
3222 context.set_network_delegate(&network_delegate);
3223 context.Init();
[email protected]c2911d72011-10-03 22:16:363224
3225 {
3226 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193227 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363228 r.Start();
[email protected]255620da2013-08-19 13:14:293229 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363230
3231 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3232 EXPECT_EQ(OK, r.status().error());
3233 EXPECT_EQ(401, r.GetResponseCode());
3234 EXPECT_FALSE(d.auth_required_called());
3235 EXPECT_EQ(1, network_delegate.created_requests());
3236 EXPECT_EQ(0, network_delegate.destroyed_requests());
3237 }
3238 EXPECT_EQ(1, network_delegate.destroyed_requests());
3239}
3240
3241// Tests that the network delegate can asynchronously complete OnAuthRequired
3242// by taking no action. This indicates that the NetworkDelegate does not want
3243// to handle the challenge, and is passing the buck along to the
3244// URLRequest::Delegate.
3245TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3246 ASSERT_TRUE(test_server_.Start());
3247
3248 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303249 BlockingNetworkDelegate network_delegate(
3250 BlockingNetworkDelegate::AUTO_CALLBACK);
3251 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363252
[email protected]ef2bf422012-05-11 03:27:093253 TestURLRequestContext context(true);
3254 context.set_network_delegate(&network_delegate);
3255 context.Init();
[email protected]c2911d72011-10-03 22:16:363256
[email protected]f3cf9802011-10-28 18:44:583257 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363258
3259 {
3260 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193261 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363262 r.Start();
[email protected]255620da2013-08-19 13:14:293263 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363264
3265 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3266 EXPECT_EQ(0, r.status().error());
3267 EXPECT_EQ(200, r.GetResponseCode());
3268 EXPECT_TRUE(d.auth_required_called());
3269 EXPECT_EQ(1, network_delegate.created_requests());
3270 EXPECT_EQ(0, network_delegate.destroyed_requests());
3271 }
3272 EXPECT_EQ(1, network_delegate.destroyed_requests());
3273}
3274
3275// Tests that the network delegate can asynchronously complete OnAuthRequired
3276// by setting credentials.
3277TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3278 ASSERT_TRUE(test_server_.Start());
3279
3280 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303281 BlockingNetworkDelegate network_delegate(
3282 BlockingNetworkDelegate::AUTO_CALLBACK);
3283 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363284 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363285 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3286
[email protected]f3cf9802011-10-28 18:44:583287 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363288 network_delegate.set_auth_credentials(auth_credentials);
3289
[email protected]ef2bf422012-05-11 03:27:093290 TestURLRequestContext context(true);
3291 context.set_network_delegate(&network_delegate);
3292 context.Init();
[email protected]c2911d72011-10-03 22:16:363293
3294 {
3295 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193296 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363297 r.Start();
[email protected]255620da2013-08-19 13:14:293298 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363299
3300 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3301 EXPECT_EQ(0, r.status().error());
3302
3303 EXPECT_EQ(200, r.GetResponseCode());
3304 EXPECT_FALSE(d.auth_required_called());
3305 EXPECT_EQ(1, network_delegate.created_requests());
3306 EXPECT_EQ(0, network_delegate.destroyed_requests());
3307 }
3308 EXPECT_EQ(1, network_delegate.destroyed_requests());
3309}
3310
3311// Tests that the network delegate can asynchronously complete OnAuthRequired
3312// by cancelling authentication.
3313TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3314 ASSERT_TRUE(test_server_.Start());
3315
3316 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303317 BlockingNetworkDelegate network_delegate(
3318 BlockingNetworkDelegate::AUTO_CALLBACK);
3319 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363320 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363321 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3322
[email protected]ef2bf422012-05-11 03:27:093323 TestURLRequestContext context(true);
3324 context.set_network_delegate(&network_delegate);
3325 context.Init();
[email protected]c2911d72011-10-03 22:16:363326
3327 {
3328 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193329 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363330 r.Start();
[email protected]255620da2013-08-19 13:14:293331 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363332
3333 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3334 EXPECT_EQ(OK, r.status().error());
3335 EXPECT_EQ(401, r.GetResponseCode());
3336 EXPECT_FALSE(d.auth_required_called());
3337 EXPECT_EQ(1, network_delegate.created_requests());
3338 EXPECT_EQ(0, network_delegate.destroyed_requests());
3339 }
3340 EXPECT_EQ(1, network_delegate.destroyed_requests());
3341}
3342
[email protected]9045b8822012-01-13 20:35:353343// Tests that we can handle when a network request was canceled while we were
3344// waiting for the network delegate.
3345// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3346TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3347 ASSERT_TRUE(test_server_.Start());
3348
3349 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303350 BlockingNetworkDelegate network_delegate(
3351 BlockingNetworkDelegate::USER_CALLBACK);
3352 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353353
[email protected]ef2bf422012-05-11 03:27:093354 TestURLRequestContext context(true);
3355 context.set_network_delegate(&network_delegate);
3356 context.Init();
[email protected]9045b8822012-01-13 20:35:353357
3358 {
[email protected]2ca01e52013-10-31 22:05:193359 URLRequest r(
3360 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353361
3362 r.Start();
[email protected]255620da2013-08-19 13:14:293363 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303364 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3365 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353366 EXPECT_EQ(0, network_delegate.completed_requests());
3367 // Cancel before callback.
3368 r.Cancel();
3369 // Ensure that network delegate is notified.
3370 EXPECT_EQ(1, network_delegate.completed_requests());
3371 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3372 EXPECT_EQ(ERR_ABORTED, r.status().error());
3373 EXPECT_EQ(1, network_delegate.created_requests());
3374 EXPECT_EQ(0, network_delegate.destroyed_requests());
3375 }
3376 EXPECT_EQ(1, network_delegate.destroyed_requests());
3377}
3378
3379// Tests that we can handle when a network request was canceled while we were
3380// waiting for the network delegate.
3381// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3382TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3383 ASSERT_TRUE(test_server_.Start());
3384
3385 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303386 BlockingNetworkDelegate network_delegate(
3387 BlockingNetworkDelegate::USER_CALLBACK);
3388 network_delegate.set_block_on(
3389 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353390
[email protected]ef2bf422012-05-11 03:27:093391 TestURLRequestContext context(true);
3392 context.set_network_delegate(&network_delegate);
3393 context.Init();
[email protected]9045b8822012-01-13 20:35:353394
3395 {
[email protected]2ca01e52013-10-31 22:05:193396 URLRequest r(
3397 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353398
3399 r.Start();
[email protected]255620da2013-08-19 13:14:293400 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303401 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3402 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353403 EXPECT_EQ(0, network_delegate.completed_requests());
3404 // Cancel before callback.
3405 r.Cancel();
3406 // Ensure that network delegate is notified.
3407 EXPECT_EQ(1, network_delegate.completed_requests());
3408 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3409 EXPECT_EQ(ERR_ABORTED, r.status().error());
3410 EXPECT_EQ(1, network_delegate.created_requests());
3411 EXPECT_EQ(0, network_delegate.destroyed_requests());
3412 }
3413 EXPECT_EQ(1, network_delegate.destroyed_requests());
3414}
3415
3416// Tests that we can handle when a network request was canceled while we were
3417// waiting for the network delegate.
3418// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3419TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3420 ASSERT_TRUE(test_server_.Start());
3421
3422 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303423 BlockingNetworkDelegate network_delegate(
3424 BlockingNetworkDelegate::USER_CALLBACK);
3425 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353426
[email protected]ef2bf422012-05-11 03:27:093427 TestURLRequestContext context(true);
3428 context.set_network_delegate(&network_delegate);
3429 context.Init();
[email protected]9045b8822012-01-13 20:35:353430
3431 {
[email protected]2ca01e52013-10-31 22:05:193432 URLRequest r(
3433 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353434
3435 r.Start();
[email protected]255620da2013-08-19 13:14:293436 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303437 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3438 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353439 EXPECT_EQ(0, network_delegate.completed_requests());
3440 // Cancel before callback.
3441 r.Cancel();
3442 // Ensure that network delegate is notified.
3443 EXPECT_EQ(1, network_delegate.completed_requests());
3444 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3445 EXPECT_EQ(ERR_ABORTED, r.status().error());
3446 EXPECT_EQ(1, network_delegate.created_requests());
3447 EXPECT_EQ(0, network_delegate.destroyed_requests());
3448 }
3449 EXPECT_EQ(1, network_delegate.destroyed_requests());
3450}
3451
3452// Tests that we can handle when a network request was canceled while we were
3453// waiting for the network delegate.
3454// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023455TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353456 ASSERT_TRUE(test_server_.Start());
3457
3458 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303459 BlockingNetworkDelegate network_delegate(
3460 BlockingNetworkDelegate::USER_CALLBACK);
3461 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353462
[email protected]ef2bf422012-05-11 03:27:093463 TestURLRequestContext context(true);
3464 context.set_network_delegate(&network_delegate);
3465 context.Init();
[email protected]9045b8822012-01-13 20:35:353466
3467 {
[email protected]2ca01e52013-10-31 22:05:193468 URLRequest r(
3469 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353470
3471 r.Start();
[email protected]255620da2013-08-19 13:14:293472 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303473 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3474 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353475 EXPECT_EQ(0, network_delegate.completed_requests());
3476 // Cancel before callback.
3477 r.Cancel();
3478 // Ensure that network delegate is notified.
3479 EXPECT_EQ(1, network_delegate.completed_requests());
3480 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3481 EXPECT_EQ(ERR_ABORTED, r.status().error());
3482 EXPECT_EQ(1, network_delegate.created_requests());
3483 EXPECT_EQ(0, network_delegate.destroyed_requests());
3484 }
3485 EXPECT_EQ(1, network_delegate.destroyed_requests());
3486}
3487
[email protected]95409e12010-08-17 20:07:113488// In this unit test, we're using the HTTPTestServer as a proxy server and
3489// issuing a CONNECT request with the magic host name "www.server-auth.com".
3490// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353491TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113492 ASSERT_TRUE(test_server_.Start());
3493
[email protected]ceefd7fd2012-11-29 00:36:243494 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043495 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193496 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503497
[email protected]dc651782009-02-14 01:45:083498 TestDelegate d;
3499 {
[email protected]2ca01e52013-10-31 22:05:193500 URLRequest r(
3501 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]dc651782009-02-14 01:45:083502
3503 r.Start();
3504 EXPECT_TRUE(r.is_pending());
3505
[email protected]255620da2013-08-19 13:14:293506 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083507
[email protected]7461a402011-03-24 23:19:513508 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:053509 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:083510 }
3511}
3512
[email protected]b89290212009-08-14 22:37:353513TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113514 ASSERT_TRUE(test_server_.Start());
3515
initial.commit586acc5fe2008-07-26 22:42:523516 TestDelegate d;
3517 {
[email protected]2ca01e52013-10-31 22:05:193518 URLRequest r(test_server_.GetURL(std::string()),
3519 DEFAULT_PRIORITY,
3520 &d,
3521 &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523522
3523 r.Start();
3524 EXPECT_TRUE(r.is_pending());
3525
[email protected]255620da2013-08-19 13:14:293526 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523527
3528 EXPECT_EQ(1, d.response_started_count());
3529 EXPECT_FALSE(d.received_data_before_response());
3530 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193531 EXPECT_EQ(test_server_.host_port_pair().host(),
3532 r.GetSocketAddress().host());
3533 EXPECT_EQ(test_server_.host_port_pair().port(),
3534 r.GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163535
[email protected]9e743cd2010-03-16 07:03:533536 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523537 }
initial.commit586acc5fe2008-07-26 22:42:523538}
3539
[email protected]263163f2012-06-14 22:40:343540// This test has the server send a large number of cookies to the client.
3541// To ensure that no number of cookies causes a crash, a galloping binary
3542// search is used to estimate that maximum number of cookies that are accepted
3543// by the browser. Beyond the maximum number, the request will fail with
3544// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303545#if defined(OS_WIN)
3546// http://crbug.com/177916
3547#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3548#else
3549#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3550#endif // defined(OS_WIN)
3551TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343552 ASSERT_TRUE(test_server_.Start());
3553
3554 int lower_bound = 0;
3555 int upper_bound = 1;
3556
3557 // Double the number of cookies until the response header limits are
3558 // exceeded.
3559 while (DoManyCookiesRequest(upper_bound)) {
3560 lower_bound = upper_bound;
3561 upper_bound *= 2;
3562 ASSERT_LT(upper_bound, 1000000);
3563 }
3564
3565 int tolerance = upper_bound * 0.005;
3566 if (tolerance < 2)
3567 tolerance = 2;
3568
3569 // Perform a binary search to find the highest possible number of cookies,
3570 // within the desired tolerance.
3571 while (upper_bound - lower_bound >= tolerance) {
3572 int num_cookies = (lower_bound + upper_bound) / 2;
3573
3574 if (DoManyCookiesRequest(num_cookies))
3575 lower_bound = num_cookies;
3576 else
3577 upper_bound = num_cookies;
3578 }
3579 // Success: the test did not crash.
3580}
3581
[email protected]b89290212009-08-14 22:37:353582TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113583 ASSERT_TRUE(test_server_.Start());
3584
initial.commit586acc5fe2008-07-26 22:42:523585 TestDelegate d;
3586 {
[email protected]2ca01e52013-10-31 22:05:193587 URLRequest r(test_server_.GetURL(std::string()),
3588 DEFAULT_PRIORITY,
3589 &d,
3590 &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523591
3592 r.Start();
3593 EXPECT_TRUE(r.is_pending());
3594
[email protected]255620da2013-08-19 13:14:293595 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523596
3597 EXPECT_EQ(1, d.response_started_count());
3598 EXPECT_FALSE(d.received_data_before_response());
3599 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193600 EXPECT_EQ(test_server_.host_port_pair().host(),
3601 r.GetSocketAddress().host());
3602 EXPECT_EQ(test_server_.host_port_pair().port(),
3603 r.GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523604 }
[email protected]5d7b373e2009-09-02 07:19:033605}
3606
[email protected]79e1fd62013-06-20 06:50:043607TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3608 ASSERT_TRUE(test_server_.Start());
3609
3610 TestDelegate d;
3611 {
3612 GURL test_url(test_server_.GetURL(std::string()));
[email protected]2ca01e52013-10-31 22:05:193613 URLRequest r(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:043614
3615 HttpRequestHeaders headers;
3616 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3617
3618 r.Start();
3619 EXPECT_TRUE(r.is_pending());
3620
[email protected]255620da2013-08-19 13:14:293621 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043622
3623 EXPECT_EQ(1, d.response_started_count());
3624 EXPECT_FALSE(d.received_data_before_response());
3625 EXPECT_NE(0, d.bytes_received());
3626 EXPECT_EQ(test_server_.host_port_pair().host(),
3627 r.GetSocketAddress().host());
3628 EXPECT_EQ(test_server_.host_port_pair().port(),
3629 r.GetSocketAddress().port());
3630
3631 EXPECT_TRUE(d.have_full_request_headers());
3632 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3633 }
3634}
3635
[email protected]58e32bb2013-01-21 18:23:253636TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3637 ASSERT_TRUE(test_server_.Start());
3638
3639 TestDelegate d;
3640 {
[email protected]2ca01e52013-10-31 22:05:193641 URLRequest r(test_server_.GetURL(std::string()),
3642 DEFAULT_PRIORITY,
3643 &d,
3644 &default_context_);
[email protected]58e32bb2013-01-21 18:23:253645
3646 r.Start();
3647 EXPECT_TRUE(r.is_pending());
3648
[email protected]255620da2013-08-19 13:14:293649 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253650
3651 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173652 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253653 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3654
3655 EXPECT_EQ(1, d.response_started_count());
3656 EXPECT_FALSE(d.received_data_before_response());
3657 EXPECT_NE(0, d.bytes_received());
3658 EXPECT_EQ(test_server_.host_port_pair().host(),
3659 r.GetSocketAddress().host());
3660 EXPECT_EQ(test_server_.host_port_pair().port(),
3661 r.GetSocketAddress().port());
3662 }
3663}
3664
[email protected]aad63572011-05-24 20:14:393665TEST_F(URLRequestTestHTTP, GetZippedTest) {
3666 ASSERT_TRUE(test_server_.Start());
3667
3668 // Parameter that specifies the Content-Length field in the response:
3669 // C - Compressed length.
3670 // U - Uncompressed length.
3671 // L - Large length (larger than both C & U).
3672 // M - Medium length (between C & U).
3673 // S - Small length (smaller than both C & U).
3674 const char test_parameters[] = "CULMS";
3675 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3676 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:443677 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:393678 // S has too little data, but we seem to accept it.
3679 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:373680 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:393681
3682 for (int i = 0; i < num_tests ; i++) {
3683 TestDelegate d;
3684 {
3685 std::string test_file =
3686 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3687 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:393688
[email protected]ceefd7fd2012-11-29 00:36:243689 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:093690 TestURLRequestContext context(true);
3691 context.set_network_delegate(&network_delegate);
3692 context.Init();
[email protected]87a09a92011-07-14 15:50:503693
[email protected]2ca01e52013-10-31 22:05:193694 URLRequest r(
3695 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, &context);
[email protected]aad63572011-05-24 20:14:393696 r.Start();
3697 EXPECT_TRUE(r.is_pending());
3698
[email protected]255620da2013-08-19 13:14:293699 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:393700
3701 EXPECT_EQ(1, d.response_started_count());
3702 EXPECT_FALSE(d.received_data_before_response());
3703 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3704 << " status = " << r.status().status()
[email protected]d0cc35b2011-09-08 12:02:053705 << " error = " << r.status().error();
[email protected]aad63572011-05-24 20:14:393706 if (test_expect_success[i]) {
3707 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3708 << " Parameter = \"" << test_file << "\"";
3709 } else {
3710 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]5543cbb2012-04-20 16:35:233711 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
[email protected]aad63572011-05-24 20:14:393712 << " Parameter = \"" << test_file << "\"";
3713 }
3714 }
3715 }
3716}
3717
[email protected]c044616e2013-02-20 02:01:263718TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
[email protected]95409e12010-08-17 20:07:113719 ASSERT_TRUE(test_server_.Start());
3720
[email protected]ce7d0cbc2013-05-03 18:57:223721 SpawnedTestServer https_test_server(
3722 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:153723 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:113724 ASSERT_TRUE(https_test_server.Start());
[email protected]7844480a2009-12-16 21:18:583725
3726 // An https server is sent a request with an https referer,
3727 // and responds with a redirect to an http url. The http
3728 // server should not be sent the referer.
[email protected]007b3f82013-04-09 08:46:453729 GURL http_destination = test_server_.GetURL(std::string());
[email protected]7844480a2009-12-16 21:18:583730 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193731 URLRequest req(
3732 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3733 DEFAULT_PRIORITY,
3734 &d,
3735 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:133736 req.SetReferrer("https://www.referrer.com/");
[email protected]7844480a2009-12-16 21:18:583737 req.Start();
[email protected]255620da2013-08-19 13:14:293738 base::RunLoop().Run();
[email protected]7844480a2009-12-16 21:18:583739
3740 EXPECT_EQ(1, d.response_started_count());
3741 EXPECT_EQ(1, d.received_redirect_count());
3742 EXPECT_EQ(http_destination, req.url());
3743 EXPECT_EQ(std::string(), req.referrer());
3744}
3745
[email protected]58e32bb2013-01-21 18:23:253746TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3747 ASSERT_TRUE(test_server_.Start());
3748
[email protected]007b3f82013-04-09 08:46:453749 GURL destination_url = test_server_.GetURL(std::string());
3750 GURL original_url =
3751 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:253752 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193753 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]58e32bb2013-01-21 18:23:253754 req.Start();
[email protected]255620da2013-08-19 13:14:293755 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253756
3757 EXPECT_EQ(1, d.response_started_count());
3758 EXPECT_EQ(1, d.received_redirect_count());
3759 EXPECT_EQ(destination_url, req.url());
3760 EXPECT_EQ(original_url, req.original_url());
3761 ASSERT_EQ(2U, req.url_chain().size());
3762 EXPECT_EQ(original_url, req.url_chain()[0]);
3763 EXPECT_EQ(destination_url, req.url_chain()[1]);
3764
3765 LoadTimingInfo load_timing_info_before_redirect;
3766 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3767 &load_timing_info_before_redirect));
3768 TestLoadTimingNotReused(load_timing_info_before_redirect,
3769 CONNECT_TIMING_HAS_DNS_TIMES);
3770
3771 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173772 req.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253773 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3774
3775 // Check that a new socket was used on redirect, since the server does not
3776 // supposed keep-alive sockets, and that the times before the redirect are
3777 // before the ones recorded for the second request.
3778 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3779 load_timing_info.socket_log_id);
3780 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3781 load_timing_info.connect_timing.connect_start);
3782}
3783
[email protected]8f1ac082011-04-19 21:14:133784TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3785 ASSERT_TRUE(test_server_.Start());
3786
[email protected]007b3f82013-04-09 08:46:453787 GURL destination_url = test_server_.GetURL(std::string());
3788 GURL middle_redirect_url =
3789 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:133790 GURL original_url = test_server_.GetURL(
3791 "server-redirect?" + middle_redirect_url.spec());
3792 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193793 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]8f1ac082011-04-19 21:14:133794 req.Start();
[email protected]255620da2013-08-19 13:14:293795 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:133796
3797 EXPECT_EQ(1, d.response_started_count());
3798 EXPECT_EQ(2, d.received_redirect_count());
3799 EXPECT_EQ(destination_url, req.url());
3800 EXPECT_EQ(original_url, req.original_url());
3801 ASSERT_EQ(3U, req.url_chain().size());
3802 EXPECT_EQ(original_url, req.url_chain()[0]);
3803 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3804 EXPECT_EQ(destination_url, req.url_chain()[2]);
3805}
3806
[email protected]abe1c4a2013-10-25 19:28:513807// First and second pieces of information logged by delegates to URLRequests.
3808const char kFirstDelegateInfo[] = "Wonderful delegate";
3809const char kSecondDelegateInfo[] = "Exciting delegate";
3810
3811// Logs delegate information to a URLRequest. The first string is logged
3812// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3813// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3814// another asynchronous call is used to clear the delegate information
3815// before calling a callback. The object then deletes itself.
3816class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3817 public:
3818 typedef base::Callback<void()> Callback;
3819
3820 // Each time delegate information is added to the URLRequest, the resulting
3821 // load state is checked. The expected load state after each request is
3822 // passed in as an argument.
3823 static void Run(URLRequest* url_request,
3824 LoadState expected_first_load_state,
3825 LoadState expected_second_load_state,
3826 LoadState expected_third_load_state,
3827 const Callback& callback) {
3828 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3829 url_request,
3830 expected_first_load_state,
3831 expected_second_load_state,
3832 expected_third_load_state,
3833 callback);
3834 logger->Start();
3835 }
3836
3837 // Checks that the log entries, starting with log_position, contain the
3838 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3839 // recorded. Returns the index of entry after the expected number of
3840 // events this logged, or entries.size() if there aren't enough entries.
3841 static size_t CheckDelegateInfo(
3842 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3843 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3844 if (log_position + 3 >= entries.size()) {
3845 ADD_FAILURE() << "Not enough log entries";
3846 return entries.size();
3847 }
3848 std::string delegate_info;
3849 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3850 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3851 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3852 &delegate_info));
3853 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3854
3855 ++log_position;
3856 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3857 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3858
3859 ++log_position;
3860 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3861 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3862 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3863 &delegate_info));
3864 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3865
3866 ++log_position;
3867 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3868 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3869
3870 return log_position + 1;
3871 }
3872
[email protected]1826a402014-01-08 15:40:483873 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3874 // Returns the position of the end message.
3875 static size_t ExpectBeforeNetworkEvents(
3876 const CapturingNetLog::CapturedEntryList& entries,
3877 size_t log_position) {
3878 log_position =
3879 ExpectLogContainsSomewhereAfter(entries,
3880 log_position,
3881 NetLog::TYPE_URL_REQUEST_DELEGATE,
3882 NetLog::PHASE_BEGIN);
3883 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3884 entries[log_position + 1].type);
3885 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3886 return log_position + 1;
3887 }
3888
[email protected]abe1c4a2013-10-25 19:28:513889 private:
3890 friend class base::RefCounted<AsyncDelegateLogger>;
3891
3892 AsyncDelegateLogger(URLRequest* url_request,
3893 LoadState expected_first_load_state,
3894 LoadState expected_second_load_state,
3895 LoadState expected_third_load_state,
3896 const Callback& callback)
3897 : url_request_(url_request),
3898 expected_first_load_state_(expected_first_load_state),
3899 expected_second_load_state_(expected_second_load_state),
3900 expected_third_load_state_(expected_third_load_state),
3901 callback_(callback) {
3902 }
3903
3904 ~AsyncDelegateLogger() {}
3905
3906 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:533907 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:513908 LoadStateWithParam load_state = url_request_->GetLoadState();
3909 EXPECT_EQ(expected_first_load_state_, load_state.state);
3910 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3911 base::MessageLoop::current()->PostTask(
3912 FROM_HERE,
3913 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3914 }
3915
3916 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:533917 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:513918 LoadStateWithParam load_state = url_request_->GetLoadState();
3919 EXPECT_EQ(expected_second_load_state_, load_state.state);
3920 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3921 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3922 } else {
3923 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3924 }
3925 base::MessageLoop::current()->PostTask(
3926 FROM_HERE,
3927 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3928 }
3929
3930 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:533931 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:513932 LoadStateWithParam load_state = url_request_->GetLoadState();
3933 EXPECT_EQ(expected_third_load_state_, load_state.state);
3934 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:083935 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:513936 callback_.Run();
3937 }
3938
3939 URLRequest* url_request_;
3940 const int expected_first_load_state_;
3941 const int expected_second_load_state_;
3942 const int expected_third_load_state_;
3943 const Callback callback_;
3944
3945 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3946};
3947
3948// NetworkDelegate that logs delegate information before a request is started,
3949// before headers are sent, when headers are read, and when auth information
3950// is requested. Uses AsyncDelegateLogger.
3951class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3952 public:
3953 AsyncLoggingNetworkDelegate() {}
3954 virtual ~AsyncLoggingNetworkDelegate() {}
3955
3956 // NetworkDelegate implementation.
3957 virtual int OnBeforeURLRequest(URLRequest* request,
3958 const CompletionCallback& callback,
3959 GURL* new_url) OVERRIDE {
3960 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3961 return RunCallbackAsynchronously(request, callback);
3962 }
3963
3964 virtual int OnBeforeSendHeaders(URLRequest* request,
3965 const CompletionCallback& callback,
3966 HttpRequestHeaders* headers) OVERRIDE {
3967 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3968 return RunCallbackAsynchronously(request, callback);
3969 }
3970
3971 virtual int OnHeadersReceived(
3972 URLRequest* request,
3973 const CompletionCallback& callback,
3974 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:163975 scoped_refptr<HttpResponseHeaders>* override_response_headers,
3976 GURL* allowed_unsafe_redirect_url) OVERRIDE {
3977 TestNetworkDelegate::OnHeadersReceived(request,
3978 callback,
[email protected]abe1c4a2013-10-25 19:28:513979 original_response_headers,
[email protected]5f714132014-03-26 10:41:163980 override_response_headers,
3981 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:513982 return RunCallbackAsynchronously(request, callback);
3983 }
3984
3985 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
3986 URLRequest* request,
3987 const AuthChallengeInfo& auth_info,
3988 const AuthCallback& callback,
3989 AuthCredentials* credentials) OVERRIDE {
3990 AsyncDelegateLogger::Run(
3991 request,
3992 LOAD_STATE_WAITING_FOR_DELEGATE,
3993 LOAD_STATE_WAITING_FOR_DELEGATE,
3994 LOAD_STATE_WAITING_FOR_DELEGATE,
3995 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
3996 callback, credentials));
3997 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
3998 }
3999
4000 private:
4001 static int RunCallbackAsynchronously(
4002 URLRequest* request,
4003 const CompletionCallback& callback) {
4004 AsyncDelegateLogger::Run(
4005 request,
4006 LOAD_STATE_WAITING_FOR_DELEGATE,
4007 LOAD_STATE_WAITING_FOR_DELEGATE,
4008 LOAD_STATE_WAITING_FOR_DELEGATE,
4009 base::Bind(callback, OK));
4010 return ERR_IO_PENDING;
4011 }
4012
4013 static void SetAuthAndResume(const AuthCallback& callback,
4014 AuthCredentials* credentials) {
4015 *credentials = AuthCredentials(kUser, kSecret);
4016 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4017 }
4018
4019 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4020};
4021
4022// URLRequest::Delegate that logs delegate information when the headers
4023// are received, when each read completes, and during redirects. Uses
4024// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4025//
4026// Inherits from TestDelegate to reuse the TestDelegate code to handle
4027// advancing to the next step in most cases, as well as cancellation.
4028class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4029 public:
4030 enum CancelStage {
4031 NO_CANCEL = 0,
4032 CANCEL_ON_RECEIVED_REDIRECT,
4033 CANCEL_ON_RESPONSE_STARTED,
4034 CANCEL_ON_READ_COMPLETED
4035 };
4036
4037 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4038 : cancel_stage_(cancel_stage) {
4039 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4040 set_cancel_in_received_redirect(true);
4041 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4042 set_cancel_in_response_started(true);
4043 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4044 set_cancel_in_received_data(true);
4045 }
4046 virtual ~AsyncLoggingUrlRequestDelegate() {}
4047
4048 // URLRequest::Delegate implementation:
4049 void virtual OnReceivedRedirect(URLRequest* request,
4050 const GURL& new_url,
4051 bool* defer_redirect) OVERRIDE {
4052 *defer_redirect = true;
4053 AsyncDelegateLogger::Run(
4054 request,
4055 LOAD_STATE_WAITING_FOR_DELEGATE,
4056 LOAD_STATE_WAITING_FOR_DELEGATE,
4057 LOAD_STATE_WAITING_FOR_DELEGATE,
4058 base::Bind(
4059 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4060 base::Unretained(this), request, new_url));
4061 }
4062
4063 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4064 AsyncDelegateLogger::Run(
4065 request,
4066 LOAD_STATE_WAITING_FOR_DELEGATE,
4067 LOAD_STATE_WAITING_FOR_DELEGATE,
4068 LOAD_STATE_WAITING_FOR_DELEGATE,
4069 base::Bind(
4070 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4071 base::Unretained(this), request));
4072 }
4073
4074 virtual void OnReadCompleted(URLRequest* request,
4075 int bytes_read) OVERRIDE {
4076 AsyncDelegateLogger::Run(
4077 request,
4078 LOAD_STATE_IDLE,
4079 LOAD_STATE_IDLE,
4080 LOAD_STATE_IDLE,
4081 base::Bind(
4082 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4083 base::Unretained(this), request, bytes_read));
4084 }
4085
4086 private:
4087 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4088 const GURL& new_url) {
4089 bool defer_redirect = false;
4090 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
4091 // FollowDeferredRedirect should not be called after cancellation.
4092 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4093 return;
4094 if (!defer_redirect)
4095 request->FollowDeferredRedirect();
4096 }
4097
4098 void OnResponseStartedLoggingComplete(URLRequest* request) {
4099 // The parent class continues the request.
4100 TestDelegate::OnResponseStarted(request);
4101 }
4102
4103 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4104 // The parent class continues the request.
4105 TestDelegate::OnReadCompleted(request, bytes_read);
4106 }
4107
4108 const CancelStage cancel_stage_;
4109
4110 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4111};
4112
4113// Tests handling of delegate info before a request starts.
4114TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4115 ASSERT_TRUE(test_server_.Start());
4116
4117 TestDelegate request_delegate;
4118 TestURLRequestContext context(true);
4119 context.set_network_delegate(NULL);
4120 context.set_net_log(&net_log_);
4121 context.Init();
4122
4123 {
4124 URLRequest r(test_server_.GetURL("empty.html"),
[email protected]2ca01e52013-10-31 22:05:194125 DEFAULT_PRIORITY,
4126 &request_delegate,
4127 &context);
[email protected]abe1c4a2013-10-25 19:28:514128 LoadStateWithParam load_state = r.GetLoadState();
4129 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084130 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514131
4132 AsyncDelegateLogger::Run(
4133 &r,
4134 LOAD_STATE_WAITING_FOR_DELEGATE,
4135 LOAD_STATE_WAITING_FOR_DELEGATE,
4136 LOAD_STATE_IDLE,
4137 base::Bind(&URLRequest::Start, base::Unretained(&r)));
4138
4139 base::RunLoop().Run();
4140
4141 EXPECT_EQ(200, r.GetResponseCode());
4142 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4143 }
4144
4145 CapturingNetLog::CapturedEntryList entries;
4146 net_log_.GetEntries(&entries);
4147 size_t log_position = ExpectLogContainsSomewhereAfter(
4148 entries,
4149 0,
4150 NetLog::TYPE_DELEGATE_INFO,
4151 NetLog::PHASE_BEGIN);
4152
4153 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4154
4155 // Nothing else should add any delegate info to the request.
4156 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4157 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4158}
4159
4160// Tests handling of delegate info from a network delegate.
4161TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4162 ASSERT_TRUE(test_server_.Start());
4163
4164 TestDelegate request_delegate;
4165 AsyncLoggingNetworkDelegate network_delegate;
4166 TestURLRequestContext context(true);
4167 context.set_network_delegate(&network_delegate);
4168 context.set_net_log(&net_log_);
4169 context.Init();
4170
4171 {
4172 URLRequest r(test_server_.GetURL("simple.html"),
[email protected]2ca01e52013-10-31 22:05:194173 DEFAULT_PRIORITY,
4174 &request_delegate,
4175 &context);
[email protected]abe1c4a2013-10-25 19:28:514176 LoadStateWithParam load_state = r.GetLoadState();
4177 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084178 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514179
4180 r.Start();
4181 base::RunLoop().Run();
4182
4183 EXPECT_EQ(200, r.GetResponseCode());
4184 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4185 EXPECT_EQ(1, network_delegate.created_requests());
4186 EXPECT_EQ(0, network_delegate.destroyed_requests());
4187 }
4188 EXPECT_EQ(1, network_delegate.destroyed_requests());
4189
4190 size_t log_position = 0;
4191 CapturingNetLog::CapturedEntryList entries;
4192 net_log_.GetEntries(&entries);
4193 for (size_t i = 0; i < 3; ++i) {
4194 log_position = ExpectLogContainsSomewhereAfter(
4195 entries,
4196 log_position + 1,
4197 NetLog::TYPE_URL_REQUEST_DELEGATE,
4198 NetLog::PHASE_BEGIN);
4199
4200 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4201 log_position + 1);
4202
4203 ASSERT_LT(log_position, entries.size());
4204 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4205 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484206
4207 if (i == 1) {
4208 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4209 entries, log_position + 1);
4210 }
[email protected]abe1c4a2013-10-25 19:28:514211 }
4212
4213 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4214 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4215}
4216
4217// Tests handling of delegate info from a network delegate in the case of an
4218// HTTP redirect.
4219TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4220 ASSERT_TRUE(test_server_.Start());
4221
4222 TestDelegate request_delegate;
4223 AsyncLoggingNetworkDelegate network_delegate;
4224 TestURLRequestContext context(true);
4225 context.set_network_delegate(&network_delegate);
4226 context.set_net_log(&net_log_);
4227 context.Init();
4228
4229 {
4230 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194231 DEFAULT_PRIORITY,
4232 &request_delegate,
4233 &context);
[email protected]abe1c4a2013-10-25 19:28:514234 LoadStateWithParam load_state = r.GetLoadState();
4235 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084236 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514237
4238 r.Start();
4239 base::RunLoop().Run();
4240
4241 EXPECT_EQ(200, r.GetResponseCode());
4242 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4243 EXPECT_EQ(2, network_delegate.created_requests());
4244 EXPECT_EQ(0, network_delegate.destroyed_requests());
4245 }
4246 EXPECT_EQ(1, network_delegate.destroyed_requests());
4247
4248 size_t log_position = 0;
4249 CapturingNetLog::CapturedEntryList entries;
4250 net_log_.GetEntries(&entries);
4251 // The NetworkDelegate logged information in OnBeforeURLRequest,
4252 // OnBeforeSendHeaders, and OnHeadersReceived.
4253 for (size_t i = 0; i < 3; ++i) {
4254 log_position = ExpectLogContainsSomewhereAfter(
4255 entries,
4256 log_position + 1,
4257 NetLog::TYPE_URL_REQUEST_DELEGATE,
4258 NetLog::PHASE_BEGIN);
4259
4260 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4261 log_position + 1);
4262
4263 ASSERT_LT(log_position, entries.size());
4264 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4265 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484266
4267 if (i == 1) {
4268 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4269 entries, log_position + 1);
4270 }
[email protected]abe1c4a2013-10-25 19:28:514271 }
4272
4273 // The URLRequest::Delegate then gets informed about the redirect.
4274 log_position = ExpectLogContainsSomewhereAfter(
4275 entries,
4276 log_position + 1,
4277 NetLog::TYPE_URL_REQUEST_DELEGATE,
4278 NetLog::PHASE_BEGIN);
4279
4280 // The NetworkDelegate logged information in the same three events as before.
4281 for (size_t i = 0; i < 3; ++i) {
4282 log_position = ExpectLogContainsSomewhereAfter(
4283 entries,
4284 log_position + 1,
4285 NetLog::TYPE_URL_REQUEST_DELEGATE,
4286 NetLog::PHASE_BEGIN);
4287
4288 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4289 log_position + 1);
4290
4291 ASSERT_LT(log_position, entries.size());
4292 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4293 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4294 }
4295
4296 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4297 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4298}
4299
4300// Tests handling of delegate info from a network delegate in the case of HTTP
4301// AUTH.
4302TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4303 ASSERT_TRUE(test_server_.Start());
4304
4305 TestDelegate request_delegate;
4306 AsyncLoggingNetworkDelegate network_delegate;
4307 TestURLRequestContext context(true);
4308 context.set_network_delegate(&network_delegate);
4309 context.set_net_log(&net_log_);
4310 context.Init();
4311
4312 {
4313 URLRequest r(test_server_.GetURL("auth-basic"),
[email protected]2ca01e52013-10-31 22:05:194314 DEFAULT_PRIORITY,
4315 &request_delegate,
4316 &context);
[email protected]abe1c4a2013-10-25 19:28:514317 LoadStateWithParam load_state = r.GetLoadState();
4318 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084319 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514320
4321 r.Start();
4322 base::RunLoop().Run();
4323
4324 EXPECT_EQ(200, r.GetResponseCode());
4325 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4326 EXPECT_EQ(1, network_delegate.created_requests());
4327 EXPECT_EQ(0, network_delegate.destroyed_requests());
4328 }
4329 EXPECT_EQ(1, network_delegate.destroyed_requests());
4330
4331 size_t log_position = 0;
4332 CapturingNetLog::CapturedEntryList entries;
4333 net_log_.GetEntries(&entries);
4334 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4335 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4336 // OnBeforeURLRequest and OnBeforeSendHeaders.
4337 for (size_t i = 0; i < 6; ++i) {
4338 log_position = ExpectLogContainsSomewhereAfter(
4339 entries,
4340 log_position + 1,
4341 NetLog::TYPE_URL_REQUEST_DELEGATE,
4342 NetLog::PHASE_BEGIN);
4343
4344 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4345 log_position + 1);
4346
4347 ASSERT_LT(log_position, entries.size());
4348 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4349 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484350
4351 if (i == 1) {
4352 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4353 entries, log_position + 1);
4354 }
[email protected]abe1c4a2013-10-25 19:28:514355 }
4356
4357 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4358 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4359}
4360
4361// Tests handling of delegate info from a URLRequest::Delegate.
4362TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4363 ASSERT_TRUE(test_server_.Start());
4364
4365 AsyncLoggingUrlRequestDelegate request_delegate(
4366 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4367 TestURLRequestContext context(true);
4368 context.set_network_delegate(NULL);
4369 context.set_net_log(&net_log_);
4370 context.Init();
4371
4372 {
4373 // A chunked response with delays between chunks is used to make sure that
4374 // attempts by the URLRequest delegate to log information while reading the
4375 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484376 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514377 // that it occurs.
4378 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
[email protected]2ca01e52013-10-31 22:05:194379 DEFAULT_PRIORITY,
4380 &request_delegate,
4381 &context);
[email protected]abe1c4a2013-10-25 19:28:514382 LoadStateWithParam load_state = r.GetLoadState();
4383 r.Start();
4384 base::RunLoop().Run();
4385
4386 EXPECT_EQ(200, r.GetResponseCode());
4387 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4388 }
4389
4390 CapturingNetLog::CapturedEntryList entries;
4391 net_log_.GetEntries(&entries);
4392
[email protected]1826a402014-01-08 15:40:484393 size_t log_position = 0;
4394
4395 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4396 entries, log_position);
4397
[email protected]abe1c4a2013-10-25 19:28:514398 // The delegate info should only have been logged on header complete. Other
4399 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484400 log_position =
4401 ExpectLogContainsSomewhereAfter(entries,
4402 log_position + 1,
4403 NetLog::TYPE_URL_REQUEST_DELEGATE,
4404 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514405
4406 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4407 log_position + 1);
4408
4409 ASSERT_LT(log_position, entries.size());
4410 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4411 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4412
4413 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4414 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4415 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4416 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4417}
4418
4419// Tests handling of delegate info from a URLRequest::Delegate in the case of
4420// an HTTP redirect.
4421TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4422 ASSERT_TRUE(test_server_.Start());
4423
4424 AsyncLoggingUrlRequestDelegate request_delegate(
4425 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4426 TestURLRequestContext context(true);
4427 context.set_network_delegate(NULL);
4428 context.set_net_log(&net_log_);
4429 context.Init();
4430
4431 {
4432 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194433 DEFAULT_PRIORITY,
4434 &request_delegate,
4435 &context);
[email protected]abe1c4a2013-10-25 19:28:514436 LoadStateWithParam load_state = r.GetLoadState();
4437 r.Start();
4438 base::RunLoop().Run();
4439
4440 EXPECT_EQ(200, r.GetResponseCode());
4441 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4442 }
4443
4444 CapturingNetLog::CapturedEntryList entries;
4445 net_log_.GetEntries(&entries);
4446
4447 // Delegate info should only have been logged in OnReceivedRedirect and
4448 // OnResponseStarted.
4449 size_t log_position = 0;
4450 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484451 if (i == 0) {
4452 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4453 entries, log_position) + 1;
4454 }
4455
[email protected]abe1c4a2013-10-25 19:28:514456 log_position = ExpectLogContainsSomewhereAfter(
4457 entries,
4458 log_position,
4459 NetLog::TYPE_URL_REQUEST_DELEGATE,
4460 NetLog::PHASE_BEGIN);
4461
4462 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4463 log_position + 1);
4464
4465 ASSERT_LT(log_position, entries.size());
4466 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4467 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4468 }
4469
4470 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4471 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4472 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4473 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4474}
4475
4476// Tests handling of delegate info from a URLRequest::Delegate in the case of
4477// an HTTP redirect, with cancellation at various points.
4478TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4479 ASSERT_TRUE(test_server_.Start());
4480
4481 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4482 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4483 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4484 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4485 };
4486
4487 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4488 ++test_case) {
4489 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4490 TestURLRequestContext context(true);
4491 CapturingNetLog net_log;
4492 context.set_network_delegate(NULL);
4493 context.set_net_log(&net_log);
4494 context.Init();
4495
4496 {
4497 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194498 DEFAULT_PRIORITY,
4499 &request_delegate,
4500 &context);
[email protected]abe1c4a2013-10-25 19:28:514501 LoadStateWithParam load_state = r.GetLoadState();
4502 r.Start();
4503 base::RunLoop().Run();
4504 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4505 }
4506
4507 CapturingNetLog::CapturedEntryList entries;
4508 net_log.GetEntries(&entries);
4509
4510 // Delegate info is always logged in both OnReceivedRedirect and
4511 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4512 // OnResponseStarted delegate call is after cancellation, but logging is
4513 // still currently supported in that call.
4514 size_t log_position = 0;
4515 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484516 if (i == 0) {
4517 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4518 entries, log_position) + 1;
4519 }
4520
[email protected]abe1c4a2013-10-25 19:28:514521 log_position = ExpectLogContainsSomewhereAfter(
4522 entries,
4523 log_position,
4524 NetLog::TYPE_URL_REQUEST_DELEGATE,
4525 NetLog::PHASE_BEGIN);
4526
4527 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4528 log_position + 1);
4529
4530 ASSERT_LT(log_position, entries.size());
4531 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4532 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4533 }
4534
4535 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4536 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4537 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4538 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4539 }
4540}
4541
[email protected]847c0fa92012-11-06 16:37:424542namespace {
4543
4544const char kExtraHeader[] = "Allow-Snafu";
4545const char kExtraValue[] = "fubar";
4546
4547class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164548 virtual void OnReceivedRedirect(net::URLRequest* request,
4549 const GURL& new_url,
4550 bool* defer_redirect) OVERRIDE {
[email protected]847c0fa92012-11-06 16:37:424551 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4552 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4553 }
4554};
4555
4556} // namespace
4557
4558TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4559 ASSERT_TRUE(test_server_.Start());
4560
4561 GURL destination_url = test_server_.GetURL(
4562 "echoheader?" + std::string(kExtraHeader));
4563 GURL original_url = test_server_.GetURL(
4564 "server-redirect?" + destination_url.spec());
4565 RedirectWithAdditionalHeadersDelegate d;
[email protected]2ca01e52013-10-31 22:05:194566 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]847c0fa92012-11-06 16:37:424567 req.Start();
[email protected]255620da2013-08-19 13:14:294568 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424569
4570 std::string value;
4571 const HttpRequestHeaders& headers = req.extra_request_headers();
4572 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4573 EXPECT_EQ(kExtraValue, value);
4574 EXPECT_FALSE(req.is_pending());
4575 EXPECT_FALSE(req.is_redirecting());
4576 EXPECT_EQ(kExtraValue, d.data_received());
4577}
4578
[email protected]251a1b92012-11-13 11:01:094579namespace {
4580
4581const char kExtraHeaderToRemove[] = "To-Be-Removed";
4582
4583class RedirectWithHeaderRemovalDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164584 virtual void OnReceivedRedirect(net::URLRequest* request,
[email protected]251a1b92012-11-13 11:01:094585 const GURL& new_url,
[email protected]46fadfd2013-02-06 09:40:164586 bool* defer_redirect) OVERRIDE {
[email protected]251a1b92012-11-13 11:01:094587 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4588 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4589 }
4590};
4591
4592} // namespace
4593
4594TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4595 ASSERT_TRUE(test_server_.Start());
4596
4597 GURL destination_url = test_server_.GetURL(
4598 "echoheader?" + std::string(kExtraHeaderToRemove));
4599 GURL original_url = test_server_.GetURL(
4600 "server-redirect?" + destination_url.spec());
4601 RedirectWithHeaderRemovalDelegate d;
[email protected]2ca01e52013-10-31 22:05:194602 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]251a1b92012-11-13 11:01:094603 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4604 req.Start();
[email protected]255620da2013-08-19 13:14:294605 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094606
4607 std::string value;
4608 const HttpRequestHeaders& headers = req.extra_request_headers();
4609 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4610 EXPECT_FALSE(req.is_pending());
4611 EXPECT_FALSE(req.is_redirecting());
4612 EXPECT_EQ("None", d.data_received());
4613}
4614
[email protected]316c1e5e2012-09-12 15:17:444615TEST_F(URLRequestTestHTTP, CancelTest) {
4616 TestDelegate d;
4617 {
[email protected]2ca01e52013-10-31 22:05:194618 URLRequest r(GURL("http://www.google.com/"),
4619 DEFAULT_PRIORITY,
4620 &d,
4621 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444622
4623 r.Start();
4624 EXPECT_TRUE(r.is_pending());
4625
4626 r.Cancel();
4627
[email protected]255620da2013-08-19 13:14:294628 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444629
4630 // We expect to receive OnResponseStarted even though the request has been
4631 // cancelled.
4632 EXPECT_EQ(1, d.response_started_count());
4633 EXPECT_EQ(0, d.bytes_received());
4634 EXPECT_FALSE(d.received_data_before_response());
4635 }
4636}
4637
4638TEST_F(URLRequestTestHTTP, CancelTest2) {
4639 ASSERT_TRUE(test_server_.Start());
4640
4641 TestDelegate d;
4642 {
[email protected]2ca01e52013-10-31 22:05:194643 URLRequest r(test_server_.GetURL(std::string()),
4644 DEFAULT_PRIORITY,
4645 &d,
4646 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444647
4648 d.set_cancel_in_response_started(true);
4649
4650 r.Start();
4651 EXPECT_TRUE(r.is_pending());
4652
[email protected]255620da2013-08-19 13:14:294653 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444654
4655 EXPECT_EQ(1, d.response_started_count());
4656 EXPECT_EQ(0, d.bytes_received());
4657 EXPECT_FALSE(d.received_data_before_response());
4658 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4659 }
4660}
4661
4662TEST_F(URLRequestTestHTTP, CancelTest3) {
4663 ASSERT_TRUE(test_server_.Start());
4664
4665 TestDelegate d;
4666 {
[email protected]2ca01e52013-10-31 22:05:194667 URLRequest r(test_server_.GetURL(std::string()),
4668 DEFAULT_PRIORITY,
4669 &d,
4670 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444671
4672 d.set_cancel_in_received_data(true);
4673
4674 r.Start();
4675 EXPECT_TRUE(r.is_pending());
4676
[email protected]255620da2013-08-19 13:14:294677 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444678
4679 EXPECT_EQ(1, d.response_started_count());
4680 // There is no guarantee about how much data was received
4681 // before the cancel was issued. It could have been 0 bytes,
4682 // or it could have been all the bytes.
4683 // EXPECT_EQ(0, d.bytes_received());
4684 EXPECT_FALSE(d.received_data_before_response());
4685 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4686 }
4687}
4688
4689TEST_F(URLRequestTestHTTP, CancelTest4) {
4690 ASSERT_TRUE(test_server_.Start());
4691
4692 TestDelegate d;
4693 {
[email protected]2ca01e52013-10-31 22:05:194694 URLRequest r(test_server_.GetURL(std::string()),
4695 DEFAULT_PRIORITY,
4696 &d,
4697 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444698
4699 r.Start();
4700 EXPECT_TRUE(r.is_pending());
4701
4702 // The request will be implicitly canceled when it is destroyed. The
4703 // test delegate must not post a quit message when this happens because
4704 // this test doesn't actually have a message loop. The quit message would
4705 // get put on this thread's message queue and the next test would exit
4706 // early, causing problems.
4707 d.set_quit_on_complete(false);
4708 }
4709 // expect things to just cleanup properly.
4710
4711 // we won't actually get a received reponse here because we've never run the
4712 // message loop
4713 EXPECT_FALSE(d.received_data_before_response());
4714 EXPECT_EQ(0, d.bytes_received());
4715}
4716
4717TEST_F(URLRequestTestHTTP, CancelTest5) {
4718 ASSERT_TRUE(test_server_.Start());
4719
4720 // populate cache
4721 {
4722 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194723 URLRequest r(test_server_.GetURL("cachetime"),
4724 DEFAULT_PRIORITY,
4725 &d,
4726 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444727 r.Start();
[email protected]255620da2013-08-19 13:14:294728 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444729 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4730 }
4731
4732 // cancel read from cache (see bug 990242)
4733 {
4734 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194735 URLRequest r(test_server_.GetURL("cachetime"),
4736 DEFAULT_PRIORITY,
4737 &d,
4738 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444739 r.Start();
4740 r.Cancel();
[email protected]255620da2013-08-19 13:14:294741 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444742
4743 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4744 EXPECT_EQ(1, d.response_started_count());
4745 EXPECT_EQ(0, d.bytes_received());
4746 EXPECT_FALSE(d.received_data_before_response());
4747 }
4748}
4749
4750TEST_F(URLRequestTestHTTP, PostTest) {
4751 ASSERT_TRUE(test_server_.Start());
4752 HTTPUploadDataOperationTest("POST");
4753}
4754
4755TEST_F(URLRequestTestHTTP, PutTest) {
4756 ASSERT_TRUE(test_server_.Start());
4757 HTTPUploadDataOperationTest("PUT");
4758}
4759
4760TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4761 ASSERT_TRUE(test_server_.Start());
4762
4763 TestDelegate d;
4764 {
[email protected]2ca01e52013-10-31 22:05:194765 URLRequest r(
4766 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444767 r.set_method("POST");
4768
4769 r.Start();
4770 EXPECT_TRUE(r.is_pending());
4771
[email protected]255620da2013-08-19 13:14:294772 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444773
[email protected]329b68b2012-11-14 17:54:274774 ASSERT_EQ(1, d.response_started_count())
4775 << "request failed: " << r.status().status()
4776 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444777
4778 EXPECT_FALSE(d.received_data_before_response());
4779 EXPECT_TRUE(d.data_received().empty());
4780 }
4781}
4782
4783TEST_F(URLRequestTestHTTP, PostFileTest) {
4784 ASSERT_TRUE(test_server_.Start());
4785
4786 TestDelegate d;
4787 {
[email protected]2ca01e52013-10-31 22:05:194788 URLRequest r(
4789 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444790 r.set_method("POST");
4791
[email protected]6cdfd7f2013-02-08 20:40:154792 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:444793 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:024794 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:444795
[email protected]f288ef02012-12-15 20:28:284796 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:444797
[email protected]6cdfd7f2013-02-08 20:40:154798 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:444799 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4800 path = path.Append(FILE_PATH_LITERAL("net"));
4801 path = path.Append(FILE_PATH_LITERAL("data"));
4802 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4803 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:364804 element_readers.push_back(
4805 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4806 path,
4807 0,
4808 kuint64max,
4809 base::Time()));
[email protected]96c77a72013-09-24 09:49:204810 r.set_upload(make_scoped_ptr(
4811 new UploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:444812
4813 r.Start();
4814 EXPECT_TRUE(r.is_pending());
4815
[email protected]255620da2013-08-19 13:14:294816 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444817
[email protected]329b68b2012-11-14 17:54:274818 int64 size = 0;
[email protected]56285702013-12-04 18:22:494819 ASSERT_EQ(true, base::GetFileSize(path, &size));
[email protected]4356f0f2013-04-07 00:58:174820 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:444821
[email protected]7600d0b2013-12-08 21:43:304822 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:444823
[email protected]329b68b2012-11-14 17:54:274824 ASSERT_EQ(1, d.response_started_count())
4825 << "request failed: " << r.status().status()
4826 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444827
4828 EXPECT_FALSE(d.received_data_before_response());
4829
[email protected]329b68b2012-11-14 17:54:274830 EXPECT_EQ(size, d.bytes_received());
4831 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:444832 }
4833}
4834
[email protected]999dd8c2013-11-12 06:45:544835TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4836 ASSERT_TRUE(test_server_.Start());
4837
4838 TestDelegate d;
4839 {
4840 URLRequest r(test_server_.GetURL("echo"), DEFAULT_PRIORITY,
4841 &d, &default_context_);
4842 r.set_method("POST");
4843
4844 ScopedVector<UploadElementReader> element_readers;
4845
4846 element_readers.push_back(new UploadFileElementReader(
4847 base::MessageLoopProxy::current().get(),
4848 base::FilePath(FILE_PATH_LITERAL(
4849 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4850 0,
4851 kuint64max,
4852 base::Time()));
4853 r.set_upload(make_scoped_ptr(
4854 new UploadDataStream(element_readers.Pass(), 0)));
4855
4856 r.Start();
4857 EXPECT_TRUE(r.is_pending());
4858
4859 base::RunLoop().Run();
4860
[email protected]999dd8c2013-11-12 06:45:544861 EXPECT_TRUE(d.request_failed());
4862 EXPECT_FALSE(d.received_data_before_response());
4863 EXPECT_EQ(0, d.bytes_received());
4864 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
4865 EXPECT_EQ(ERR_FILE_NOT_FOUND, r.status().error());
[email protected]999dd8c2013-11-12 06:45:544866 }
4867}
4868
[email protected]316c1e5e2012-09-12 15:17:444869TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4870 ASSERT_TRUE(test_server_.Start());
4871
4872 TestDelegate d;
4873 {
[email protected]2ca01e52013-10-31 22:05:194874 URLRequest r(
4875 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444876 r.EnableChunkedUpload();
4877 r.set_method("POST");
4878 AddChunksToUpload(&r);
4879 r.Start();
4880 EXPECT_TRUE(r.is_pending());
4881
[email protected]255620da2013-08-19 13:14:294882 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444883
4884 VerifyReceivedDataMatchesChunks(&r, &d);
4885 }
4886}
4887
[email protected]329b68b2012-11-14 17:54:274888TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4889 ASSERT_TRUE(test_server_.Start());
4890
4891 TestDelegate d;
4892 {
[email protected]2ca01e52013-10-31 22:05:194893 URLRequest r(
4894 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]329b68b2012-11-14 17:54:274895 r.EnableChunkedUpload();
4896 r.set_method("POST");
4897 r.Start();
4898 EXPECT_TRUE(r.is_pending());
4899 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294900 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:274901
4902 VerifyReceivedDataMatchesChunks(&r, &d);
4903 }
4904}
4905
[email protected]316c1e5e2012-09-12 15:17:444906TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4907 ASSERT_TRUE(test_server_.Start());
4908
4909 TestDelegate d;
4910 {
[email protected]2ca01e52013-10-31 22:05:194911 URLRequest r(
4912 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444913 r.EnableChunkedUpload();
4914 r.set_method("POST");
4915 r.Start();
4916 EXPECT_TRUE(r.is_pending());
4917
[email protected]255620da2013-08-19 13:14:294918 base::RunLoop().RunUntilIdle();
[email protected]316c1e5e2012-09-12 15:17:444919 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294920 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444921
4922 VerifyReceivedDataMatchesChunks(&r, &d);
4923 }
4924}
4925
4926TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4927 ASSERT_TRUE(test_server_.Start());
4928
4929 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194930 URLRequest req(test_server_.GetURL("files/with-headers.html"),
4931 DEFAULT_PRIORITY,
4932 &d,
4933 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444934 req.Start();
[email protected]255620da2013-08-19 13:14:294935 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444936
4937 const HttpResponseHeaders* headers = req.response_headers();
4938
4939 // Simple sanity check that response_info() accesses the same data.
4940 EXPECT_EQ(headers, req.response_info().headers.get());
4941
4942 std::string header;
4943 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4944 EXPECT_EQ("private", header);
4945
4946 header.clear();
4947 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4948 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4949
4950 // The response has two "X-Multiple-Entries" headers.
4951 // This verfies our output has them concatenated together.
4952 header.clear();
4953 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4954 EXPECT_EQ("a, b", header);
4955}
4956
[email protected]242d8562012-10-30 21:20:464957TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:224958 SpawnedTestServer::SSLOptions ssl_options;
4959 SpawnedTestServer https_test_server(
4960 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:464961 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154962 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:464963 ASSERT_TRUE(https_test_server.Start());
4964
4965 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194966 URLRequest request(https_test_server.GetURL("files/hsts-headers.html"),
4967 DEFAULT_PRIORITY,
4968 &d,
4969 &default_context_);
[email protected]242d8562012-10-30 21:20:464970 request.Start();
[email protected]255620da2013-08-19 13:14:294971 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:464972
4973 TransportSecurityState* security_state =
4974 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:464975 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:264976 EXPECT_TRUE(security_state->GetDynamicDomainState(
4977 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:464978 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:264979 domain_state.sts.upgrade_mode);
4980 EXPECT_TRUE(domain_state.sts.include_subdomains);
4981 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:274982#if defined(OS_ANDROID)
4983 // Android's CertVerifyProc does not (yet) handle pins.
4984#else
4985 EXPECT_FALSE(domain_state.HasPublicKeyPins());
4986#endif
4987}
4988
4989// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
4990// reject HPKP headers, and a test setting only HPKP headers will fail (no
4991// DomainState present because header rejected).
4992#if defined(OS_ANDROID)
4993#define MAYBE_ProcessPKP DISABLED_ProcessPKP
4994#else
4995#define MAYBE_ProcessPKP ProcessPKP
4996#endif
4997
4998// Tests that enabling HPKP on a domain does not affect the HSTS
4999// validity/expiration.
5000TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5001 SpawnedTestServer::SSLOptions ssl_options;
5002 SpawnedTestServer https_test_server(
5003 SpawnedTestServer::TYPE_HTTPS,
5004 ssl_options,
5005 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5006 ASSERT_TRUE(https_test_server.Start());
5007
5008 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195009 URLRequest request(https_test_server.GetURL("files/hpkp-headers.html"),
5010 DEFAULT_PRIORITY,
5011 &d,
5012 &default_context_);
[email protected]37fd55fb2013-06-29 13:13:275013 request.Start();
[email protected]255620da2013-08-19 13:14:295014 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275015
5016 TransportSecurityState* security_state =
5017 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275018 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265019 EXPECT_TRUE(security_state->GetDynamicDomainState(
5020 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275021 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265022 domain_state.sts.upgrade_mode);
5023 EXPECT_FALSE(domain_state.sts.include_subdomains);
5024 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275025 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265026 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465027}
5028
5029TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:225030 SpawnedTestServer::SSLOptions ssl_options;
5031 SpawnedTestServer https_test_server(
5032 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465033 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155034 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465035 ASSERT_TRUE(https_test_server.Start());
5036
5037 TestDelegate d;
5038 URLRequest request(
5039 https_test_server.GetURL("files/hsts-multiple-headers.html"),
[email protected]2ca01e52013-10-31 22:05:195040 DEFAULT_PRIORITY,
[email protected]242d8562012-10-30 21:20:465041 &d,
5042 &default_context_);
5043 request.Start();
[email protected]255620da2013-08-19 13:14:295044 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465045
5046 // We should have set parameters from the first header, not the second.
5047 TransportSecurityState* security_state =
5048 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465049 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265050 EXPECT_TRUE(security_state->GetDynamicDomainState(
5051 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465052 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265053 domain_state.sts.upgrade_mode);
5054 EXPECT_FALSE(domain_state.sts.include_subdomains);
5055 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465056}
5057
[email protected]9f972ec2013-04-10 20:24:365058TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:225059 SpawnedTestServer::SSLOptions ssl_options;
5060 SpawnedTestServer https_test_server(
5061 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:365062 ssl_options,
5063 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5064 ASSERT_TRUE(https_test_server.Start());
5065
5066 TestDelegate d;
5067 URLRequest request(
5068 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
[email protected]2ca01e52013-10-31 22:05:195069 DEFAULT_PRIORITY,
[email protected]9f972ec2013-04-10 20:24:365070 &d,
5071 &default_context_);
5072 request.Start();
[email protected]255620da2013-08-19 13:14:295073 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365074
5075 // We should have set parameters from the first header, not the second.
5076 TransportSecurityState* security_state =
5077 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365078 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265079 EXPECT_TRUE(security_state->GetDynamicDomainState(
5080 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]9f972ec2013-04-10 20:24:365081 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265082 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365083#if defined(OS_ANDROID)
5084 // Android's CertVerifyProc does not (yet) handle pins.
5085#else
5086 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5087#endif
[email protected]9e6968d2014-05-07 21:46:265088 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365089
[email protected]a165f092013-06-12 16:10:055090 // Even though there is an HSTS header asserting includeSubdomains, it is
5091 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265092 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055093 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265094 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365095}
5096
[email protected]37fd55fb2013-06-29 13:13:275097// Tests that when multiple HPKP headers are present, asserting different
5098// policies, that only the first such policy is processed.
5099TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5100 SpawnedTestServer::SSLOptions ssl_options;
5101 SpawnedTestServer https_test_server(
5102 SpawnedTestServer::TYPE_HTTPS,
5103 ssl_options,
5104 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5105 ASSERT_TRUE(https_test_server.Start());
5106
5107 TestDelegate d;
5108 URLRequest request(
5109 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
[email protected]2ca01e52013-10-31 22:05:195110 DEFAULT_PRIORITY,
[email protected]37fd55fb2013-06-29 13:13:275111 &d,
5112 &default_context_);
5113 request.Start();
[email protected]255620da2013-08-19 13:14:295114 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275115
5116 TransportSecurityState* security_state =
5117 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275118 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265119 EXPECT_TRUE(security_state->GetDynamicDomainState(
5120 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275121 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265122 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275123#if defined(OS_ANDROID)
5124 // Android's CertVerifyProc does not (yet) handle pins.
5125#else
5126 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5127#endif
[email protected]9e6968d2014-05-07 21:46:265128 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275129
[email protected]9e6968d2014-05-07 21:46:265130 EXPECT_TRUE(domain_state.sts.include_subdomains);
5131 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275132}
5133
[email protected]316c1e5e2012-09-12 15:17:445134TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5135 ASSERT_TRUE(test_server_.Start());
5136
5137 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195138 URLRequest req(test_server_.GetURL("files/content-type-normalization.html"),
5139 DEFAULT_PRIORITY,
5140 &d,
5141 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445142 req.Start();
[email protected]255620da2013-08-19 13:14:295143 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445144
5145 std::string mime_type;
5146 req.GetMimeType(&mime_type);
5147 EXPECT_EQ("text/html", mime_type);
5148
5149 std::string charset;
5150 req.GetCharset(&charset);
5151 EXPECT_EQ("utf-8", charset);
5152 req.Cancel();
5153}
5154
[email protected]02494ec2014-05-07 15:05:295155TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345156 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345157 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345158 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025159 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345160
5161 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
[email protected]588614c22013-08-16 00:09:025162 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345163}
5164
[email protected]02494ec2014-05-07 15:05:295165#if !defined(DISABLE_FILE_SUPPORT)
5166TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5167 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5168 GURL file_url("file:///foo.txt");
5169 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5170 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5171
5172 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5173 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
5174}
5175
[email protected]588614c22013-08-16 00:09:025176TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445177 ASSERT_TRUE(test_server_.Start());
5178
5179 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195180 URLRequest req(test_server_.GetURL("files/redirect-to-file.html"),
5181 DEFAULT_PRIORITY,
5182 &d,
5183 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445184 req.Start();
[email protected]255620da2013-08-19 13:14:295185 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445186
5187 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5188 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5189}
[email protected]02494ec2014-05-07 15:05:295190#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445191
[email protected]588614c22013-08-16 00:09:025192TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5193 ASSERT_TRUE(test_server_.Start());
5194
5195 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195196 URLRequest req(test_server_.GetURL("files/redirect-to-data.html"),
5197 DEFAULT_PRIORITY,
5198 &d,
5199 &default_context_);
[email protected]588614c22013-08-16 00:09:025200 req.Start();
5201 base::MessageLoop::current()->Run();
5202
5203 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5204 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5205}
5206
[email protected]316c1e5e2012-09-12 15:17:445207TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5208 ASSERT_TRUE(test_server_.Start());
5209
5210 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195211 URLRequest req(test_server_.GetURL("files/redirect-to-invalid-url.html"),
5212 DEFAULT_PRIORITY,
5213 &d,
5214 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445215 req.Start();
[email protected]255620da2013-08-19 13:14:295216 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445217
5218 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5219 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
5220}
5221
[email protected]e50efea2014-03-24 18:41:005222// Make sure redirects are cached, despite not reading their bodies.
5223TEST_F(URLRequestTestHTTP, CacheRedirect) {
5224 ASSERT_TRUE(test_server_.Start());
5225 GURL redirect_url =
5226 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5227
5228 {
5229 TestDelegate d;
5230 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5231 req.Start();
5232 base::RunLoop().Run();
5233 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5234 EXPECT_EQ(1, d.received_redirect_count());
5235 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5236 }
5237
5238 {
5239 TestDelegate d;
5240 d.set_quit_on_redirect(true);
5241 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5242 req.Start();
5243 base::RunLoop().Run();
5244
5245 EXPECT_EQ(1, d.received_redirect_count());
5246 EXPECT_EQ(0, d.response_started_count());
5247 EXPECT_TRUE(req.was_cached());
5248
5249 req.FollowDeferredRedirect();
5250 base::RunLoop().Run();
5251 EXPECT_EQ(1, d.received_redirect_count());
5252 EXPECT_EQ(1, d.response_started_count());
5253 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5254 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5255 }
5256}
5257
5258// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5259// when the headers are read, since the body won't have been read.
5260TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5261 ASSERT_TRUE(test_server_.Start());
5262 // URL that is normally cached.
5263 GURL initial_url = test_server_.GetURL("cachetime");
5264
5265 {
5266 // Set up the TestNetworkDelegate tp force a redirect.
5267 GURL redirect_to_url = test_server_.GetURL("echo");
5268 default_network_delegate_.set_redirect_on_headers_received_url(
5269 redirect_to_url);
5270
5271 TestDelegate d;
5272 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5273 req.Start();
5274 base::RunLoop().Run();
5275 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5276 EXPECT_EQ(1, d.received_redirect_count());
5277 EXPECT_EQ(redirect_to_url, req.url());
5278 }
5279
5280 {
5281 TestDelegate d;
5282 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5283 req.Start();
5284 base::RunLoop().Run();
5285
5286 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5287 EXPECT_FALSE(req.was_cached());
5288 EXPECT_EQ(0, d.received_redirect_count());
5289 EXPECT_EQ(initial_url, req.url());
5290 }
5291}
5292
[email protected]5f714132014-03-26 10:41:165293// Tests that redirection to an unsafe URL is allowed when it has been marked as
5294// safe.
5295TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5296 ASSERT_TRUE(test_server_.Start());
5297
5298 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5299 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5300 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5301
5302 TestDelegate d;
5303 {
5304 URLRequest r(test_server_.GetURL("whatever"),
5305 DEFAULT_PRIORITY,
5306 &d,
5307 &default_context_);
5308
5309 r.Start();
5310 base::RunLoop().Run();
5311
5312 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5313
5314 EXPECT_EQ(2U, r.url_chain().size());
5315 EXPECT_EQ(net::OK, r.status().error());
5316 EXPECT_EQ(unsafe_url, r.url());
5317 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5318 }
5319}
5320
5321// Tests that a redirect to a different unsafe URL is blocked, even after adding
5322// some other URL to the whitelist.
5323TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5324 ASSERT_TRUE(test_server_.Start());
5325
5326 GURL unsafe_url("data:text/html,something");
5327 GURL different_unsafe_url("data:text/html,something-else");
5328 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5329 default_network_delegate_.set_allowed_unsafe_redirect_url(
5330 different_unsafe_url);
5331
5332 TestDelegate d;
5333 {
5334 URLRequest r(test_server_.GetURL("whatever"),
5335 DEFAULT_PRIORITY,
5336 &d,
5337 &default_context_);
5338
5339 r.Start();
5340 base::RunLoop().Run();
5341
5342 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
5343 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r.status().error());
5344 }
5345}
5346
[email protected]5f714132014-03-26 10:41:165347// Redirects from an URL with fragment to an unsafe URL with fragment should
5348// be allowed, and the reference fragment of the target URL should be preserved.
5349TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5350 ASSERT_TRUE(test_server_.Start());
5351
5352 GURL original_url(test_server_.GetURL("original#fragment1"));
5353 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5354 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5355
5356 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5357 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5358
5359 TestDelegate d;
5360 {
5361 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5362
5363 r.Start();
5364 base::RunLoop().Run();
5365
5366 EXPECT_EQ(2U, r.url_chain().size());
5367 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5368 EXPECT_EQ(net::OK, r.status().error());
5369 EXPECT_EQ(original_url, r.original_url());
5370 EXPECT_EQ(expected_url, r.url());
5371 }
5372}
5373
5374// When a delegate has specified a safe redirect URL, but it does not match the
5375// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145376TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165377 ASSERT_TRUE(test_server_.Start());
5378
5379 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5380 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5381 GURL redirect_url(test_server_.GetURL("target"));
5382 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5383
5384 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5385 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5386
5387 TestDelegate d;
5388 {
5389 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5390
5391 r.Start();
5392 base::RunLoop().Run();
5393
5394 EXPECT_EQ(2U, r.url_chain().size());
5395 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5396 EXPECT_EQ(net::OK, r.status().error());
5397 EXPECT_EQ(original_url, r.original_url());
5398 EXPECT_EQ(expected_redirect_url, r.url());
5399 }
5400}
5401
[email protected]f878230e2014-04-03 15:36:145402// When a delegate has specified a safe redirect URL, assume that the redirect
5403// URL should not be changed. In particular, the reference fragment should not
5404// be modified.
5405TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5406 ASSERT_TRUE(test_server_.Start());
5407
5408 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5409 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5410
5411 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5412 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5413
5414 TestDelegate d;
5415 {
5416 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5417
5418 r.Start();
5419 base::RunLoop().Run();
5420
5421 EXPECT_EQ(2U, r.url_chain().size());
5422 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5423 EXPECT_EQ(net::OK, r.status().error());
5424 EXPECT_EQ(original_url, r.original_url());
5425 EXPECT_EQ(redirect_url, r.url());
5426 }
5427}
5428
5429// When a URLRequestRedirectJob is created, the redirection must be followed and
5430// the reference fragment of the target URL must not be modified.
5431TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5432 ASSERT_TRUE(test_server_.Start());
5433
5434 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5435 GURL redirect_url(test_server_.GetURL("echo"));
5436
5437 TestDelegate d;
5438 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5439
5440 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5441 &r, &default_network_delegate_, redirect_url,
5442 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5443 AddTestInterceptor()->set_main_intercept_job(job);
5444
5445 r.Start();
5446 base::RunLoop().Run();
5447
5448 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5449 EXPECT_EQ(net::OK, r.status().error());
5450 EXPECT_EQ(original_url, r.original_url());
5451 EXPECT_EQ(redirect_url, r.url());
5452}
5453
[email protected]316c1e5e2012-09-12 15:17:445454TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5455 ASSERT_TRUE(test_server_.Start());
5456
5457 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195458 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5459 DEFAULT_PRIORITY,
5460 &d,
5461 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135462 req.SetReferrer("http://user:[email protected]/");
[email protected]316c1e5e2012-09-12 15:17:445463 req.Start();
[email protected]255620da2013-08-19 13:14:295464 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445465
5466 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5467}
5468
[email protected]99ecf6e2013-04-10 22:46:135469TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5470 ASSERT_TRUE(test_server_.Start());
5471
5472 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195473 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5474 DEFAULT_PRIORITY,
5475 &d,
5476 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135477 req.SetReferrer("http://foo.com/test#fragment");
5478 req.Start();
[email protected]255620da2013-08-19 13:14:295479 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135480
5481 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5482}
5483
5484TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5485 ASSERT_TRUE(test_server_.Start());
5486
5487 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195488 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5489 DEFAULT_PRIORITY,
5490 &d,
5491 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135492 req.SetReferrer("http://foo.com/test#fragment");
5493 req.SetReferrer("");
5494 req.Start();
[email protected]255620da2013-08-19 13:14:295495 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135496
5497 EXPECT_EQ(std::string("None"), d.data_received());
5498}
5499
[email protected]1826a402014-01-08 15:40:485500// Defer network start and then resume, checking that the request was a success
5501// and bytes were received.
5502TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5503 ASSERT_TRUE(test_server_.Start());
5504
5505 TestDelegate d;
5506 {
5507 d.set_quit_on_network_start(true);
5508 GURL test_url(test_server_.GetURL("echo"));
5509 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5510
5511 req.Start();
5512 base::RunLoop().Run();
5513
5514 EXPECT_EQ(1, d.received_before_network_start_count());
5515 EXPECT_EQ(0, d.response_started_count());
5516
5517 req.ResumeNetworkStart();
5518 base::RunLoop().Run();
5519
5520 EXPECT_EQ(1, d.response_started_count());
5521 EXPECT_NE(0, d.bytes_received());
5522 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5523 }
5524}
5525
5526// Check that OnBeforeNetworkStart is only called once even if there is a
5527// redirect.
5528TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5529 ASSERT_TRUE(test_server_.Start());
5530
5531 TestDelegate d;
5532 {
5533 d.set_quit_on_redirect(true);
5534 d.set_quit_on_network_start(true);
5535 URLRequest req(test_server_.GetURL("server-redirect?echo"),
5536 DEFAULT_PRIORITY,
5537 &d,
5538 &default_context_);
5539
5540 req.Start();
5541 base::RunLoop().Run();
5542
5543 EXPECT_EQ(1, d.received_before_network_start_count());
5544 EXPECT_EQ(0, d.response_started_count());
5545 EXPECT_EQ(0, d.received_redirect_count());
5546
5547 req.ResumeNetworkStart();
5548 base::RunLoop().Run();
5549
5550 EXPECT_EQ(1, d.received_redirect_count());
5551 req.FollowDeferredRedirect();
5552 base::RunLoop().Run();
5553
5554 // Check that the redirect's new network transaction does not get propagated
5555 // to a second OnBeforeNetworkStart() notification.
5556 EXPECT_EQ(1, d.received_before_network_start_count());
5557
5558 EXPECT_EQ(1, d.response_started_count());
5559 EXPECT_NE(0, d.bytes_received());
5560 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5561 }
5562}
5563
5564// Cancel the request after learning that the request would use the network.
5565TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5566 ASSERT_TRUE(test_server_.Start());
5567
5568 TestDelegate d;
5569 {
5570 d.set_quit_on_network_start(true);
5571 GURL test_url(test_server_.GetURL("echo"));
5572 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5573
5574 req.Start();
5575 base::RunLoop().Run();
5576
5577 EXPECT_EQ(1, d.received_before_network_start_count());
5578 EXPECT_EQ(0, d.response_started_count());
5579
5580 req.Cancel();
5581 base::RunLoop().Run();
5582
5583 EXPECT_EQ(1, d.response_started_count());
5584 EXPECT_EQ(0, d.bytes_received());
5585 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5586 }
5587}
5588
[email protected]316c1e5e2012-09-12 15:17:445589TEST_F(URLRequestTestHTTP, CancelRedirect) {
5590 ASSERT_TRUE(test_server_.Start());
5591
5592 TestDelegate d;
5593 {
5594 d.set_cancel_in_received_redirect(true);
[email protected]2ca01e52013-10-31 22:05:195595 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5596 DEFAULT_PRIORITY,
5597 &d,
5598 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445599 req.Start();
[email protected]255620da2013-08-19 13:14:295600 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445601
5602 EXPECT_EQ(1, d.response_started_count());
5603 EXPECT_EQ(0, d.bytes_received());
5604 EXPECT_FALSE(d.received_data_before_response());
5605 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5606 }
5607}
5608
5609TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5610 ASSERT_TRUE(test_server_.Start());
5611
5612 TestDelegate d;
5613 {
5614 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:045615 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]2ca01e52013-10-31 22:05:195616 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:045617
[email protected]316c1e5e2012-09-12 15:17:445618 req.Start();
[email protected]255620da2013-08-19 13:14:295619 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445620
5621 EXPECT_EQ(1, d.received_redirect_count());
5622
5623 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295624 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445625
5626 EXPECT_EQ(1, d.response_started_count());
5627 EXPECT_FALSE(d.received_data_before_response());
5628 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5629
[email protected]6cdfd7f2013-02-08 20:40:155630 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445631 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5632 path = path.Append(FILE_PATH_LITERAL("net"));
5633 path = path.Append(FILE_PATH_LITERAL("data"));
5634 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5635 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5636
5637 std::string contents;
[email protected]82f84b92013-08-30 18:23:505638 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:445639 EXPECT_EQ(contents, d.data_received());
5640 }
5641}
5642
[email protected]79e1fd62013-06-20 06:50:045643TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5644 ASSERT_TRUE(test_server_.Start());
5645
5646 TestDelegate d;
5647 {
5648 d.set_quit_on_redirect(true);
5649 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]2ca01e52013-10-31 22:05:195650 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:045651
5652 EXPECT_FALSE(d.have_full_request_headers());
5653
5654 req.Start();
[email protected]255620da2013-08-19 13:14:295655 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045656
5657 EXPECT_EQ(1, d.received_redirect_count());
5658 EXPECT_TRUE(d.have_full_request_headers());
5659 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5660 d.ClearFullRequestHeaders();
5661
5662 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295663 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045664
5665 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5666 EXPECT_EQ(1, d.response_started_count());
5667 EXPECT_TRUE(d.have_full_request_headers());
5668 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5669 EXPECT_FALSE(d.received_data_before_response());
5670 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5671
5672 base::FilePath path;
5673 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5674 path = path.Append(FILE_PATH_LITERAL("net"));
5675 path = path.Append(FILE_PATH_LITERAL("data"));
5676 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5677 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5678
5679 std::string contents;
[email protected]82f84b92013-08-30 18:23:505680 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:045681 EXPECT_EQ(contents, d.data_received());
5682 }
5683}
5684
[email protected]316c1e5e2012-09-12 15:17:445685TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5686 ASSERT_TRUE(test_server_.Start());
5687
5688 TestDelegate d;
5689 {
5690 d.set_quit_on_redirect(true);
[email protected]2ca01e52013-10-31 22:05:195691 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5692 DEFAULT_PRIORITY,
5693 &d,
5694 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445695 req.Start();
[email protected]255620da2013-08-19 13:14:295696 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445697
5698 EXPECT_EQ(1, d.received_redirect_count());
5699
5700 req.Cancel();
[email protected]255620da2013-08-19 13:14:295701 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445702
5703 EXPECT_EQ(1, d.response_started_count());
5704 EXPECT_EQ(0, d.bytes_received());
5705 EXPECT_FALSE(d.received_data_before_response());
5706 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5707 }
5708}
5709
5710TEST_F(URLRequestTestHTTP, VaryHeader) {
5711 ASSERT_TRUE(test_server_.Start());
5712
[email protected]3b23a222013-05-15 21:33:255713 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:445714 {
5715 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195716 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5717 DEFAULT_PRIORITY,
5718 &d,
5719 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445720 HttpRequestHeaders headers;
5721 headers.SetHeader("foo", "1");
5722 req.SetExtraRequestHeaders(headers);
5723 req.Start();
[email protected]255620da2013-08-19 13:14:295724 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:255725
5726 LoadTimingInfo load_timing_info;
5727 req.GetLoadTimingInfo(&load_timing_info);
5728 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445729 }
5730
[email protected]3b23a222013-05-15 21:33:255731 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:445732 {
5733 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195734 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5735 DEFAULT_PRIORITY,
5736 &d,
5737 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445738 HttpRequestHeaders headers;
5739 headers.SetHeader("foo", "1");
5740 req.SetExtraRequestHeaders(headers);
5741 req.Start();
[email protected]255620da2013-08-19 13:14:295742 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445743
5744 EXPECT_TRUE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255745
5746 LoadTimingInfo load_timing_info;
5747 req.GetLoadTimingInfo(&load_timing_info);
5748 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:445749 }
5750
[email protected]3b23a222013-05-15 21:33:255751 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:445752 {
5753 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195754 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5755 DEFAULT_PRIORITY,
5756 &d,
5757 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445758 HttpRequestHeaders headers;
5759 headers.SetHeader("foo", "2");
5760 req.SetExtraRequestHeaders(headers);
5761 req.Start();
[email protected]255620da2013-08-19 13:14:295762 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445763
5764 EXPECT_FALSE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255765
5766 LoadTimingInfo load_timing_info;
5767 req.GetLoadTimingInfo(&load_timing_info);
5768 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445769 }
5770}
5771
5772TEST_F(URLRequestTestHTTP, BasicAuth) {
5773 ASSERT_TRUE(test_server_.Start());
5774
5775 // populate the cache
5776 {
5777 TestDelegate d;
5778 d.set_credentials(AuthCredentials(kUser, kSecret));
5779
[email protected]2ca01e52013-10-31 22:05:195780 URLRequest r(test_server_.GetURL("auth-basic"),
5781 DEFAULT_PRIORITY,
5782 &d,
5783 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445784 r.Start();
5785
[email protected]255620da2013-08-19 13:14:295786 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445787
5788 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5789 }
5790
5791 // repeat request with end-to-end validation. since auth-basic results in a
5792 // cachable page, we expect this test to result in a 304. in which case, the
5793 // response should be fetched from the cache.
5794 {
5795 TestDelegate d;
5796 d.set_credentials(AuthCredentials(kUser, kSecret));
5797
[email protected]2ca01e52013-10-31 22:05:195798 URLRequest r(test_server_.GetURL("auth-basic"),
5799 DEFAULT_PRIORITY,
5800 &d,
5801 &default_context_);
[email protected]bb1c4662013-11-14 00:00:075802 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:445803 r.Start();
5804
[email protected]255620da2013-08-19 13:14:295805 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445806
5807 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5808
5809 // Should be the same cached document.
5810 EXPECT_TRUE(r.was_cached());
5811 }
5812}
5813
5814// Check that Set-Cookie headers in 401 responses are respected.
5815// http://crbug.com/6450
5816TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5817 ASSERT_TRUE(test_server_.Start());
5818
5819 GURL url_requiring_auth =
5820 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5821
5822 // Request a page that will give a 401 containing a Set-Cookie header.
5823 // Verify that when the transaction is restarted, it includes the new cookie.
5824 {
[email protected]ceefd7fd2012-11-29 00:36:245825 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445826 TestURLRequestContext context(true);
5827 context.set_network_delegate(&network_delegate);
5828 context.Init();
5829
5830 TestDelegate d;
5831 d.set_credentials(AuthCredentials(kUser, kSecret));
5832
[email protected]2ca01e52013-10-31 22:05:195833 URLRequest r(url_requiring_auth, DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445834 r.Start();
5835
[email protected]255620da2013-08-19 13:14:295836 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445837
5838 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5839
5840 // Make sure we sent the cookie in the restarted transaction.
5841 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5842 != std::string::npos);
5843 }
5844
5845 // Same test as above, except this time the restart is initiated earlier
5846 // (without user intervention since identity is embedded in the URL).
5847 {
[email protected]ceefd7fd2012-11-29 00:36:245848 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445849 TestURLRequestContext context(true);
5850 context.set_network_delegate(&network_delegate);
5851 context.Init();
5852
5853 TestDelegate d;
5854
5855 GURL::Replacements replacements;
5856 std::string username("user2");
5857 std::string password("secret");
5858 replacements.SetUsernameStr(username);
5859 replacements.SetPasswordStr(password);
5860 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5861
[email protected]2ca01e52013-10-31 22:05:195862 URLRequest r(url_with_identity, DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445863 r.Start();
5864
[email protected]255620da2013-08-19 13:14:295865 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445866
5867 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5868
5869 // Make sure we sent the cookie in the restarted transaction.
5870 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5871 != std::string::npos);
5872 }
5873}
5874
[email protected]58e32bb2013-01-21 18:23:255875// Tests that load timing works as expected with auth and the cache.
5876TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5877 ASSERT_TRUE(test_server_.Start());
5878
5879 // populate the cache
5880 {
5881 TestDelegate d;
5882 d.set_credentials(AuthCredentials(kUser, kSecret));
5883
[email protected]2ca01e52013-10-31 22:05:195884 URLRequest r(test_server_.GetURL("auth-basic"),
5885 DEFAULT_PRIORITY,
5886 &d,
5887 &default_context_);
[email protected]58e32bb2013-01-21 18:23:255888 r.Start();
5889
[email protected]255620da2013-08-19 13:14:295890 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255891
5892 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5893
5894 LoadTimingInfo load_timing_info_before_auth;
5895 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5896 &load_timing_info_before_auth));
5897 TestLoadTimingNotReused(load_timing_info_before_auth,
5898 CONNECT_TIMING_HAS_DNS_TIMES);
5899
5900 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175901 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255902 // The test server does not support keep alive sockets, so the second
5903 // request with auth should use a new socket.
5904 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5905 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5906 load_timing_info.socket_log_id);
5907 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5908 load_timing_info.connect_timing.connect_start);
5909 }
5910
[email protected]3b23a222013-05-15 21:33:255911 // Repeat request with end-to-end validation. Since auth-basic results in a
5912 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:255913 // response should be fetched from the cache.
5914 {
5915 TestDelegate d;
5916 d.set_credentials(AuthCredentials(kUser, kSecret));
5917
[email protected]2ca01e52013-10-31 22:05:195918 URLRequest r(test_server_.GetURL("auth-basic"),
5919 DEFAULT_PRIORITY,
5920 &d,
5921 &default_context_);
[email protected]bb1c4662013-11-14 00:00:075922 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]58e32bb2013-01-21 18:23:255923 r.Start();
5924
[email protected]255620da2013-08-19 13:14:295925 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255926
5927 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5928
5929 // Should be the same cached document.
5930 EXPECT_TRUE(r.was_cached());
5931
[email protected]3b23a222013-05-15 21:33:255932 // Since there was a request that went over the wire, the load timing
5933 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:255934 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175935 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255936 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:255937 }
5938}
5939
[email protected]316c1e5e2012-09-12 15:17:445940// In this test, we do a POST which the server will 302 redirect.
5941// The subsequent transaction should use GET, and should not send the
5942// Content-Type header.
5943// http://code.google.com/p/chromium/issues/detail?id=843
5944TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5945 ASSERT_TRUE(test_server_.Start());
5946
5947 const char kData[] = "hello world";
5948
5949 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195950 URLRequest req(test_server_.GetURL("files/redirect-to-echoall"),
5951 DEFAULT_PRIORITY,
5952 &d,
5953 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445954 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285955 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445956
5957 // Set headers (some of which are specific to the POST).
5958 HttpRequestHeaders headers;
5959 headers.AddHeadersFromString(
5960 "Content-Type: multipart/form-data; "
5961 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5962 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5963 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5964 "Accept-Language: en-US,en\r\n"
5965 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5966 "Content-Length: 11\r\n"
5967 "Origin: http://localhost:1337/");
5968 req.SetExtraRequestHeaders(headers);
5969 req.Start();
[email protected]255620da2013-08-19 13:14:295970 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445971
5972 std::string mime_type;
5973 req.GetMimeType(&mime_type);
5974 EXPECT_EQ("text/html", mime_type);
5975
5976 const std::string& data = d.data_received();
5977
5978 // Check that the post-specific headers were stripped:
5979 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
5980 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
5981 EXPECT_FALSE(ContainsString(data, "Origin:"));
5982
5983 // These extra request headers should not have been stripped.
5984 EXPECT_TRUE(ContainsString(data, "Accept:"));
5985 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
5986 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
5987}
5988
5989// The following tests check that we handle mutating the request method for
5990// HTTP redirects as expected.
5991// See http://crbug.com/56373 and http://crbug.com/102130.
5992
5993TEST_F(URLRequestTestHTTP, Redirect301Tests) {
5994 ASSERT_TRUE(test_server_.Start());
5995
5996 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
5997
5998 HTTPRedirectMethodTest(url, "POST", "GET", true);
5999 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6000 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6001}
6002
6003TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6004 ASSERT_TRUE(test_server_.Start());
6005
6006 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6007
6008 HTTPRedirectMethodTest(url, "POST", "GET", true);
6009 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6010 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6011}
6012
6013TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6014 ASSERT_TRUE(test_server_.Start());
6015
6016 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6017
6018 HTTPRedirectMethodTest(url, "POST", "GET", true);
6019 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6020 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6021}
6022
6023TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6024 ASSERT_TRUE(test_server_.Start());
6025
6026 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6027
6028 HTTPRedirectMethodTest(url, "POST", "POST", true);
6029 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6030 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6031}
6032
[email protected]0a17aab32014-04-24 03:32:376033TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6034 ASSERT_TRUE(test_server_.Start());
6035
6036 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6037
6038 HTTPRedirectMethodTest(url, "POST", "POST", true);
6039 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6040 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6041}
6042
6043// Make sure that 308 responses without bodies are not treated as redirects.
6044// Certain legacy apis that pre-date the response code expect this behavior
6045// (Like Google Drive).
6046TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6047 ASSERT_TRUE(test_server_.Start());
6048
6049 TestDelegate d;
6050 const GURL url = test_server_.GetURL("files/308-without-location-header");
6051
6052 URLRequest request(url, DEFAULT_PRIORITY, &d, &default_context_);
6053
6054 request.Start();
6055 base::RunLoop().Run();
6056 EXPECT_EQ(URLRequestStatus::SUCCESS, request.status().status());
6057 EXPECT_EQ(OK, request.status().error());
6058 EXPECT_EQ(0, d.received_redirect_count());
6059 EXPECT_EQ(308, request.response_headers()->response_code());
6060 EXPECT_EQ("This is not a redirect.", d.data_received());
6061}
6062
[email protected]f878230e2014-04-03 15:36:146063TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6064 ASSERT_TRUE(test_server_.Start());
6065
6066 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6067 GURL expected_url(test_server_.GetURL("echo#fragment"));
6068
6069 TestDelegate d;
6070 {
6071 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
6072
6073 r.Start();
6074 base::RunLoop().Run();
6075
6076 EXPECT_EQ(2U, r.url_chain().size());
6077 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
6078 EXPECT_EQ(net::OK, r.status().error());
6079 EXPECT_EQ(original_url, r.original_url());
6080 EXPECT_EQ(expected_url, r.url());
6081 }
6082}
6083
[email protected]316c1e5e2012-09-12 15:17:446084TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6085 ASSERT_TRUE(test_server_.Start());
6086
6087 const char kData[] = "hello world";
6088
6089 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196090 URLRequest req(test_server_.GetURL("empty.html"),
6091 DEFAULT_PRIORITY,
6092 &d,
6093 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446094 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:286095 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:446096 HttpRequestHeaders headers;
6097 headers.SetHeader(HttpRequestHeaders::kContentLength,
6098 base::UintToString(arraysize(kData) - 1));
6099 req.SetExtraRequestHeaders(headers);
6100
6101 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:416102 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096103 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446104 AddTestInterceptor()->set_main_intercept_job(job);
6105
6106 req.Start();
[email protected]255620da2013-08-19 13:14:296107 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446108 EXPECT_EQ("GET", req.method());
6109}
6110
6111TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6112 ASSERT_TRUE(test_server_.Start());
6113
6114 const char kData[] = "hello world";
6115
6116 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196117 URLRequest req(test_server_.GetURL("empty.html"),
6118 DEFAULT_PRIORITY,
6119 &d,
6120 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446121 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:286122 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:446123 HttpRequestHeaders headers;
6124 headers.SetHeader(HttpRequestHeaders::kContentLength,
6125 base::UintToString(arraysize(kData) - 1));
6126 req.SetExtraRequestHeaders(headers);
6127
6128 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:416129 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096130 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6131 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446132 AddTestInterceptor()->set_main_intercept_job(job);
6133
6134 req.Start();
[email protected]255620da2013-08-19 13:14:296135 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446136 EXPECT_EQ("POST", req.method());
6137 EXPECT_EQ(kData, d.data_received());
6138}
6139
6140// Check that default A-L header is sent.
6141TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6142 ASSERT_TRUE(test_server_.Start());
6143
[email protected]8790210c2013-12-02 05:29:536144 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246145 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446146 TestURLRequestContext context(true);
6147 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436148 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446149 context.Init();
6150
6151 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196152 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6153 DEFAULT_PRIORITY,
6154 &d,
6155 &context);
[email protected]316c1e5e2012-09-12 15:17:446156 req.Start();
[email protected]255620da2013-08-19 13:14:296157 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446158 EXPECT_EQ("en", d.data_received());
6159}
6160
6161// Check that an empty A-L header is not sent. http://crbug.com/77365.
6162TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6163 ASSERT_TRUE(test_server_.Start());
6164
[email protected]8790210c2013-12-02 05:29:536165 std::string empty_string; // Avoid most vexing parse on line below.
6166 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246167 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446168 TestURLRequestContext context(true);
6169 context.set_network_delegate(&network_delegate);
6170 context.Init();
6171 // We override the language after initialization because empty entries
6172 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436173 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446174
6175 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196176 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6177 DEFAULT_PRIORITY,
6178 &d,
6179 &context);
[email protected]316c1e5e2012-09-12 15:17:446180 req.Start();
[email protected]255620da2013-08-19 13:14:296181 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446182 EXPECT_EQ("None", d.data_received());
6183}
6184
6185// Check that if request overrides the A-L header, the default is not appended.
6186// See http://crbug.com/20894
6187TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6188 ASSERT_TRUE(test_server_.Start());
6189
6190 TestDelegate d;
6191 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
[email protected]2ca01e52013-10-31 22:05:196192 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446193 &d,
6194 &default_context_);
6195 HttpRequestHeaders headers;
6196 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6197 req.SetExtraRequestHeaders(headers);
6198 req.Start();
[email protected]255620da2013-08-19 13:14:296199 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446200 EXPECT_EQ(std::string("ru"), d.data_received());
6201}
6202
6203// Check that default A-E header is sent.
6204TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6205 ASSERT_TRUE(test_server_.Start());
6206
6207 TestDelegate d;
6208 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
[email protected]2ca01e52013-10-31 22:05:196209 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446210 &d,
6211 &default_context_);
6212 HttpRequestHeaders headers;
6213 req.SetExtraRequestHeaders(headers);
6214 req.Start();
[email protected]255620da2013-08-19 13:14:296215 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446216 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6217}
6218
6219// Check that if request overrides the A-E header, the default is not appended.
6220// See http://crbug.com/47381
6221TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6222 ASSERT_TRUE(test_server_.Start());
6223
6224 TestDelegate d;
6225 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
[email protected]2ca01e52013-10-31 22:05:196226 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446227 &d,
6228 &default_context_);
6229 HttpRequestHeaders headers;
6230 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6231 req.SetExtraRequestHeaders(headers);
6232 req.Start();
[email protected]255620da2013-08-19 13:14:296233 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446234 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6235 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6236}
6237
[email protected]84f05432013-03-15 01:00:126238// Check that setting the A-C header sends the proper header.
6239TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446240 ASSERT_TRUE(test_server_.Start());
6241
6242 TestDelegate d;
6243 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
[email protected]2ca01e52013-10-31 22:05:196244 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446245 &d,
6246 &default_context_);
6247 HttpRequestHeaders headers;
6248 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6249 req.SetExtraRequestHeaders(headers);
6250 req.Start();
[email protected]255620da2013-08-19 13:14:296251 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446252 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6253}
6254
6255// Check that default User-Agent header is sent.
6256TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6257 ASSERT_TRUE(test_server_.Start());
6258
6259 TestDelegate d;
6260 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
[email protected]2ca01e52013-10-31 22:05:196261 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446262 &d,
6263 &default_context_);
6264 req.Start();
[email protected]255620da2013-08-19 13:14:296265 base::RunLoop().Run();
[email protected]aa051272014-03-10 05:56:566266 EXPECT_EQ(req.context()->http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376267 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446268}
6269
6270// Check that if request overrides the User-Agent header,
6271// the default is not appended.
6272TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6273 ASSERT_TRUE(test_server_.Start());
6274
6275 TestDelegate d;
6276 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
[email protected]2ca01e52013-10-31 22:05:196277 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446278 &d,
6279 &default_context_);
6280 HttpRequestHeaders headers;
6281 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6282 req.SetExtraRequestHeaders(headers);
6283 req.Start();
[email protected]255620da2013-08-19 13:14:296284 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356285 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446286}
6287
[email protected]ee4c30d2012-11-07 15:08:436288// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6289// User-Agent header to be sent but does not send the Accept-Language and
6290// Accept-Charset headers.
6291TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6292 ASSERT_TRUE(test_server_.Start());
6293
[email protected]ceefd7fd2012-11-29 00:36:246294 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436295 TestURLRequestContext context(true);
6296 context.set_network_delegate(&network_delegate);
6297 context.Init();
6298 // We override the HttpUserAgentSettings after initialization because empty
6299 // entries get overridden by Init().
6300 context.set_http_user_agent_settings(NULL);
6301
6302 struct {
6303 const char* request;
6304 const char* expected_response;
6305 } tests[] = { { "echoheader?Accept-Language", "None" },
6306 { "echoheader?Accept-Charset", "None" },
6307 { "echoheader?User-Agent", "" } };
6308
6309 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
6310 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196311 URLRequest req(
6312 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, &context);
[email protected]ee4c30d2012-11-07 15:08:436313 req.Start();
[email protected]255620da2013-08-19 13:14:296314 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436315 EXPECT_EQ(tests[i].expected_response, d.data_received())
6316 << " Request = \"" << tests[i].request << "\"";
6317 }
6318}
6319
[email protected]5033ab82013-03-22 20:17:466320// Make sure that URLRequest passes on its priority updates to
6321// newly-created jobs after the first one.
6322TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6323 ASSERT_TRUE(test_server_.Start());
6324
6325 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196326 URLRequest req(test_server_.GetURL("empty.html"),
6327 DEFAULT_PRIORITY,
6328 &d,
6329 &default_context_);
[email protected]5033ab82013-03-22 20:17:466330 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
6331
6332 scoped_refptr<URLRequestRedirectJob> redirect_job =
6333 new URLRequestRedirectJob(
6334 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096335 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506336 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466337
6338 req.SetPriority(LOW);
6339 req.Start();
6340 EXPECT_TRUE(req.is_pending());
6341
6342 scoped_refptr<URLRequestTestJob> job =
6343 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506344 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466345
6346 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296347 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466348 EXPECT_EQ(LOW, job->priority());
6349}
6350
[email protected]80abdad2014-03-15 00:20:546351// Check that creating a network request while entering/exiting suspend mode
6352// fails as it should. This is the only case where an HttpTransactionFactory
6353// does not return an HttpTransaction.
6354TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6355 // Create a new HttpNetworkLayer that thinks it's suspended.
6356 HttpNetworkSession::Params params;
6357 params.host_resolver = default_context_.host_resolver();
6358 params.cert_verifier = default_context_.cert_verifier();
6359 params.transport_security_state = default_context_.transport_security_state();
6360 params.proxy_service = default_context_.proxy_service();
6361 params.ssl_config_service = default_context_.ssl_config_service();
6362 params.http_auth_handler_factory =
6363 default_context_.http_auth_handler_factory();
6364 params.network_delegate = &default_network_delegate_;
6365 params.http_server_properties = default_context_.http_server_properties();
6366 scoped_ptr<HttpNetworkLayer> network_layer(
6367 new HttpNetworkLayer(new HttpNetworkSession(params)));
6368 network_layer->OnSuspend();
6369
6370 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6371 HttpCache::DefaultBackend::InMemory(0));
6372
6373 TestURLRequestContext context(true);
6374 context.set_http_transaction_factory(&http_cache);
6375 context.Init();
6376
6377 TestDelegate d;
6378 URLRequest req(GURL("http://127.0.0.1/"),
6379 DEFAULT_PRIORITY,
6380 &d,
6381 &context);
6382 req.Start();
6383 base::RunLoop().Run();
6384
6385 EXPECT_TRUE(d.request_failed());
6386 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6387 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6388}
6389
6390// Check that creating a network request while entering/exiting suspend mode
6391// fails as it should in the case there is no cache. This is the only case
6392// where an HttpTransactionFactory does not return an HttpTransaction.
6393TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6394 // Create a new HttpNetworkLayer that thinks it's suspended.
6395 HttpNetworkSession::Params params;
6396 params.host_resolver = default_context_.host_resolver();
6397 params.cert_verifier = default_context_.cert_verifier();
6398 params.transport_security_state = default_context_.transport_security_state();
6399 params.proxy_service = default_context_.proxy_service();
6400 params.ssl_config_service = default_context_.ssl_config_service();
6401 params.http_auth_handler_factory =
6402 default_context_.http_auth_handler_factory();
6403 params.network_delegate = &default_network_delegate_;
6404 params.http_server_properties = default_context_.http_server_properties();
6405 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6406 network_layer.OnSuspend();
6407
6408 TestURLRequestContext context(true);
6409 context.set_http_transaction_factory(&network_layer);
6410 context.Init();
6411
6412 TestDelegate d;
6413 URLRequest req(GURL("http://127.0.0.1/"),
6414 DEFAULT_PRIORITY,
6415 &d,
6416 &context);
6417 req.Start();
6418 base::RunLoop().Run();
6419
6420 EXPECT_TRUE(d.request_failed());
6421 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6422 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6423}
6424
[email protected]73e0bba2009-02-19 22:57:096425class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:506426 public:
[email protected]ef2bf422012-05-11 03:27:096427 HTTPSRequestTest() : default_context_(true) {
6428 default_context_.set_network_delegate(&default_network_delegate_);
6429 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:506430 }
6431 virtual ~HTTPSRequestTest() {}
6432
6433 protected:
[email protected]ceefd7fd2012-11-29 00:36:246434 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:096435 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:466436};
6437
[email protected]c044616e2013-02-20 02:01:266438TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226439 SpawnedTestServer test_server(
6440 SpawnedTestServer::TYPE_HTTPS,
6441 SpawnedTestServer::kLocalhost,
6442 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116443 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:466444
[email protected]ea224582008-12-07 20:25:466445 TestDelegate d;
6446 {
[email protected]2ca01e52013-10-31 22:05:196447 URLRequest r(test_server.GetURL(std::string()),
6448 DEFAULT_PRIORITY,
6449 &d,
6450 &default_context_);
[email protected]ea224582008-12-07 20:25:466451 r.Start();
6452 EXPECT_TRUE(r.is_pending());
6453
[email protected]255620da2013-08-19 13:14:296454 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:466455
6456 EXPECT_EQ(1, d.response_started_count());
6457 EXPECT_FALSE(d.received_data_before_response());
6458 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176459 CheckSSLInfo(r.ssl_info());
[email protected]6d81b482011-02-22 19:47:196460 EXPECT_EQ(test_server.host_port_pair().host(),
6461 r.GetSocketAddress().host());
6462 EXPECT_EQ(test_server.host_port_pair().port(),
6463 r.GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:466464 }
[email protected]ea224582008-12-07 20:25:466465}
6466
[email protected]5774ada2010-07-15 06:30:546467TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226468 SpawnedTestServer::SSLOptions ssl_options(
6469 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6470 SpawnedTestServer test_server(
6471 SpawnedTestServer::TYPE_HTTPS,
6472 ssl_options,
6473 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116474 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:336475
6476 bool err_allowed = true;
6477 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6478 TestDelegate d;
6479 {
6480 d.set_allow_certificate_errors(err_allowed);
[email protected]2ca01e52013-10-31 22:05:196481 URLRequest r(test_server.GetURL(std::string()),
6482 DEFAULT_PRIORITY,
6483 &d,
6484 &default_context_);
[email protected]bacff652009-03-31 17:50:336485
6486 r.Start();
6487 EXPECT_TRUE(r.is_pending());
6488
[email protected]255620da2013-08-19 13:14:296489 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:336490
6491 EXPECT_EQ(1, d.response_started_count());
6492 EXPECT_FALSE(d.received_data_before_response());
6493 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:176494 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:336495 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176496 CheckSSLInfo(r.ssl_info());
6497 } else {
[email protected]bacff652009-03-31 17:50:336498 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176499 }
[email protected]bacff652009-03-31 17:50:336500 }
6501 }
6502}
6503
[email protected]5774ada2010-07-15 06:30:546504TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226505 SpawnedTestServer::SSLOptions ssl_options(
6506 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6507 SpawnedTestServer test_server(
6508 SpawnedTestServer::TYPE_HTTPS,
6509 ssl_options,
6510 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116511 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:336512
6513 // Iterate from false to true, just so that we do the opposite of the
6514 // previous test in order to increase test coverage.
6515 bool err_allowed = false;
6516 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6517 TestDelegate d;
6518 {
6519 d.set_allow_certificate_errors(err_allowed);
[email protected]2ca01e52013-10-31 22:05:196520 URLRequest r(test_server.GetURL(std::string()),
6521 DEFAULT_PRIORITY,
6522 &d,
6523 &default_context_);
[email protected]bacff652009-03-31 17:50:336524
6525 r.Start();
6526 EXPECT_TRUE(r.is_pending());
6527
[email protected]255620da2013-08-19 13:14:296528 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:336529
6530 EXPECT_EQ(1, d.response_started_count());
6531 EXPECT_FALSE(d.received_data_before_response());
6532 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:176533 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:336534 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176535 CheckSSLInfo(r.ssl_info());
6536 } else {
[email protected]bacff652009-03-31 17:50:336537 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176538 }
[email protected]bacff652009-03-31 17:50:336539 }
6540 }
6541}
[email protected]73e0bba2009-02-19 22:57:096542
[email protected]316c1e5e2012-09-12 15:17:446543// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
6544// than necessary.
6545TEST_F(HTTPSRequestTest, TLSv1Fallback) {
[email protected]316c1e5e2012-09-12 15:17:446546 // The OpenSSL library in use may not support TLS 1.1.
6547#if !defined(USE_OPENSSL)
[email protected]c091d3602014-03-24 02:32:486548 EXPECT_GT(kDefaultSSLVersionMax, SSL_PROTOCOL_VERSION_TLS1);
[email protected]316c1e5e2012-09-12 15:17:446549#endif
[email protected]c091d3602014-03-24 02:32:486550 if (kDefaultSSLVersionMax <= SSL_PROTOCOL_VERSION_TLS1)
[email protected]316c1e5e2012-09-12 15:17:446551 return;
6552
[email protected]ce7d0cbc2013-05-03 18:57:226553 SpawnedTestServer::SSLOptions ssl_options(
6554 SpawnedTestServer::SSLOptions::CERT_OK);
[email protected]316c1e5e2012-09-12 15:17:446555 ssl_options.tls_intolerant =
[email protected]ce7d0cbc2013-05-03 18:57:226556 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
6557 SpawnedTestServer test_server(
6558 SpawnedTestServer::TYPE_HTTPS,
6559 ssl_options,
6560 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446561 ASSERT_TRUE(test_server.Start());
6562
6563 TestDelegate d;
6564 TestURLRequestContext context(true);
6565 context.Init();
6566 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:196567 URLRequest r(
6568 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:446569 r.Start();
6570
[email protected]255620da2013-08-19 13:14:296571 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446572
6573 EXPECT_EQ(1, d.response_started_count());
6574 EXPECT_NE(0, d.bytes_received());
6575 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
6576 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6577 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6578}
6579
[email protected]974fbdfb2013-12-11 20:16:136580// Tests that we don't fallback with servers that implement TLS_FALLBACK_SCSV.
6581#if defined(USE_OPENSSL)
6582TEST_F(HTTPSRequestTest, DISABLED_FallbackSCSV) {
6583#else
6584TEST_F(HTTPSRequestTest, FallbackSCSV) {
6585#endif
6586 SpawnedTestServer::SSLOptions ssl_options(
6587 SpawnedTestServer::SSLOptions::CERT_OK);
6588 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
6589 // a version fallback.
6590 ssl_options.tls_intolerant =
6591 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6592 // Have the server process TLS_FALLBACK_SCSV so that version fallback
6593 // connections are rejected.
6594 ssl_options.fallback_scsv_enabled = true;
6595
6596 SpawnedTestServer test_server(
6597 SpawnedTestServer::TYPE_HTTPS,
6598 ssl_options,
6599 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6600 ASSERT_TRUE(test_server.Start());
6601
6602 TestDelegate d;
6603 TestURLRequestContext context(true);
6604 context.Init();
6605 d.set_allow_certificate_errors(true);
6606 URLRequest r(
6607 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6608 r.Start();
6609
6610 base::RunLoop().Run();
6611
6612 EXPECT_EQ(1, d.response_started_count());
6613 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
6614 // intolerance. If the fallback SCSV is processed when the original error
6615 // that caused the fallback should be returned, which should be
6616 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
6617 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, r.status().error());
6618}
6619
[email protected]316c1e5e2012-09-12 15:17:446620// This tests that a load of www.google.com with a certificate error sets
6621// the |certificate_errors_are_fatal| flag correctly. This flag will cause
6622// the interstitial to be fatal.
6623TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226624 SpawnedTestServer::SSLOptions ssl_options(
6625 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6626 SpawnedTestServer test_server(
6627 SpawnedTestServer::TYPE_HTTPS,
6628 ssl_options,
6629 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446630 ASSERT_TRUE(test_server.Start());
6631
6632 // We require that the URL be www.google.com in order to pick up the
6633 // preloaded HSTS entries in the TransportSecurityState. This means that we
6634 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:246635 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:446636
6637 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:246638 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446639 TestURLRequestContext context(true);
6640 context.set_network_delegate(&network_delegate);
6641 context.set_host_resolver(&host_resolver);
6642 TransportSecurityState transport_security_state;
6643 context.set_transport_security_state(&transport_security_state);
6644 context.Init();
6645
6646 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:046647 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6648 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196649 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446650 &d,
6651 &context);
6652
6653 r.Start();
6654 EXPECT_TRUE(r.is_pending());
6655
[email protected]255620da2013-08-19 13:14:296656 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446657
6658 EXPECT_EQ(1, d.response_started_count());
6659 EXPECT_FALSE(d.received_data_before_response());
6660 EXPECT_TRUE(d.have_certificate_errors());
6661 EXPECT_TRUE(d.certificate_errors_are_fatal());
6662}
6663
6664// This tests that cached HTTPS page loads do not cause any updates to the
6665// TransportSecurityState.
6666TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6667 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6668 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:226669 SpawnedTestServer::SSLOptions ssl_options(
6670 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6671 SpawnedTestServer test_server(
6672 SpawnedTestServer::TYPE_HTTPS,
6673 ssl_options,
6674 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446675 ASSERT_TRUE(test_server.Start());
6676
[email protected]9e6968d2014-05-07 21:46:266677 // We require that the URL be www.google.com in order to pick up the static
6678 // and dynamic STS and PKP entries in the TransportSecurityState. This means
6679 // that we have to use a MockHostResolver in order to direct www.google.com to
6680 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:446681
6682 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:246683 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446684 TestURLRequestContext context(true);
6685 context.set_network_delegate(&network_delegate);
6686 context.set_host_resolver(&host_resolver);
6687 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:266688
6689 TransportSecurityState::DomainState static_domain_state;
6690 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6691 "www.google.com", true, &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:446692 context.set_transport_security_state(&transport_security_state);
6693 context.Init();
6694
[email protected]9e6968d2014-05-07 21:46:266695 TransportSecurityState::DomainState dynamic_domain_state;
6696 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6697 "www.google.com", &dynamic_domain_state));
6698
[email protected]316c1e5e2012-09-12 15:17:446699 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:046700 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6701 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196702 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446703 &d,
6704 &context);
6705
6706 r.Start();
6707 EXPECT_TRUE(r.is_pending());
6708
[email protected]255620da2013-08-19 13:14:296709 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446710
6711 EXPECT_EQ(1, d.response_started_count());
6712 EXPECT_FALSE(d.received_data_before_response());
6713 EXPECT_TRUE(d.have_certificate_errors());
6714 EXPECT_TRUE(d.certificate_errors_are_fatal());
6715
[email protected]9e6968d2014-05-07 21:46:266716 // Get a fresh copy of the states, and check that they haven't changed.
6717 TransportSecurityState::DomainState new_static_domain_state;
6718 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6719 "www.google.com", true, &new_static_domain_state));
6720 TransportSecurityState::DomainState new_dynamic_domain_state;
6721 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6722 "www.google.com", &new_dynamic_domain_state));
6723
6724 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
6725 static_domain_state.sts.upgrade_mode);
6726 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
6727 static_domain_state.sts.include_subdomains);
6728 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
6729 static_domain_state.pkp.include_subdomains);
6730 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
6731 static_domain_state.pkp.spki_hashes));
6732 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
6733 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:446734}
6735
[email protected]8ccc69f2012-11-28 19:52:146736// Make sure HSTS preserves a POST request's method and body.
6737TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6738 static const char kData[] = "hello world";
6739
[email protected]ce7d0cbc2013-05-03 18:57:226740 SpawnedTestServer::SSLOptions ssl_options(
6741 SpawnedTestServer::SSLOptions::CERT_OK);
6742 SpawnedTestServer test_server(
6743 SpawnedTestServer::TYPE_HTTPS,
6744 ssl_options,
6745 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:146746 ASSERT_TRUE(test_server.Start());
6747
6748
6749 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6750 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:226751 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6752 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:146753 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:146754
6755 // Force https for www.somewhere.com.
6756 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:206757 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6758 bool include_subdomains = false;
6759 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6760 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:146761
6762 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6763
6764 TestURLRequestContext context(true);
6765 context.set_host_resolver(&host_resolver);
6766 context.set_transport_security_state(&transport_security_state);
6767 context.set_network_delegate(&network_delegate);
6768 context.Init();
6769
6770 TestDelegate d;
6771 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6772 // cause a certificate error. Ignore the error.
6773 d.set_allow_certificate_errors(true);
6774
[email protected]7d3cbc92013-03-18 22:33:046775 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6776 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196777 DEFAULT_PRIORITY,
[email protected]8ccc69f2012-11-28 19:52:146778 &d,
6779 &context);
6780 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:286781 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]8ccc69f2012-11-28 19:52:146782
6783 req.Start();
[email protected]255620da2013-08-19 13:14:296784 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:146785
6786 EXPECT_EQ("https", req.url().scheme());
6787 EXPECT_EQ("POST", req.method());
6788 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:406789
6790 LoadTimingInfo load_timing_info;
6791 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6792 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6793 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:146794}
6795
[email protected]316c1e5e2012-09-12 15:17:446796TEST_F(HTTPSRequestTest, SSLv3Fallback) {
[email protected]ce7d0cbc2013-05-03 18:57:226797 SpawnedTestServer::SSLOptions ssl_options(
6798 SpawnedTestServer::SSLOptions::CERT_OK);
6799 ssl_options.tls_intolerant =
6800 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6801 SpawnedTestServer test_server(
6802 SpawnedTestServer::TYPE_HTTPS,
6803 ssl_options,
6804 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446805 ASSERT_TRUE(test_server.Start());
6806
6807 TestDelegate d;
6808 TestURLRequestContext context(true);
6809 context.Init();
6810 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:196811 URLRequest r(
6812 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:446813 r.Start();
6814
[email protected]255620da2013-08-19 13:14:296815 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446816
6817 EXPECT_EQ(1, d.response_started_count());
6818 EXPECT_NE(0, d.bytes_received());
6819 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
6820 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6821 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6822}
6823
6824namespace {
6825
6826class SSLClientAuthTestDelegate : public TestDelegate {
6827 public:
6828 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6829 }
6830 virtual void OnCertificateRequested(
6831 URLRequest* request,
[email protected]46fadfd2013-02-06 09:40:166832 SSLCertRequestInfo* cert_request_info) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:446833 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:346834 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:446835 }
6836 int on_certificate_requested_count() {
6837 return on_certificate_requested_count_;
6838 }
6839 private:
6840 int on_certificate_requested_count_;
6841};
6842
6843} // namespace
6844
6845// TODO(davidben): Test the rest of the code. Specifically,
6846// - Filtering which certificates to select.
6847// - Sending a certificate back.
6848// - Getting a certificate request in an SSL renegotiation sending the
6849// HTTP request.
6850TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226851 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446852 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:226853 SpawnedTestServer test_server(
6854 SpawnedTestServer::TYPE_HTTPS,
6855 ssl_options,
6856 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446857 ASSERT_TRUE(test_server.Start());
6858
6859 SSLClientAuthTestDelegate d;
6860 {
[email protected]2ca01e52013-10-31 22:05:196861 URLRequest r(test_server.GetURL(std::string()),
6862 DEFAULT_PRIORITY,
6863 &d,
6864 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446865
6866 r.Start();
6867 EXPECT_TRUE(r.is_pending());
6868
[email protected]255620da2013-08-19 13:14:296869 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446870
6871 EXPECT_EQ(1, d.on_certificate_requested_count());
6872 EXPECT_FALSE(d.received_data_before_response());
6873 EXPECT_EQ(0, d.bytes_received());
6874
6875 // Send no certificate.
6876 // TODO(davidben): Get temporary client cert import (with keys) working on
6877 // all platforms so we can test sending a cert as well.
6878 r.ContinueWithCertificate(NULL);
6879
[email protected]255620da2013-08-19 13:14:296880 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446881
6882 EXPECT_EQ(1, d.response_started_count());
6883 EXPECT_FALSE(d.received_data_before_response());
6884 EXPECT_NE(0, d.bytes_received());
6885 }
6886}
6887
6888TEST_F(HTTPSRequestTest, ResumeTest) {
6889 // Test that we attempt a session resume when making two connections to the
6890 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:226891 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446892 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:226893 SpawnedTestServer test_server(
6894 SpawnedTestServer::TYPE_HTTPS,
6895 ssl_options,
6896 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446897 ASSERT_TRUE(test_server.Start());
6898
6899 SSLClientSocket::ClearSessionCache();
6900
6901 {
6902 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196903 URLRequest r(test_server.GetURL("ssl-session-cache"),
6904 DEFAULT_PRIORITY,
6905 &d,
6906 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446907
6908 r.Start();
6909 EXPECT_TRUE(r.is_pending());
6910
[email protected]255620da2013-08-19 13:14:296911 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446912
6913 EXPECT_EQ(1, d.response_started_count());
6914 }
6915
6916 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6917 CloseAllConnections();
6918
6919 {
6920 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196921 URLRequest r(test_server.GetURL("ssl-session-cache"),
6922 DEFAULT_PRIORITY,
6923 &d,
6924 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446925
6926 r.Start();
6927 EXPECT_TRUE(r.is_pending());
6928
[email protected]255620da2013-08-19 13:14:296929 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446930
6931 // The response will look like;
6932 // insert abc
6933 // lookup abc
6934 // insert xyz
6935 //
6936 // With a newline at the end which makes the split think that there are
6937 // four lines.
6938
6939 EXPECT_EQ(1, d.response_started_count());
6940 std::vector<std::string> lines;
6941 base::SplitString(d.data_received(), '\n', &lines);
6942 ASSERT_EQ(4u, lines.size()) << d.data_received();
6943
6944 std::string session_id;
6945
6946 for (size_t i = 0; i < 2; i++) {
6947 std::vector<std::string> parts;
6948 base::SplitString(lines[i], '\t', &parts);
6949 ASSERT_EQ(2u, parts.size());
6950 if (i == 0) {
6951 EXPECT_EQ("insert", parts[0]);
6952 session_id = parts[1];
6953 } else {
6954 EXPECT_EQ("lookup", parts[0]);
6955 EXPECT_EQ(session_id, parts[1]);
6956 }
6957 }
6958 }
6959}
6960
6961TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6962 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6963 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:226964 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446965 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:226966 SpawnedTestServer test_server(
6967 SpawnedTestServer::TYPE_HTTPS,
6968 ssl_options,
6969 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446970 ASSERT_TRUE(test_server.Start());
6971
6972 SSLClientSocket::ClearSessionCache();
6973
6974 {
6975 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196976 URLRequest r(test_server.GetURL("ssl-session-cache"),
6977 DEFAULT_PRIORITY,
6978 &d,
6979 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446980
6981 r.Start();
6982 EXPECT_TRUE(r.is_pending());
6983
[email protected]255620da2013-08-19 13:14:296984 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446985
6986 EXPECT_EQ(1, d.response_started_count());
6987 }
6988
6989 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6990 HttpNetworkSession::Params params;
6991 params.host_resolver = default_context_.host_resolver();
6992 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:116993 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:446994 params.proxy_service = default_context_.proxy_service();
6995 params.ssl_config_service = default_context_.ssl_config_service();
6996 params.http_auth_handler_factory =
6997 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:416998 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:446999 params.http_server_properties = default_context_.http_server_properties();
7000 params.ssl_session_cache_shard = "alternate";
7001
7002 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
7003 new net::HttpNetworkSession(params),
7004 net::HttpCache::DefaultBackend::InMemory(0)));
7005
7006 default_context_.set_http_transaction_factory(cache.get());
7007
7008 {
7009 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:197010 URLRequest r(test_server.GetURL("ssl-session-cache"),
7011 DEFAULT_PRIORITY,
7012 &d,
7013 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:447014
7015 r.Start();
7016 EXPECT_TRUE(r.is_pending());
7017
[email protected]255620da2013-08-19 13:14:297018 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447019
7020 // The response will look like;
7021 // insert abc
7022 // insert xyz
7023 //
7024 // With a newline at the end which makes the split think that there are
7025 // three lines.
7026
7027 EXPECT_EQ(1, d.response_started_count());
7028 std::vector<std::string> lines;
7029 base::SplitString(d.data_received(), '\n', &lines);
7030 ASSERT_EQ(3u, lines.size());
7031
7032 std::string session_id;
7033 for (size_t i = 0; i < 2; i++) {
7034 std::vector<std::string> parts;
7035 base::SplitString(lines[i], '\t', &parts);
7036 ASSERT_EQ(2u, parts.size());
7037 EXPECT_EQ("insert", parts[0]);
7038 if (i == 0) {
7039 session_id = parts[1];
7040 } else {
7041 EXPECT_NE(session_id, parts[1]);
7042 }
7043 }
7044 }
7045}
7046
[email protected]a8fed1742013-12-27 02:14:247047class HTTPSSessionTest : public testing::Test {
7048 public:
7049 HTTPSSessionTest() : default_context_(true) {
7050 cert_verifier_.set_default_result(net::OK);
7051
7052 default_context_.set_network_delegate(&default_network_delegate_);
7053 default_context_.set_cert_verifier(&cert_verifier_);
7054 default_context_.Init();
7055 }
7056 virtual ~HTTPSSessionTest() {}
7057
7058 protected:
7059 MockCertVerifier cert_verifier_;
7060 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7061 TestURLRequestContext default_context_;
7062};
7063
7064// Tests that session resumption is not attempted if an invalid certificate
7065// is presented.
7066TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7067 SpawnedTestServer::SSLOptions ssl_options;
7068 ssl_options.record_resume = true;
7069 SpawnedTestServer test_server(
7070 SpawnedTestServer::TYPE_HTTPS,
7071 ssl_options,
7072 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7073 ASSERT_TRUE(test_server.Start());
7074
7075 SSLClientSocket::ClearSessionCache();
7076
7077 // Simulate the certificate being expired and attempt a connection.
7078 cert_verifier_.set_default_result(net::ERR_CERT_DATE_INVALID);
7079 {
7080 TestDelegate d;
7081 URLRequest r(test_server.GetURL("ssl-session-cache"),
7082 DEFAULT_PRIORITY,
7083 &d,
7084 &default_context_);
7085
7086 r.Start();
7087 EXPECT_TRUE(r.is_pending());
7088
7089 base::RunLoop().Run();
7090
7091 EXPECT_EQ(1, d.response_started_count());
7092 }
7093
7094 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7095 CloseAllConnections();
7096
7097 // Now change the certificate to be acceptable (so that the response is
7098 // loaded), and ensure that no session id is presented to the peer.
7099 cert_verifier_.set_default_result(net::OK);
7100 {
7101 TestDelegate d;
7102 URLRequest r(test_server.GetURL("ssl-session-cache"),
7103 DEFAULT_PRIORITY,
7104 &d,
7105 &default_context_);
7106
7107 r.Start();
7108 EXPECT_TRUE(r.is_pending());
7109
7110 base::RunLoop().Run();
7111
7112 // The response will look like;
7113 // insert abc
7114 // insert xyz
7115 //
7116 // With a newline at the end which makes the split think that there are
7117 // three lines.
7118 //
7119 // If a session was presented (eg: a bug), then the response would look
7120 // like;
7121 // insert abc
7122 // lookup abc
7123 // insert xyz
7124
7125 EXPECT_EQ(1, d.response_started_count());
7126 std::vector<std::string> lines;
7127 base::SplitString(d.data_received(), '\n', &lines);
7128 ASSERT_EQ(3u, lines.size()) << d.data_received();
7129
7130 std::string session_id;
7131 for (size_t i = 0; i < 2; i++) {
7132 std::vector<std::string> parts;
7133 base::SplitString(lines[i], '\t', &parts);
7134 ASSERT_EQ(2u, parts.size());
7135 EXPECT_EQ("insert", parts[0]);
7136 if (i == 0) {
7137 session_id = parts[1];
7138 } else {
7139 EXPECT_NE(session_id, parts[1]);
7140 }
7141 }
7142 }
7143}
7144
[email protected]a13234c2012-03-20 21:45:027145class TestSSLConfigService : public SSLConfigService {
[email protected]dffe8242012-03-20 15:14:277146 public:
[email protected]3a86a712013-07-30 07:16:207147 TestSSLConfigService(bool ev_enabled,
7148 bool online_rev_checking,
7149 bool rev_checking_required_local_anchors)
[email protected]a13234c2012-03-20 21:45:027150 : ev_enabled_(ev_enabled),
[email protected]3a86a712013-07-30 07:16:207151 online_rev_checking_(online_rev_checking),
7152 rev_checking_required_local_anchors_(
7153 rev_checking_required_local_anchors) {}
[email protected]a13234c2012-03-20 21:45:027154
[email protected]a9813302012-04-28 09:29:287155 // SSLConfigService:
7156 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
[email protected]dffe8242012-03-20 15:14:277157 *config = SSLConfig();
[email protected]a13234c2012-03-20 21:45:027158 config->rev_checking_enabled = online_rev_checking_;
7159 config->verify_ev_cert = ev_enabled_;
[email protected]3a86a712013-07-30 07:16:207160 config->rev_checking_required_local_anchors =
7161 rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:277162 }
[email protected]a13234c2012-03-20 21:45:027163
[email protected]a9813302012-04-28 09:29:287164 protected:
7165 virtual ~TestSSLConfigService() {}
7166
[email protected]a13234c2012-03-20 21:45:027167 private:
7168 const bool ev_enabled_;
7169 const bool online_rev_checking_;
[email protected]3a86a712013-07-30 07:16:207170 const bool rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:277171};
7172
7173// This the fingerprint of the "Testing CA" certificate used by the testserver.
7174// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:267175static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:277176 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7177 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7178
[email protected]51523f52013-07-31 21:57:287179// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7180// testserver.
7181static const SHA256HashValue kOCSPTestCertSPKI = { {
7182 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7183 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7184 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7185 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7186} };
7187
[email protected]dffe8242012-03-20 15:14:277188// This is the policy OID contained in the certificates that testserver
7189// generates.
7190static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
7191
7192class HTTPSOCSPTest : public HTTPSRequestTest {
7193 public:
7194 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:097195 : context_(true),
[email protected]b6f2de32012-08-17 04:35:087196 ev_test_policy_(
7197 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7198 kOCSPTestCertFingerprint,
7199 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:027200 }
7201
7202 virtual void SetUp() OVERRIDE {
[email protected]ef2bf422012-05-11 03:27:097203 SetupContext(&context_);
7204 context_.Init();
[email protected]dffe8242012-03-20 15:14:277205
7206 scoped_refptr<net::X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:207207 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
[email protected]dffe8242012-03-20 15:14:277208 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
[email protected]90499482013-06-01 00:39:507209 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:277210
[email protected]a592c0432012-12-01 18:10:297211#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:097212 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:277213 EnsureNSSHttpIOInit();
7214#endif
7215 }
7216
[email protected]ce7d0cbc2013-05-03 18:57:227217 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:277218 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:537219 // We always overwrite out_cert_status.
7220 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:227221 SpawnedTestServer test_server(
7222 SpawnedTestServer::TYPE_HTTPS,
7223 ssl_options,
7224 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:277225 ASSERT_TRUE(test_server.Start());
7226
7227 TestDelegate d;
7228 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:197229 URLRequest r(
7230 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context_);
[email protected]dffe8242012-03-20 15:14:277231 r.Start();
7232
[email protected]255620da2013-08-19 13:14:297233 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:277234
7235 EXPECT_EQ(1, d.response_started_count());
7236 *out_cert_status = r.ssl_info().cert_status;
7237 }
7238
[email protected]46fadfd2013-02-06 09:40:167239 virtual ~HTTPSOCSPTest() {
[email protected]a592c0432012-12-01 18:10:297240#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:277241 ShutdownNSSHttpIO();
7242#endif
7243 }
7244
[email protected]a13234c2012-03-20 21:45:027245 protected:
7246 // SetupContext configures the URLRequestContext that will be used for making
7247 // connetions to testserver. This can be overridden in test subclasses for
7248 // different behaviour.
7249 virtual void SetupContext(URLRequestContext* context) {
7250 context->set_ssl_config_service(
7251 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:207252 true /* online revocation checking */,
7253 false /* require rev. checking for local
7254 anchors */));
[email protected]a13234c2012-03-20 21:45:027255 }
7256
[email protected]dffe8242012-03-20 15:14:277257 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:097258 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:087259 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:277260};
7261
[email protected]a13234c2012-03-20 21:45:027262static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:017263#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:027264 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7265 // have that ability on other platforms.
7266 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
7267#else
7268 return 0;
7269#endif
7270}
7271
[email protected]3a86a712013-07-30 07:16:207272// SystemSupportsHardFailRevocationChecking returns true iff the current
7273// operating system supports revocation checking and can distinguish between
7274// situations where a given certificate lacks any revocation information (eg:
7275// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7276// revocation information cannot be obtained (eg: the CRL was unreachable).
7277// If it does not, then tests which rely on 'hard fail' behaviour should be
7278// skipped.
7279static bool SystemSupportsHardFailRevocationChecking() {
7280#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7281 return true;
7282#else
7283 return false;
7284#endif
7285}
7286
[email protected]a13234c2012-03-20 21:45:027287// SystemUsesChromiumEVMetadata returns true iff the current operating system
7288// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7289// several tests are effected because our testing EV certificate won't be
7290// recognised as EV.
7291static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:327292#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:577293 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7294 return false;
[email protected]e1b2d732014-03-28 16:20:327295#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7296 // On OS X and Android, we use the system to tell us whether a certificate is
7297 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:017298 return false;
7299#else
7300 return true;
7301#endif
7302}
7303
[email protected]b6f2de32012-08-17 04:35:087304static bool SystemSupportsOCSP() {
[email protected]5c504192012-03-27 19:00:577305#if defined(USE_OPENSSL)
7306 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7307 return false;
7308#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:027309 return base::win::GetVersion() >= base::win::VERSION_VISTA;
7310#elif defined(OS_ANDROID)
7311 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7312 return false;
7313#else
7314 return true;
7315#endif
7316}
7317
[email protected]dffe8242012-03-20 15:14:277318TEST_F(HTTPSOCSPTest, Valid) {
7319 if (!SystemSupportsOCSP()) {
7320 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7321 return;
7322 }
7323
[email protected]ce7d0cbc2013-05-03 18:57:227324 SpawnedTestServer::SSLOptions ssl_options(
7325 SpawnedTestServer::SSLOptions::CERT_AUTO);
7326 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:277327
[email protected]924e9f92012-12-16 22:00:537328 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127329 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:277330
7331 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7332
[email protected]a13234c2012-03-20 21:45:027333 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7334 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:277335
7336 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7337}
7338
7339TEST_F(HTTPSOCSPTest, Revoked) {
7340 if (!SystemSupportsOCSP()) {
7341 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7342 return;
7343 }
7344
[email protected]ce7d0cbc2013-05-03 18:57:227345 SpawnedTestServer::SSLOptions ssl_options(
7346 SpawnedTestServer::SSLOptions::CERT_AUTO);
7347 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:277348
7349 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127350 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:277351
[email protected]a592c0432012-12-01 18:10:297352#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:277353 // Doesn't pass on OS X yet for reasons that need to be investigated.
7354 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7355#endif
7356 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7357 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7358}
7359
7360TEST_F(HTTPSOCSPTest, Invalid) {
7361 if (!SystemSupportsOCSP()) {
7362 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7363 return;
7364 }
7365
[email protected]ce7d0cbc2013-05-03 18:57:227366 SpawnedTestServer::SSLOptions ssl_options(
7367 SpawnedTestServer::SSLOptions::CERT_AUTO);
7368 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:277369
[email protected]924e9f92012-12-16 22:00:537370 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127371 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:277372
[email protected]a13234c2012-03-20 21:45:027373 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:277374 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:277375
7376 // Without a positive OCSP response, we shouldn't show the EV status.
7377 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7378 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7379}
[email protected]a13234c2012-03-20 21:45:027380
[email protected]3a86a712013-07-30 07:16:207381class HTTPSHardFailTest : public HTTPSOCSPTest {
7382 protected:
7383 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7384 context->set_ssl_config_service(
7385 new TestSSLConfigService(false /* check for EV */,
7386 false /* online revocation checking */,
7387 true /* require rev. checking for local
7388 anchors */));
7389 }
7390};
7391
7392
7393TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
7394 if (!SystemSupportsOCSP()) {
7395 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7396 return;
7397 }
7398
7399 if (!SystemSupportsHardFailRevocationChecking()) {
7400 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
7401 << "revocation checking";
7402 return;
7403 }
7404
7405 SpawnedTestServer::SSLOptions ssl_options(
7406 SpawnedTestServer::SSLOptions::CERT_AUTO);
7407 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7408
7409 CertStatus cert_status;
7410 DoConnection(ssl_options, &cert_status);
7411
7412 EXPECT_EQ(CERT_STATUS_REVOKED,
7413 cert_status & CERT_STATUS_REVOKED);
7414
7415 // Without a positive OCSP response, we shouldn't show the EV status.
7416 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7417}
7418
[email protected]a13234c2012-03-20 21:45:027419class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
7420 protected:
7421 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7422 context->set_ssl_config_service(
7423 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:207424 false /* online revocation checking */,
7425 false /* require rev. checking for local
7426 anchors */));
[email protected]a13234c2012-03-20 21:45:027427 }
7428};
7429
7430TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
7431 if (!SystemSupportsOCSP()) {
7432 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7433 return;
7434 }
7435
[email protected]ce7d0cbc2013-05-03 18:57:227436 SpawnedTestServer::SSLOptions ssl_options(
7437 SpawnedTestServer::SSLOptions::CERT_AUTO);
7438 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027439 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7440
[email protected]924e9f92012-12-16 22:00:537441 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127442 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027443
7444 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7445 cert_status & CERT_STATUS_ALL_ERRORS);
7446
7447 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:087448 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7449 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027450}
7451
[email protected]be0fff62013-08-29 23:37:487452TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
7453 if (!SystemSupportsOCSP()) {
7454 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7455 return;
7456 }
7457
7458 SpawnedTestServer::SSLOptions ssl_options(
7459 SpawnedTestServer::SSLOptions::CERT_AUTO);
7460 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7461 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7462
7463 CertStatus cert_status;
7464 DoConnection(ssl_options, &cert_status);
7465
7466 // Currently only works for Windows. When using NSS or OS X, it's not
7467 // possible to determine whether the check failed because of actual
7468 // revocation or because there was an OCSP failure.
7469#if defined(OS_WIN)
7470 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7471#else
7472 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7473#endif
7474
7475 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7476 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7477 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7478}
7479
[email protected]a13234c2012-03-20 21:45:027480TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
7481 if (!SystemSupportsOCSP()) {
7482 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7483 return;
7484 }
7485
[email protected]ce7d0cbc2013-05-03 18:57:227486 SpawnedTestServer::SSLOptions ssl_options(
7487 SpawnedTestServer::SSLOptions::CERT_AUTO);
7488 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:027489 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7490
7491 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127492 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027493
7494 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7495
7496 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7497 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:087498 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7499 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027500}
7501
7502TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
7503 if (!SystemSupportsOCSP()) {
7504 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7505 return;
7506 }
7507
[email protected]ce7d0cbc2013-05-03 18:57:227508 SpawnedTestServer::SSLOptions ssl_options(
7509 SpawnedTestServer::SSLOptions::CERT_AUTO);
7510 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027511 SSLConfigService::SetCRLSet(
7512 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7513
7514 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127515 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027516
7517 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7518 cert_status & CERT_STATUS_ALL_ERRORS);
7519
7520 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:087521 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7522 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027523}
7524
[email protected]51523f52013-07-31 21:57:287525TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
7526 if (!SystemSupportsOCSP()) {
7527 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7528 return;
7529 }
7530
7531 SpawnedTestServer::SSLOptions ssl_options(
7532 SpawnedTestServer::SSLOptions::CERT_AUTO);
7533 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7534 SSLConfigService::SetCRLSet(
7535 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7536 false, &kOCSPTestCertSPKI, "")));
7537
7538 CertStatus cert_status;
7539 DoConnection(ssl_options, &cert_status);
7540
7541 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7542 // revocation check for EV.
7543 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7544 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7545 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7546 EXPECT_FALSE(
7547 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7548}
7549
7550TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
7551 if (!SystemSupportsOCSP()) {
7552 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7553 return;
7554 }
7555
[email protected]ce7d0cbc2013-05-03 18:57:227556 SpawnedTestServer::SSLOptions ssl_options(
7557 SpawnedTestServer::SSLOptions::CERT_AUTO);
7558 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027559 SSLConfigService::SetCRLSet(
7560 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
7561
[email protected]51523f52013-07-31 21:57:287562 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:127563 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027564
[email protected]51523f52013-07-31 21:57:287565 // Even with a fresh CRLSet, we should still do online revocation checks when
7566 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7567 // test.
7568 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7569 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:027570
[email protected]51523f52013-07-31 21:57:287571 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:027572 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:287573 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027574}
7575
[email protected]b6f2de32012-08-17 04:35:087576TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
7577 // Test that when EV verification is requested, but online revocation
7578 // checking is disabled, and the leaf certificate is not in fact EV, that
7579 // no revocation checking actually happens.
7580 if (!SystemSupportsOCSP()) {
7581 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7582 return;
7583 }
7584
7585 // Unmark the certificate's OID as EV, which should disable revocation
7586 // checking (as per the user preference)
7587 ev_test_policy_.reset();
7588
[email protected]ce7d0cbc2013-05-03 18:57:227589 SpawnedTestServer::SSLOptions ssl_options(
7590 SpawnedTestServer::SSLOptions::CERT_AUTO);
7591 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:087592 SSLConfigService::SetCRLSet(
7593 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7594
7595 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127596 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:087597
7598 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7599
7600 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7601 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7602}
7603
[email protected]a13234c2012-03-20 21:45:027604class HTTPSCRLSetTest : public HTTPSOCSPTest {
7605 protected:
7606 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7607 context->set_ssl_config_service(
7608 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:207609 false /* online revocation checking */,
7610 false /* require rev. checking for local
7611 anchors */));
[email protected]a13234c2012-03-20 21:45:027612 }
7613};
7614
7615TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:227616 SpawnedTestServer::SSLOptions ssl_options(
7617 SpawnedTestServer::SSLOptions::CERT_AUTO);
7618 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027619 SSLConfigService::SetCRLSet(
7620 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7621
[email protected]924e9f92012-12-16 22:00:537622 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127623 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027624
7625 // If we're not trying EV verification then, even if the CRLSet has expired,
7626 // we don't fall back to online revocation checks.
7627 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7628 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7629 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7630}
[email protected]51523f52013-07-31 21:57:287631
7632TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
7633#if defined(USE_OPENSSL)
7634 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
7635 return;
7636#endif
7637
7638 SpawnedTestServer::SSLOptions ssl_options(
7639 SpawnedTestServer::SSLOptions::CERT_AUTO);
7640 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7641 ssl_options.cert_serial = 10;
7642 SSLConfigService::SetCRLSet(
7643 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7644 false, &kOCSPTestCertSPKI, "\x0a")));
7645
7646 CertStatus cert_status = 0;
7647 DoConnection(ssl_options, &cert_status);
7648
7649 // If the certificate is recorded as revoked in the CRLSet, that should be
7650 // reflected without online revocation checking.
7651 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7652 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7653 EXPECT_FALSE(
7654 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7655}
[email protected]316c1e5e2012-09-12 15:17:447656#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:277657
[email protected]316c1e5e2012-09-12 15:17:447658#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:317659class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:117660 public:
[email protected]d9fca99a2012-02-24 16:16:207661 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:227662 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:157663 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:117664 }
7665
[email protected]b89ca032009-08-31 21:41:317666 protected:
[email protected]ce7d0cbc2013-05-03 18:57:227667 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:317668};
7669
[email protected]d2a133182012-08-05 16:44:087670// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:097671TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:087672 ASSERT_TRUE(test_server_.Start());
7673
[email protected]9d5730b2012-08-24 17:42:497674 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:347675 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:087676
7677 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:087678 job_factory.SetProtocolHandler(
7679 "ftp",
[email protected]e0f35c92013-05-08 16:04:347680 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:087681 default_context_.set_job_factory(&job_factory);
7682
7683 TestDelegate d;
7684 {
[email protected]2ca01e52013-10-31 22:05:197685 URLRequest r(url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]d2a133182012-08-05 16:44:087686 r.Start();
7687 EXPECT_TRUE(r.is_pending());
7688
[email protected]255620da2013-08-19 13:14:297689 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:087690
7691 EXPECT_FALSE(r.is_pending());
7692 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
7693 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
7694 }
7695}
7696
[email protected]5accf7332009-11-24 03:41:387697// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127698TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:117699 ASSERT_TRUE(test_server_.Start());
7700
[email protected]a25e90e2009-09-09 17:05:377701 TestDelegate d;
7702 {
[email protected]2ca01e52013-10-31 22:05:197703 URLRequest r(
7704 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]a25e90e2009-09-09 17:05:377705 r.Start();
7706 EXPECT_TRUE(r.is_pending());
7707
[email protected]255620da2013-08-19 13:14:297708 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:377709
7710 EXPECT_FALSE(r.is_pending());
7711 EXPECT_EQ(1, d.response_started_count());
7712 EXPECT_FALSE(d.received_data_before_response());
7713 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:197714 EXPECT_EQ(test_server_.host_port_pair().host(),
7715 r.GetSocketAddress().host());
7716 EXPECT_EQ(test_server_.host_port_pair().port(),
7717 r.GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:377718 }
7719}
7720
[email protected]7df70012010-02-04 00:09:557721// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127722TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:117723 ASSERT_TRUE(test_server_.Start());
7724
[email protected]6cdfd7f2013-02-08 20:40:157725 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277726 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027727 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277728 TestDelegate d;
7729 {
[email protected]2ca01e52013-10-31 22:05:197730 URLRequest r(test_server_.GetURL("/LICENSE"),
7731 DEFAULT_PRIORITY,
7732 &d,
7733 &default_context_);
[email protected]dd265012009-01-08 20:45:277734 r.Start();
7735 EXPECT_TRUE(r.is_pending());
7736
[email protected]255620da2013-08-19 13:14:297737 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277738
7739 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497740 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277741
[email protected]ba2f3342009-07-30 18:08:427742 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277743 EXPECT_EQ(1, d.response_started_count());
7744 EXPECT_FALSE(d.received_data_before_response());
7745 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:197746 EXPECT_EQ(test_server_.host_port_pair().host(),
7747 r.GetSocketAddress().host());
7748 EXPECT_EQ(test_server_.host_port_pair().port(),
7749 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:277750 }
7751}
7752
[email protected]e9ecbd12009-12-20 18:44:407753// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127754TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:117755 ASSERT_TRUE(test_server_.Start());
7756
[email protected]6cdfd7f2013-02-08 20:40:157757 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277758 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027759 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277760 TestDelegate d;
7761 {
[email protected]ef2bf422012-05-11 03:27:097762 URLRequest r(
[email protected]95409e12010-08-17 20:07:117763 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]2ca01e52013-10-31 22:05:197764 DEFAULT_PRIORITY,
[email protected]94e2bbe2012-06-22 15:26:137765 &d,
7766 &default_context_);
[email protected]dd265012009-01-08 20:45:277767 r.Start();
7768 EXPECT_TRUE(r.is_pending());
7769
[email protected]255620da2013-08-19 13:14:297770 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277771
7772 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497773 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277774
[email protected]ba2f3342009-07-30 18:08:427775 EXPECT_FALSE(r.is_pending());
[email protected]6d81b482011-02-22 19:47:197776 EXPECT_EQ(test_server_.host_port_pair().host(),
7777 r.GetSocketAddress().host());
7778 EXPECT_EQ(test_server_.host_port_pair().port(),
7779 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:277780 EXPECT_EQ(1, d.response_started_count());
7781 EXPECT_FALSE(d.received_data_before_response());
7782 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:257783
7784 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:177785 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257786 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:277787 }
7788}
7789
[email protected]49abd652010-08-05 05:04:537790// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127791TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:117792 ASSERT_TRUE(test_server_.Start());
7793
[email protected]6cdfd7f2013-02-08 20:40:157794 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277795 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027796 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277797 TestDelegate d;
7798 {
[email protected]2ca01e52013-10-31 22:05:197799 URLRequest r(test_server_.GetURLWithUserAndPassword(
7800 "/LICENSE", "chrome", "wrong_password"),
7801 DEFAULT_PRIORITY,
7802 &d,
7803 &default_context_);
[email protected]dd265012009-01-08 20:45:277804 r.Start();
7805 EXPECT_TRUE(r.is_pending());
7806
[email protected]255620da2013-08-19 13:14:297807 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277808
7809 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497810 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277811
[email protected]ba2f3342009-07-30 18:08:427812 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277813 EXPECT_EQ(1, d.response_started_count());
7814 EXPECT_FALSE(d.received_data_before_response());
7815 EXPECT_EQ(d.bytes_received(), 0);
7816 }
7817}
7818
[email protected]cde4e80d2009-10-16 19:58:157819// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127820TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:117821 ASSERT_TRUE(test_server_.Start());
7822
[email protected]6cdfd7f2013-02-08 20:40:157823 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:587824 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7825 app_path = app_path.AppendASCII("LICENSE");
7826 TestDelegate d;
7827 // Set correct login credentials. The delegate will be asked for them when
7828 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587829 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:587830 {
[email protected]2ca01e52013-10-31 22:05:197831 URLRequest r(test_server_.GetURLWithUserAndPassword(
7832 "/LICENSE", "chrome", "wrong_password"),
7833 DEFAULT_PRIORITY,
7834 &d,
7835 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:587836 r.Start();
7837 EXPECT_TRUE(r.is_pending());
7838
[email protected]255620da2013-08-19 13:14:297839 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:587840
7841 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497842 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:587843
7844 EXPECT_FALSE(r.is_pending());
7845 EXPECT_EQ(1, d.response_started_count());
7846 EXPECT_FALSE(d.received_data_before_response());
7847 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7848 }
7849}
7850
[email protected]49abd652010-08-05 05:04:537851// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127852TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:117853 ASSERT_TRUE(test_server_.Start());
7854
[email protected]6cdfd7f2013-02-08 20:40:157855 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277856 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027857 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277858 TestDelegate d;
7859 {
[email protected]2ca01e52013-10-31 22:05:197860 URLRequest r(test_server_.GetURLWithUserAndPassword(
7861 "/LICENSE", "wrong_user", "chrome"),
7862 DEFAULT_PRIORITY,
7863 &d,
7864 &default_context_);
[email protected]dd265012009-01-08 20:45:277865 r.Start();
7866 EXPECT_TRUE(r.is_pending());
7867
[email protected]255620da2013-08-19 13:14:297868 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277869
7870 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497871 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277872
[email protected]ba2f3342009-07-30 18:08:427873 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277874 EXPECT_EQ(1, d.response_started_count());
7875 EXPECT_FALSE(d.received_data_before_response());
7876 EXPECT_EQ(d.bytes_received(), 0);
7877 }
7878}
[email protected]8b8a197d2009-08-26 15:57:587879
[email protected]cde4e80d2009-10-16 19:58:157880// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127881TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:117882 ASSERT_TRUE(test_server_.Start());
7883
[email protected]6cdfd7f2013-02-08 20:40:157884 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:587885 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7886 app_path = app_path.AppendASCII("LICENSE");
7887 TestDelegate d;
7888 // Set correct login credentials. The delegate will be asked for them when
7889 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587890 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:587891 {
[email protected]2ca01e52013-10-31 22:05:197892 URLRequest r(test_server_.GetURLWithUserAndPassword(
7893 "/LICENSE", "wrong_user", "chrome"),
7894 DEFAULT_PRIORITY,
7895 &d,
7896 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:587897 r.Start();
7898 EXPECT_TRUE(r.is_pending());
7899
[email protected]255620da2013-08-19 13:14:297900 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:587901
7902 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497903 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:587904
7905 EXPECT_FALSE(r.is_pending());
7906 EXPECT_EQ(1, d.response_started_count());
7907 EXPECT_FALSE(d.received_data_before_response());
7908 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7909 }
7910}
[email protected]60a3df52009-09-22 16:13:247911
[email protected]cde4e80d2009-10-16 19:58:157912// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127913TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:117914 ASSERT_TRUE(test_server_.Start());
7915
[email protected]6cdfd7f2013-02-08 20:40:157916 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:247917 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7918 app_path = app_path.AppendASCII("LICENSE");
7919
7920 scoped_ptr<TestDelegate> d(new TestDelegate);
7921 {
7922 // Pass correct login identity in the URL.
[email protected]ef2bf422012-05-11 03:27:097923 URLRequest r(
[email protected]2ca01e52013-10-31 22:05:197924 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7925 DEFAULT_PRIORITY,
[email protected]94e2bbe2012-06-22 15:26:137926 d.get(),
7927 &default_context_);
[email protected]60a3df52009-09-22 16:13:247928 r.Start();
7929 EXPECT_TRUE(r.is_pending());
7930
[email protected]255620da2013-08-19 13:14:297931 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247932
7933 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497934 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247935
7936 EXPECT_FALSE(r.is_pending());
7937 EXPECT_EQ(1, d->response_started_count());
7938 EXPECT_FALSE(d->received_data_before_response());
7939 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7940 }
7941
7942 d.reset(new TestDelegate);
7943 {
7944 // This request should use cached identity from previous request.
[email protected]2ca01e52013-10-31 22:05:197945 URLRequest r(test_server_.GetURL("/LICENSE"),
7946 DEFAULT_PRIORITY,
7947 d.get(),
7948 &default_context_);
[email protected]60a3df52009-09-22 16:13:247949 r.Start();
7950 EXPECT_TRUE(r.is_pending());
7951
[email protected]255620da2013-08-19 13:14:297952 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247953
7954 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497955 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247956
7957 EXPECT_FALSE(r.is_pending());
7958 EXPECT_EQ(1, d->response_started_count());
7959 EXPECT_FALSE(d->received_data_before_response());
7960 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7961 }
7962}
7963
[email protected]cde4e80d2009-10-16 19:58:157964// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127965TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:117966 ASSERT_TRUE(test_server_.Start());
7967
[email protected]6cdfd7f2013-02-08 20:40:157968 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:247969 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7970 app_path = app_path.AppendASCII("LICENSE");
7971
7972 scoped_ptr<TestDelegate> d(new TestDelegate);
7973 // Set correct login credentials. The delegate will be asked for them when
7974 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587975 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:247976 {
[email protected]2ca01e52013-10-31 22:05:197977 URLRequest r(test_server_.GetURLWithUserAndPassword(
7978 "/LICENSE", "chrome", "wrong_password"),
7979 DEFAULT_PRIORITY,
7980 d.get(),
7981 &default_context_);
[email protected]60a3df52009-09-22 16:13:247982 r.Start();
7983 EXPECT_TRUE(r.is_pending());
7984
[email protected]255620da2013-08-19 13:14:297985 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247986
7987 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497988 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247989
7990 EXPECT_FALSE(r.is_pending());
7991 EXPECT_EQ(1, d->response_started_count());
7992 EXPECT_FALSE(d->received_data_before_response());
7993 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7994 }
7995
7996 // Use a new delegate without explicit credentials. The cached ones should be
7997 // used.
7998 d.reset(new TestDelegate);
7999 {
8000 // Don't pass wrong credentials in the URL, they would override valid cached
8001 // ones.
[email protected]2ca01e52013-10-31 22:05:198002 URLRequest r(test_server_.GetURL("/LICENSE"),
8003 DEFAULT_PRIORITY,
8004 d.get(),
8005 &default_context_);
[email protected]60a3df52009-09-22 16:13:248006 r.Start();
8007 EXPECT_TRUE(r.is_pending());
8008
[email protected]255620da2013-08-19 13:14:298009 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248010
8011 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498012 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248013
8014 EXPECT_FALSE(r.is_pending());
8015 EXPECT_EQ(1, d->response_started_count());
8016 EXPECT_FALSE(d->received_data_before_response());
8017 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8018 }
8019}
[email protected]316c1e5e2012-09-12 15:17:448020#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:518021
8022} // namespace net