blob: 16eda0e54ed5b1bfca8a0c1f6d18deeed1ca83d1 [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
[email protected]cf4cae32014-05-27 00:39:101714// the case of reusing a SPDY session. The connected socket is not considered
1715// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591716//
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());
[email protected]d8fc4722014-06-13 13:17:151866 // The proxy server is not set before failure.
1867 EXPECT_TRUE(req.proxy_server().IsEmpty());
[email protected]316c1e5e2012-09-12 15:17:441868 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1869 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1870
1871 EXPECT_EQ(1, network_delegate.error_count());
1872 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1873 EXPECT_EQ(1, network_delegate.completed_requests());
1874}
1875
1876// Make sure that net::NetworkDelegate::NotifyCompleted is called if
1877// content is empty.
1878TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1879 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191880 URLRequest req(GURL("data:,"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:441881 req.Start();
[email protected]255620da2013-08-19 13:14:291882 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441883 EXPECT_EQ("", d.data_received());
1884 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1885}
1886
[email protected]5033ab82013-03-22 20:17:461887// Make sure that SetPriority actually sets the URLRequest's priority
1888// correctly, both before and after start.
1889TEST_F(URLRequestTest, SetPriorityBasic) {
1890 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191891 URLRequest req(GURL("http://test_intercept/foo"),
1892 DEFAULT_PRIORITY,
1893 &d,
1894 &default_context_);
[email protected]5033ab82013-03-22 20:17:461895 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1896
1897 req.SetPriority(LOW);
1898 EXPECT_EQ(LOW, req.priority());
1899
1900 req.Start();
1901 EXPECT_EQ(LOW, req.priority());
1902
1903 req.SetPriority(MEDIUM);
1904 EXPECT_EQ(MEDIUM, req.priority());
1905}
1906
1907// Make sure that URLRequest calls SetPriority on a job before calling
1908// Start on it.
1909TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1910 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191911 URLRequest req(GURL("http://test_intercept/foo"),
1912 DEFAULT_PRIORITY,
1913 &d,
1914 &default_context_);
[email protected]5033ab82013-03-22 20:17:461915 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1916
1917 scoped_refptr<URLRequestTestJob> job =
1918 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501919 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461920 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1921
1922 req.SetPriority(LOW);
1923
1924 req.Start();
1925 EXPECT_EQ(LOW, job->priority());
1926}
1927
1928// Make sure that URLRequest passes on its priority updates to its
1929// job.
1930TEST_F(URLRequestTest, SetJobPriority) {
1931 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:191932 URLRequest req(GURL("http://test_intercept/foo"),
1933 DEFAULT_PRIORITY,
1934 &d,
1935 &default_context_);
[email protected]5033ab82013-03-22 20:17:461936
1937 scoped_refptr<URLRequestTestJob> job =
1938 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501939 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461940
1941 req.SetPriority(LOW);
1942 req.Start();
1943 EXPECT_EQ(LOW, job->priority());
1944
1945 req.SetPriority(MEDIUM);
1946 EXPECT_EQ(MEDIUM, req.priority());
1947 EXPECT_EQ(MEDIUM, job->priority());
1948}
1949
[email protected]bb1c4662013-11-14 00:00:071950// Setting the IGNORE_LIMITS load flag should be okay if the priority
1951// is MAXIMUM_PRIORITY.
1952TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1953 TestDelegate d;
1954 URLRequest req(GURL("http://test_intercept/foo"),
1955 MAXIMUM_PRIORITY,
1956 &d,
1957 &default_context_);
1958 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1959
1960 scoped_refptr<URLRequestTestJob> job =
1961 new URLRequestTestJob(&req, &default_network_delegate_);
1962 AddTestInterceptor()->set_main_intercept_job(job.get());
1963
1964 req.SetLoadFlags(LOAD_IGNORE_LIMITS);
1965 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1966
1967 req.SetPriority(MAXIMUM_PRIORITY);
1968 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1969
1970 req.Start();
1971 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1972 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1973}
1974
[email protected]ce7d0cbc2013-05-03 18:57:221975// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:441976#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:221977// A subclass of SpawnedTestServer that uses a statically-configured hostname.
1978// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:441979// http://crbug.com/114369
[email protected]cd6f2522014-01-16 18:27:351980// TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
[email protected]ce7d0cbc2013-05-03 18:57:221981class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:441982 public:
[email protected]6cdfd7f2013-02-08 20:40:151983 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:221984 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1985 ScopedCustomUrlRequestTestHttpHost::value(),
1986 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:441987 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:221988 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1989 ScopedCustomUrlRequestTestHttpHost::value(),
1990 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:441991};
1992
[email protected]f2f31b32013-01-16 23:24:091993TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:441994 LocalHttpTestServer test_server;
1995 ASSERT_TRUE(test_server.Start());
1996
1997 TestURLRequestContext context;
1998 scoped_refptr<DelayedCookieMonster> delayed_cm =
1999 new DelayedCookieMonster();
2000 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502001 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442002
2003 // Set up a cookie.
2004 {
2005 TestNetworkDelegate network_delegate;
2006 context.set_network_delegate(&network_delegate);
2007 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192008 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2009 DEFAULT_PRIORITY,
2010 &d,
2011 &context);
[email protected]316c1e5e2012-09-12 15:17:442012 req.Start();
[email protected]255620da2013-08-19 13:14:292013 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442014 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2015 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2016 EXPECT_EQ(1, network_delegate.set_cookie_count());
2017 }
2018
2019 // Verify that the cookie is set.
2020 {
2021 TestNetworkDelegate network_delegate;
2022 context.set_network_delegate(&network_delegate);
2023 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192024 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2025 DEFAULT_PRIORITY,
2026 &d,
2027 &context);
[email protected]316c1e5e2012-09-12 15:17:442028 req.Start();
[email protected]255620da2013-08-19 13:14:292029 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442030
2031 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2032 != std::string::npos);
2033 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2034 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2035 }
2036}
2037
[email protected]f2f31b32013-01-16 23:24:092038TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442039 LocalHttpTestServer test_server;
2040 ASSERT_TRUE(test_server.Start());
2041
2042 // Set up a cookie.
2043 {
2044 TestNetworkDelegate network_delegate;
2045 default_context_.set_network_delegate(&network_delegate);
2046 TestDelegate d;
2047 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192048 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442049 &d,
2050 &default_context_);
2051 req.Start();
[email protected]255620da2013-08-19 13:14:292052 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442053 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2054 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2055 }
2056
2057 // Verify that the cookie is set.
2058 {
2059 TestNetworkDelegate network_delegate;
2060 default_context_.set_network_delegate(&network_delegate);
2061 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192062 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2063 DEFAULT_PRIORITY,
2064 &d,
2065 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442066 req.Start();
[email protected]255620da2013-08-19 13:14:292067 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442068
2069 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2070 != std::string::npos);
2071 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2072 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2073 }
2074
2075 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2076 {
2077 TestNetworkDelegate network_delegate;
2078 default_context_.set_network_delegate(&network_delegate);
2079 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192080 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2081 DEFAULT_PRIORITY,
2082 &d,
2083 &default_context_);
[email protected]bb1c4662013-11-14 00:00:072084 req.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]316c1e5e2012-09-12 15:17:442085 req.Start();
[email protected]255620da2013-08-19 13:14:292086 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442087
2088 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2089 == std::string::npos);
2090
2091 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2092 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2093 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2094 }
2095}
2096
2097TEST_F(URLRequestTest, DoNotSaveCookies) {
2098 LocalHttpTestServer test_server;
2099 ASSERT_TRUE(test_server.Start());
2100
2101 // Set up a cookie.
2102 {
2103 TestNetworkDelegate network_delegate;
2104 default_context_.set_network_delegate(&network_delegate);
2105 TestDelegate d;
2106 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192107 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442108 &d,
2109 &default_context_);
2110 req.Start();
[email protected]255620da2013-08-19 13:14:292111 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442112
2113 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2114 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2115 EXPECT_EQ(1, network_delegate.set_cookie_count());
2116 }
2117
2118 // Try to set-up another cookie and update the previous cookie.
2119 {
2120 TestNetworkDelegate network_delegate;
2121 default_context_.set_network_delegate(&network_delegate);
2122 TestDelegate d;
2123 URLRequest req(
2124 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192125 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442126 &d,
2127 &default_context_);
[email protected]bb1c4662013-11-14 00:00:072128 req.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
[email protected]316c1e5e2012-09-12 15:17:442129 req.Start();
2130
[email protected]255620da2013-08-19 13:14:292131 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442132
2133 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2134 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2135 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2136 EXPECT_EQ(0, network_delegate.set_cookie_count());
2137 }
2138
2139 // Verify the cookies weren't saved or updated.
2140 {
2141 TestNetworkDelegate network_delegate;
2142 default_context_.set_network_delegate(&network_delegate);
2143 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192144 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2145 DEFAULT_PRIORITY,
2146 &d,
2147 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442148 req.Start();
[email protected]255620da2013-08-19 13:14:292149 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442150
2151 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2152 == std::string::npos);
2153 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2154 != std::string::npos);
2155
2156 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2157 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2158 EXPECT_EQ(0, network_delegate.set_cookie_count());
2159 }
2160}
2161
2162TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2163 LocalHttpTestServer test_server;
2164 ASSERT_TRUE(test_server.Start());
2165
2166 // Set up a cookie.
2167 {
2168 TestNetworkDelegate network_delegate;
2169 default_context_.set_network_delegate(&network_delegate);
2170 TestDelegate d;
2171 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192172 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442173 &d,
2174 &default_context_);
2175 req.Start();
[email protected]255620da2013-08-19 13:14:292176 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442177
2178 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2179 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2180 }
2181
2182 // Verify that the cookie is set.
2183 {
2184 TestNetworkDelegate network_delegate;
2185 default_context_.set_network_delegate(&network_delegate);
2186 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192187 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2188 DEFAULT_PRIORITY,
2189 &d,
2190 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442191 req.Start();
[email protected]255620da2013-08-19 13:14:292192 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442193
2194 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2195 != std::string::npos);
2196
2197 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2198 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2199 }
2200
2201 // Verify that the cookie isn't sent.
2202 {
2203 TestNetworkDelegate network_delegate;
2204 default_context_.set_network_delegate(&network_delegate);
2205 TestDelegate d;
2206 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]2ca01e52013-10-31 22:05:192207 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2208 DEFAULT_PRIORITY,
2209 &d,
2210 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442211 req.Start();
[email protected]255620da2013-08-19 13:14:292212 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442213
2214 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2215 == std::string::npos);
2216
[email protected]22e045f2013-09-20 03:54:032217 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442218 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2219 }
2220}
2221
2222TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2223 LocalHttpTestServer test_server;
2224 ASSERT_TRUE(test_server.Start());
2225
2226 // Set up a cookie.
2227 {
2228 TestNetworkDelegate network_delegate;
2229 default_context_.set_network_delegate(&network_delegate);
2230 TestDelegate d;
2231 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192232 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442233 &d,
2234 &default_context_);
2235 req.Start();
[email protected]255620da2013-08-19 13:14:292236 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442237
2238 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2239 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2240 }
2241
2242 // Try to set-up another cookie and update the previous cookie.
2243 {
2244 TestNetworkDelegate network_delegate;
2245 default_context_.set_network_delegate(&network_delegate);
2246 TestDelegate d;
2247 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2248 URLRequest req(
2249 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192250 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442251 &d,
2252 &default_context_);
2253 req.Start();
2254
[email protected]255620da2013-08-19 13:14:292255 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442256
2257 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2258 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2259 }
2260
2261 // Verify the cookies weren't saved or updated.
2262 {
2263 TestNetworkDelegate network_delegate;
2264 default_context_.set_network_delegate(&network_delegate);
2265 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192266 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2267 DEFAULT_PRIORITY,
2268 &d,
2269 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442270 req.Start();
[email protected]255620da2013-08-19 13:14:292271 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442272
2273 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2274 == std::string::npos);
2275 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2276 != std::string::npos);
2277
2278 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2279 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2280 }
2281}
2282
2283TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2284 LocalHttpTestServer test_server;
2285 ASSERT_TRUE(test_server.Start());
2286
2287 // Set up an empty cookie.
2288 {
2289 TestNetworkDelegate network_delegate;
2290 default_context_.set_network_delegate(&network_delegate);
2291 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192292 URLRequest req(test_server.GetURL("set-cookie"),
2293 DEFAULT_PRIORITY,
2294 &d,
2295 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442296 req.Start();
[email protected]255620da2013-08-19 13:14:292297 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442298
2299 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2300 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2301 EXPECT_EQ(0, network_delegate.set_cookie_count());
2302 }
2303}
2304
2305TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2306 LocalHttpTestServer test_server;
2307 ASSERT_TRUE(test_server.Start());
2308
2309 // Set up a cookie.
2310 {
2311 TestNetworkDelegate network_delegate;
2312 default_context_.set_network_delegate(&network_delegate);
2313 TestDelegate d;
2314 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
[email protected]2ca01e52013-10-31 22:05:192315 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442316 &d,
2317 &default_context_);
2318 req.Start();
[email protected]255620da2013-08-19 13:14:292319 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442320
2321 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2322 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2323 }
2324
2325 // Verify that the cookie is set.
2326 {
2327 TestNetworkDelegate network_delegate;
2328 default_context_.set_network_delegate(&network_delegate);
2329 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192330 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2331 DEFAULT_PRIORITY,
2332 &d,
2333 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442334 req.Start();
[email protected]255620da2013-08-19 13:14:292335 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442336
2337 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2338 != std::string::npos);
2339
2340 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2341 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2342 }
2343
2344 // Verify that the cookie isn't sent.
2345 {
2346 TestNetworkDelegate network_delegate;
2347 default_context_.set_network_delegate(&network_delegate);
2348 TestDelegate d;
2349 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]2ca01e52013-10-31 22:05:192350 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2351 DEFAULT_PRIORITY,
2352 &d,
2353 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442354 req.Start();
[email protected]255620da2013-08-19 13:14:292355 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442356
2357 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2358 == std::string::npos);
2359
[email protected]22e045f2013-09-20 03:54:032360 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442361 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2362 }
2363}
2364
2365TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2366 LocalHttpTestServer test_server;
2367 ASSERT_TRUE(test_server.Start());
2368
2369 // Set up a cookie.
2370 {
2371 TestNetworkDelegate network_delegate;
2372 default_context_.set_network_delegate(&network_delegate);
2373 TestDelegate d;
2374 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
[email protected]2ca01e52013-10-31 22:05:192375 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442376 &d,
2377 &default_context_);
2378 req.Start();
[email protected]255620da2013-08-19 13:14:292379 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442380
2381 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2382 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2383 }
2384
2385 // Try to set-up another cookie and update the previous cookie.
2386 {
2387 TestNetworkDelegate network_delegate;
2388 default_context_.set_network_delegate(&network_delegate);
2389 TestDelegate d;
2390 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2391 URLRequest req(
2392 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]2ca01e52013-10-31 22:05:192393 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:442394 &d,
2395 &default_context_);
2396 req.Start();
2397
[email protected]255620da2013-08-19 13:14:292398 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442399
2400 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2401 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2402 }
2403
2404 // Verify the cookies weren't saved or updated.
2405 {
2406 TestNetworkDelegate network_delegate;
2407 default_context_.set_network_delegate(&network_delegate);
2408 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192409 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2410 DEFAULT_PRIORITY,
2411 &d,
2412 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442413 req.Start();
[email protected]255620da2013-08-19 13:14:292414 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442415
2416 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2417 == std::string::npos);
2418 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2419 != std::string::npos);
2420
2421 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2422 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2423 }
2424}
2425
[email protected]5095cd72012-11-01 10:29:162426// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2427// value for the |fixed_date| argument given to the constructor.
2428class FixedDateNetworkDelegate : public TestNetworkDelegate {
2429 public:
2430 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2431 : fixed_date_(fixed_date) {}
2432 virtual ~FixedDateNetworkDelegate() {}
2433
2434 // net::NetworkDelegate implementation
2435 virtual int OnHeadersReceived(
2436 net::URLRequest* request,
2437 const net::CompletionCallback& callback,
2438 const net::HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:162439 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2440 GURL* allowed_unsafe_redirect_url) OVERRIDE;
[email protected]5095cd72012-11-01 10:29:162441
2442 private:
2443 std::string fixed_date_;
2444
2445 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2446};
2447
2448int FixedDateNetworkDelegate::OnHeadersReceived(
2449 net::URLRequest* request,
2450 const net::CompletionCallback& callback,
2451 const net::HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:162452 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2453 GURL* allowed_unsafe_redirect_url) {
[email protected]5095cd72012-11-01 10:29:162454 net::HttpResponseHeaders* new_response_headers =
2455 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2456
2457 new_response_headers->RemoveHeader("Date");
2458 new_response_headers->AddHeader("Date: " + fixed_date_);
2459
2460 *override_response_headers = new_response_headers;
2461 return TestNetworkDelegate::OnHeadersReceived(request,
2462 callback,
2463 original_response_headers,
[email protected]5f714132014-03-26 10:41:162464 override_response_headers,
2465 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162466}
2467
2468// Test that cookie expiration times are adjusted for server/client clock
2469// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2470// headers by defaulting to GMT. (crbug.com/135131)
2471TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2472 LocalHttpTestServer test_server;
2473 ASSERT_TRUE(test_server.Start());
2474
2475 // Set up an expired cookie.
2476 {
2477 TestNetworkDelegate network_delegate;
2478 default_context_.set_network_delegate(&network_delegate);
2479 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192480 URLRequest req(
2481 test_server.GetURL(
2482 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2483 DEFAULT_PRIORITY,
[email protected]5095cd72012-11-01 10:29:162484 &d,
2485 &default_context_);
2486 req.Start();
[email protected]255620da2013-08-19 13:14:292487 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162488 }
2489 // Verify that the cookie is not set.
2490 {
2491 TestNetworkDelegate network_delegate;
2492 default_context_.set_network_delegate(&network_delegate);
2493 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192494 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2495 DEFAULT_PRIORITY,
2496 &d,
2497 &default_context_);
[email protected]5095cd72012-11-01 10:29:162498 req.Start();
[email protected]255620da2013-08-19 13:14:292499 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162500
2501 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2502 }
2503 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2504 {
2505 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2506 default_context_.set_network_delegate(&network_delegate);
2507 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192508 URLRequest req(
2509 test_server.GetURL(
2510 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2511 DEFAULT_PRIORITY,
[email protected]5095cd72012-11-01 10:29:162512 &d,
2513 &default_context_);
2514 req.Start();
[email protected]255620da2013-08-19 13:14:292515 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162516 }
2517 // Verify that the cookie is set.
2518 {
2519 TestNetworkDelegate network_delegate;
2520 default_context_.set_network_delegate(&network_delegate);
2521 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192522 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2523 DEFAULT_PRIORITY,
2524 &d,
2525 &default_context_);
[email protected]5095cd72012-11-01 10:29:162526 req.Start();
[email protected]255620da2013-08-19 13:14:292527 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162528
2529 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2530 }
2531}
2532
2533
[email protected]316c1e5e2012-09-12 15:17:442534// Check that it is impossible to change the referrer in the extra headers of
2535// an URLRequest.
2536TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2537 LocalHttpTestServer test_server;
2538 ASSERT_TRUE(test_server.Start());
2539
2540 // If extra headers contain referer and the request contains a referer,
2541 // only the latter shall be respected.
2542 {
2543 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192544 URLRequest req(test_server.GetURL("echoheader?Referer"),
2545 DEFAULT_PRIORITY,
2546 &d,
2547 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:132548 req.SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442549
2550 HttpRequestHeaders headers;
2551 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2552 req.SetExtraRequestHeaders(headers);
2553
2554 req.Start();
[email protected]255620da2013-08-19 13:14:292555 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442556
2557 EXPECT_EQ("http://foo.com/", d.data_received());
2558 }
2559
2560 // If extra headers contain a referer but the request does not, no referer
2561 // shall be sent in the header.
2562 {
2563 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192564 URLRequest req(test_server.GetURL("echoheader?Referer"),
2565 DEFAULT_PRIORITY,
2566 &d,
2567 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:442568
2569 HttpRequestHeaders headers;
2570 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2571 req.SetExtraRequestHeaders(headers);
[email protected]bb1c4662013-11-14 00:00:072572 req.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442573
2574 req.Start();
[email protected]255620da2013-08-19 13:14:292575 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442576
2577 EXPECT_EQ("None", d.data_received());
2578 }
2579}
2580
[email protected]b89290212009-08-14 22:37:352581class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112582 public:
2583 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152584 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112585 "net/data/url_request_unittest"))) {
2586 }
2587
[email protected]b89290212009-08-14 22:37:352588 protected:
[email protected]21184962011-10-26 00:50:302589 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2590 // |request_method| is the method to use for the initial request.
2591 // |redirect_method| is the method that is expected to be used for the second
2592 // request, after redirection.
2593 // If |include_data| is true, data is uploaded with the request. The
2594 // response body is expected to match it exactly, if and only if
2595 // |request_method| == |redirect_method|.
2596 void HTTPRedirectMethodTest(const GURL& redirect_url,
2597 const std::string& request_method,
2598 const std::string& redirect_method,
2599 bool include_data) {
2600 static const char kData[] = "hello world";
2601 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192602 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]21184962011-10-26 00:50:302603 req.set_method(request_method);
2604 if (include_data) {
[email protected]f288ef02012-12-15 20:28:282605 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]21184962011-10-26 00:50:302606 HttpRequestHeaders headers;
2607 headers.SetHeader(HttpRequestHeaders::kContentLength,
2608 base::UintToString(arraysize(kData) - 1));
2609 req.SetExtraRequestHeaders(headers);
2610 }
2611 req.Start();
[email protected]255620da2013-08-19 13:14:292612 base::RunLoop().Run();
[email protected]21184962011-10-26 00:50:302613 EXPECT_EQ(redirect_method, req.method());
2614 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2615 EXPECT_EQ(OK, req.status().error());
2616 if (include_data) {
2617 if (request_method == redirect_method) {
2618 EXPECT_EQ(kData, d.data_received());
2619 } else {
2620 EXPECT_NE(kData, d.data_received());
2621 }
2622 }
2623 if (HasFailure())
2624 LOG(WARNING) << "Request method was: " << request_method;
2625 }
2626
[email protected]762d2db2010-01-11 19:03:012627 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012628 const int kMsgSize = 20000; // multiple of 10
2629 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482630 char* uploadBytes = new char[kMsgSize+1];
2631 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012632 char marker = 'a';
2633 for (int idx = 0; idx < kMsgSize/10; idx++) {
2634 memcpy(ptr, "----------", 10);
2635 ptr += 10;
2636 if (idx % 100 == 0) {
2637 ptr--;
2638 *ptr++ = marker;
2639 if (++marker > 'z')
2640 marker = 'a';
2641 }
2642 }
2643 uploadBytes[kMsgSize] = '\0';
2644
[email protected]762d2db2010-01-11 19:03:012645 for (int i = 0; i < kIterations; ++i) {
2646 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:192647 URLRequest r(
2648 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]762d2db2010-01-11 19:03:012649 r.set_method(method.c_str());
2650
[email protected]f288ef02012-12-15 20:28:282651 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
[email protected]762d2db2010-01-11 19:03:012652
2653 r.Start();
2654 EXPECT_TRUE(r.is_pending());
2655
[email protected]255620da2013-08-19 13:14:292656 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012657
[email protected]329b68b2012-11-14 17:54:272658 ASSERT_EQ(1, d.response_started_count())
2659 << "request failed: " << r.status().status()
2660 << ", os error: " << r.status().error();
[email protected]762d2db2010-01-11 19:03:012661
2662 EXPECT_FALSE(d.received_data_before_response());
2663 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012664 }
2665 delete[] uploadBytes;
2666 }
2667
[email protected]ef2bf422012-05-11 03:27:092668 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222669 r->AppendChunkToUpload("a", 1, false);
2670 r->AppendChunkToUpload("bcd", 3, false);
2671 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2672 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2673 r->AppendChunkToUpload("0", 1, false);
2674 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112675 }
2676
[email protected]ef2bf422012-05-11 03:27:092677 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112678 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272679 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112680 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2681
[email protected]329b68b2012-11-14 17:54:272682 ASSERT_EQ(1, d->response_started_count())
2683 << "request failed: " << r->status().status()
2684 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112685
2686 EXPECT_FALSE(d->received_data_before_response());
2687
[email protected]329b68b2012-11-14 17:54:272688 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2689 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112690 }
2691
[email protected]ede03212012-09-07 12:52:262692 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342693 TestDelegate d;
2694 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2695 base::IntToString(num_cookies)),
[email protected]2ca01e52013-10-31 22:05:192696 DEFAULT_PRIORITY,
2697 &d,
2698 &default_context_);
[email protected]263163f2012-06-14 22:40:342699
2700 r.Start();
2701 EXPECT_TRUE(r.is_pending());
2702
[email protected]255620da2013-08-19 13:14:292703 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342704
2705 bool is_success = r.status().is_success();
2706
[email protected]ede03212012-09-07 12:52:262707 if (!is_success) {
[email protected]cd6f2522014-01-16 18:27:352708 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:342709 // The test server appears to be unable to handle subsequent requests
2710 // after this error is triggered. Force it to restart.
2711 EXPECT_TRUE(test_server_.Stop());
2712 EXPECT_TRUE(test_server_.Start());
2713 }
2714
2715 return is_success;
2716 }
2717
[email protected]1700c6a2012-02-22 18:07:072718 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352719};
2720
[email protected]95409e12010-08-17 20:07:112721// In this unit test, we're using the HTTPTestServer as a proxy server and
2722// issuing a CONNECT request with the magic host name "www.redirect.com".
2723// The HTTPTestServer will return a 302 response, which we should not
2724// follow.
[email protected]f2f31b32013-01-16 23:24:092725TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112726 ASSERT_TRUE(test_server_.Start());
2727
[email protected]ceefd7fd2012-11-29 00:36:242728 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042729 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192730 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502731
[email protected]d1ec59082009-02-11 02:48:152732 TestDelegate d;
2733 {
[email protected]2ca01e52013-10-31 22:05:192734 URLRequest r(
2735 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]d1ec59082009-02-11 02:48:152736 r.Start();
2737 EXPECT_TRUE(r.is_pending());
2738
[email protected]255620da2013-08-19 13:14:292739 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:152740
[email protected]7461a402011-03-24 23:19:512741 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d8fc4722014-06-13 13:17:152742 // The proxy server is not set before failure.
2743 EXPECT_TRUE(r.proxy_server().IsEmpty());
[email protected]d0cc35b2011-09-08 12:02:052744 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:082745 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152746 // We should not have followed the redirect.
2747 EXPECT_EQ(0, d.received_redirect_count());
2748 }
2749}
2750
[email protected]8202d0c2011-02-23 08:31:142751// This is the same as the previous test, but checks that the network delegate
2752// registers the error.
[email protected]c044616e2013-02-20 02:01:262753TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142754 ASSERT_TRUE(test_server_.Start());
2755
[email protected]ceefd7fd2012-11-29 00:36:242756 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042757 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192758 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502759
[email protected]8202d0c2011-02-23 08:31:142760 TestDelegate d;
2761 {
[email protected]2ca01e52013-10-31 22:05:192762 URLRequest r(
2763 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]8202d0c2011-02-23 08:31:142764 r.Start();
2765 EXPECT_TRUE(r.is_pending());
2766
[email protected]255620da2013-08-19 13:14:292767 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:142768
[email protected]7461a402011-03-24 23:19:512769 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d8fc4722014-06-13 13:17:152770 // The proxy server is not set before failure.
2771 EXPECT_TRUE(r.proxy_server().IsEmpty());
[email protected]d0cc35b2011-09-08 12:02:052772 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]8202d0c2011-02-23 08:31:142773 EXPECT_EQ(1, d.response_started_count());
2774 // We should not have followed the redirect.
2775 EXPECT_EQ(0, d.received_redirect_count());
2776
2777 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052778 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142779 }
2780}
2781
[email protected]dc5a5cf2012-09-26 02:49:302782// Tests that we can block and asynchronously return OK in various stages.
2783TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2784 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2785 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2786 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2787 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2788 };
2789 static const size_t blocking_stages_length = arraysize(blocking_stages);
2790
2791 ASSERT_TRUE(test_server_.Start());
2792
2793 TestDelegate d;
2794 BlockingNetworkDelegate network_delegate(
2795 BlockingNetworkDelegate::USER_CALLBACK);
2796 network_delegate.set_block_on(
2797 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2798 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2799 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2800
2801 TestURLRequestContext context(true);
2802 context.set_network_delegate(&network_delegate);
2803 context.Init();
2804
2805 {
[email protected]2ca01e52013-10-31 22:05:192806 URLRequest r(
2807 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, &context);
[email protected]dc5a5cf2012-09-26 02:49:302808
2809 r.Start();
2810 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:292811 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302812 EXPECT_EQ(blocking_stages[i],
2813 network_delegate.stage_blocked_for_callback());
2814 network_delegate.DoCallback(OK);
2815 }
[email protected]255620da2013-08-19 13:14:292816 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302817 EXPECT_EQ(200, r.GetResponseCode());
2818 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2819 EXPECT_EQ(1, network_delegate.created_requests());
2820 EXPECT_EQ(0, network_delegate.destroyed_requests());
2821 }
2822 EXPECT_EQ(1, network_delegate.destroyed_requests());
2823}
2824
[email protected]4c76d7c2011-04-15 19:14:122825// Tests that the network delegate can block and cancel a request.
2826TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2827 ASSERT_TRUE(test_server_.Start());
2828
2829 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302830 BlockingNetworkDelegate network_delegate(
2831 BlockingNetworkDelegate::AUTO_CALLBACK);
2832 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2833 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:122834
[email protected]d5a4dd62012-05-23 01:41:042835 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192836 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502837
[email protected]4c76d7c2011-04-15 19:14:122838 {
[email protected]2ca01e52013-10-31 22:05:192839 URLRequest r(
2840 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122841
2842 r.Start();
[email protected]255620da2013-08-19 13:14:292843 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122844
2845 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d8fc4722014-06-13 13:17:152846 // The proxy server is not set before cancellation.
2847 EXPECT_TRUE(r.proxy_server().IsEmpty());
[email protected]d0cc35b2011-09-08 12:02:052848 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122849 EXPECT_EQ(1, network_delegate.created_requests());
2850 EXPECT_EQ(0, network_delegate.destroyed_requests());
2851 }
2852 EXPECT_EQ(1, network_delegate.destroyed_requests());
2853}
2854
[email protected]b4438d32012-09-27 06:15:302855// Helper function for NetworkDelegateCancelRequestAsynchronously and
2856// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2857// delegate operating in |block_mode| and a request for |url|. It blocks the
2858// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2859void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2860 BlockingNetworkDelegate::Stage stage,
2861 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:362862 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:302863 BlockingNetworkDelegate network_delegate(block_mode);
2864 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2865 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:362866
[email protected]b4438d32012-09-27 06:15:302867 TestURLRequestContext context(true);
2868 context.set_network_delegate(&network_delegate);
2869 context.Init();
[email protected]3cd384c602011-08-31 16:12:362870
2871 {
[email protected]2ca01e52013-10-31 22:05:192872 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]3cd384c602011-08-31 16:12:362873
2874 r.Start();
[email protected]255620da2013-08-19 13:14:292875 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:362876
2877 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d8fc4722014-06-13 13:17:152878 // The proxy server is not set before cancellation.
2879 EXPECT_TRUE(r.proxy_server().IsEmpty());
[email protected]b4438d32012-09-27 06:15:302880 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
[email protected]3cd384c602011-08-31 16:12:362881 EXPECT_EQ(1, network_delegate.created_requests());
2882 EXPECT_EQ(0, network_delegate.destroyed_requests());
2883 }
2884 EXPECT_EQ(1, network_delegate.destroyed_requests());
2885}
2886
[email protected]b4438d32012-09-27 06:15:302887// The following 3 tests check that the network delegate can cancel a request
2888// synchronously in various stages of the request.
2889TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2890 ASSERT_TRUE(test_server_.Start());
2891 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2892 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452893 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302894}
2895
2896TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2897 ASSERT_TRUE(test_server_.Start());
2898 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2899 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452900 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302901}
2902
2903TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2904 ASSERT_TRUE(test_server_.Start());
2905 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2906 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452907 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302908}
2909
2910// The following 3 tests check that the network delegate can cancel a request
2911// asynchronously in various stages of the request.
2912TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2913 ASSERT_TRUE(test_server_.Start());
2914 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2915 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452916 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302917}
2918
2919TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2920 ASSERT_TRUE(test_server_.Start());
2921 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2922 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452923 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302924}
2925
2926TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2927 ASSERT_TRUE(test_server_.Start());
2928 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2929 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452930 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302931}
2932
[email protected]4c76d7c2011-04-15 19:14:122933// Tests that the network delegate can block and redirect a request to a new
2934// URL.
2935TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2936 ASSERT_TRUE(test_server_.Start());
2937
2938 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302939 BlockingNetworkDelegate network_delegate(
2940 BlockingNetworkDelegate::AUTO_CALLBACK);
2941 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:122942 GURL redirect_url(test_server_.GetURL("simple.html"));
2943 network_delegate.set_redirect_url(redirect_url);
2944
[email protected]d5a4dd62012-05-23 01:41:042945 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192946 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502947
[email protected]4c76d7c2011-04-15 19:14:122948 {
[email protected]8f1ac082011-04-19 21:14:132949 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:192950 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122951
2952 r.Start();
[email protected]255620da2013-08-19 13:14:292953 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122954
2955 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d8fc4722014-06-13 13:17:152956 EXPECT_TRUE(r.proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:272957 EXPECT_EQ(
2958 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2959 EXPECT_TRUE(
2960 network_delegate.last_observed_proxy().Equals(
2961 test_server_.host_port_pair()));
2962
[email protected]d0cc35b2011-09-08 12:02:052963 EXPECT_EQ(0, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122964 EXPECT_EQ(redirect_url, r.url());
[email protected]8f1ac082011-04-19 21:14:132965 EXPECT_EQ(original_url, r.original_url());
2966 EXPECT_EQ(2U, r.url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:122967 EXPECT_EQ(1, network_delegate.created_requests());
2968 EXPECT_EQ(0, network_delegate.destroyed_requests());
2969 }
2970 EXPECT_EQ(1, network_delegate.destroyed_requests());
2971}
2972
[email protected]b813ed72012-04-05 08:21:362973// Tests that the network delegate can block and redirect a request to a new
2974// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2975TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2976 ASSERT_TRUE(test_server_.Start());
2977
2978 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302979 BlockingNetworkDelegate network_delegate(
2980 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:362981 GURL redirect_url(test_server_.GetURL("simple.html"));
2982 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:362983
[email protected]d5a4dd62012-05-23 01:41:042984 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192985 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:362986
2987 {
2988 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:192989 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]b813ed72012-04-05 08:21:362990
2991 r.Start();
[email protected]255620da2013-08-19 13:14:292992 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:362993
2994 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d8fc4722014-06-13 13:17:152995 EXPECT_TRUE(r.proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:272996 EXPECT_EQ(
2997 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2998 EXPECT_TRUE(
2999 network_delegate.last_observed_proxy().Equals(
3000 test_server_.host_port_pair()));
[email protected]b813ed72012-04-05 08:21:363001 EXPECT_EQ(0, r.status().error());
3002 EXPECT_EQ(redirect_url, r.url());
3003 EXPECT_EQ(original_url, r.original_url());
3004 EXPECT_EQ(2U, r.url_chain().size());
3005 EXPECT_EQ(1, network_delegate.created_requests());
3006 EXPECT_EQ(0, network_delegate.destroyed_requests());
3007 }
3008 EXPECT_EQ(1, network_delegate.destroyed_requests());
3009}
3010
[email protected]3c5ca8c2011-09-29 01:14:513011// Tests that redirects caused by the network delegate preserve POST data.
3012TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3013 ASSERT_TRUE(test_server_.Start());
3014
3015 const char kData[] = "hello world";
3016
3017 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303018 BlockingNetworkDelegate network_delegate(
3019 BlockingNetworkDelegate::AUTO_CALLBACK);
3020 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513021 GURL redirect_url(test_server_.GetURL("echo"));
3022 network_delegate.set_redirect_url(redirect_url);
3023
[email protected]ef2bf422012-05-11 03:27:093024 TestURLRequestContext context(true);
3025 context.set_network_delegate(&network_delegate);
3026 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513027
3028 {
3029 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]2ca01e52013-10-31 22:05:193030 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
[email protected]3c5ca8c2011-09-29 01:14:513031 r.set_method("POST");
[email protected]f288ef02012-12-15 20:28:283032 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]3c5ca8c2011-09-29 01:14:513033 HttpRequestHeaders headers;
3034 headers.SetHeader(HttpRequestHeaders::kContentLength,
3035 base::UintToString(arraysize(kData) - 1));
3036 r.SetExtraRequestHeaders(headers);
[email protected]3c5ca8c2011-09-29 01:14:513037 r.Start();
[email protected]255620da2013-08-19 13:14:293038 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513039
3040 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3041 EXPECT_EQ(0, r.status().error());
3042 EXPECT_EQ(redirect_url, r.url());
3043 EXPECT_EQ(original_url, r.original_url());
3044 EXPECT_EQ(2U, r.url_chain().size());
3045 EXPECT_EQ(1, network_delegate.created_requests());
3046 EXPECT_EQ(0, network_delegate.destroyed_requests());
3047 EXPECT_EQ("POST", r.method());
3048 EXPECT_EQ(kData, d.data_received());
3049 }
3050 EXPECT_EQ(1, network_delegate.destroyed_requests());
3051}
3052
[email protected]5f714132014-03-26 10:41:163053// Tests that the network delegate can block and redirect a request to a new
3054// URL during OnHeadersReceived.
3055TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3056 ASSERT_TRUE(test_server_.Start());
3057
3058 TestDelegate d;
3059 BlockingNetworkDelegate network_delegate(
3060 BlockingNetworkDelegate::AUTO_CALLBACK);
3061 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3062 GURL redirect_url(test_server_.GetURL("simple.html"));
3063 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3064
3065 TestURLRequestContextWithProxy context(
3066 test_server_.host_port_pair().ToString(), &network_delegate);
3067
3068 {
3069 GURL original_url(test_server_.GetURL("empty.html"));
3070 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
3071
3072 r.Start();
3073 base::RunLoop().Run();
3074
3075 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d8fc4722014-06-13 13:17:153076 EXPECT_TRUE(r.proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273077 EXPECT_EQ(
3078 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3079 EXPECT_TRUE(
3080 network_delegate.last_observed_proxy().Equals(
3081 test_server_.host_port_pair()));
[email protected]5f714132014-03-26 10:41:163082 EXPECT_EQ(net::OK, r.status().error());
3083 EXPECT_EQ(redirect_url, r.url());
3084 EXPECT_EQ(original_url, r.original_url());
3085 EXPECT_EQ(2U, r.url_chain().size());
3086 EXPECT_EQ(2, network_delegate.created_requests());
3087 EXPECT_EQ(0, network_delegate.destroyed_requests());
3088 }
3089 EXPECT_EQ(1, network_delegate.destroyed_requests());
3090}
3091
[email protected]c2911d72011-10-03 22:16:363092// Tests that the network delegate can synchronously complete OnAuthRequired
3093// by taking no action. This indicates that the NetworkDelegate does not want to
3094// handle the challenge, and is passing the buck along to the
3095// URLRequest::Delegate.
3096TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3097 ASSERT_TRUE(test_server_.Start());
3098
3099 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303100 BlockingNetworkDelegate network_delegate(
3101 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363102
[email protected]ef2bf422012-05-11 03:27:093103 TestURLRequestContext context(true);
3104 context.set_network_delegate(&network_delegate);
3105 context.Init();
[email protected]c2911d72011-10-03 22:16:363106
[email protected]f3cf9802011-10-28 18:44:583107 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363108
3109 {
3110 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193111 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363112 r.Start();
[email protected]79e1fd62013-06-20 06:50:043113
[email protected]255620da2013-08-19 13:14:293114 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043115
3116 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3117 EXPECT_EQ(0, r.status().error());
3118 EXPECT_EQ(200, r.GetResponseCode());
3119 EXPECT_TRUE(d.auth_required_called());
3120 EXPECT_EQ(1, network_delegate.created_requests());
3121 EXPECT_EQ(0, network_delegate.destroyed_requests());
3122 }
3123 EXPECT_EQ(1, network_delegate.destroyed_requests());
3124}
3125
3126TEST_F(URLRequestTestHTTP,
3127 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3128 ASSERT_TRUE(test_server_.Start());
3129
3130 TestDelegate d;
3131 BlockingNetworkDelegate network_delegate(
3132 BlockingNetworkDelegate::SYNCHRONOUS);
3133
3134 TestURLRequestContext context(true);
3135 context.set_network_delegate(&network_delegate);
3136 context.Init();
3137
3138 d.set_credentials(AuthCredentials(kUser, kSecret));
3139
3140 {
3141 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193142 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]79e1fd62013-06-20 06:50:043143 r.Start();
3144
3145 {
3146 HttpRequestHeaders headers;
3147 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3148 EXPECT_FALSE(headers.HasHeader("Authorization"));
3149 }
3150
[email protected]255620da2013-08-19 13:14:293151 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363152
3153 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3154 EXPECT_EQ(0, r.status().error());
3155 EXPECT_EQ(200, r.GetResponseCode());
3156 EXPECT_TRUE(d.auth_required_called());
3157 EXPECT_EQ(1, network_delegate.created_requests());
3158 EXPECT_EQ(0, network_delegate.destroyed_requests());
3159 }
3160 EXPECT_EQ(1, network_delegate.destroyed_requests());
3161}
3162
3163// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403164// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363165TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3166 ASSERT_TRUE(test_server_.Start());
3167
3168 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303169 BlockingNetworkDelegate network_delegate(
3170 BlockingNetworkDelegate::SYNCHRONOUS);
3171 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363172 network_delegate.set_auth_retval(
3173 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3174
[email protected]f3cf9802011-10-28 18:44:583175 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363176
[email protected]ef2bf422012-05-11 03:27:093177 TestURLRequestContext context(true);
3178 context.set_network_delegate(&network_delegate);
3179 context.Init();
[email protected]c2911d72011-10-03 22:16:363180
3181 {
3182 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193183 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363184 r.Start();
[email protected]255620da2013-08-19 13:14:293185 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363186
3187 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3188 EXPECT_EQ(0, r.status().error());
3189 EXPECT_EQ(200, r.GetResponseCode());
3190 EXPECT_FALSE(d.auth_required_called());
3191 EXPECT_EQ(1, network_delegate.created_requests());
3192 EXPECT_EQ(0, network_delegate.destroyed_requests());
3193 }
3194 EXPECT_EQ(1, network_delegate.destroyed_requests());
3195}
3196
[email protected]79e1fd62013-06-20 06:50:043197// Same as above, but also tests that GetFullRequestHeaders returns the proper
3198// headers (for the first or second request) when called at the proper times.
3199TEST_F(URLRequestTestHTTP,
3200 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3201 ASSERT_TRUE(test_server_.Start());
3202
3203 TestDelegate d;
3204 BlockingNetworkDelegate network_delegate(
3205 BlockingNetworkDelegate::SYNCHRONOUS);
3206 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3207 network_delegate.set_auth_retval(
3208 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3209
3210 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3211
3212 TestURLRequestContext context(true);
3213 context.set_network_delegate(&network_delegate);
3214 context.Init();
3215
3216 {
3217 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193218 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]79e1fd62013-06-20 06:50:043219 r.Start();
[email protected]255620da2013-08-19 13:14:293220 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043221
3222 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3223 EXPECT_EQ(0, r.status().error());
3224 EXPECT_EQ(200, r.GetResponseCode());
3225 EXPECT_FALSE(d.auth_required_called());
3226 EXPECT_EQ(1, network_delegate.created_requests());
3227 EXPECT_EQ(0, network_delegate.destroyed_requests());
3228
3229 {
3230 HttpRequestHeaders headers;
3231 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3232 EXPECT_TRUE(headers.HasHeader("Authorization"));
3233 }
3234 }
3235 EXPECT_EQ(1, network_delegate.destroyed_requests());
3236}
3237
[email protected]c2911d72011-10-03 22:16:363238// Tests that the network delegate can synchronously complete OnAuthRequired
3239// by cancelling authentication.
3240TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3241 ASSERT_TRUE(test_server_.Start());
3242
3243 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303244 BlockingNetworkDelegate network_delegate(
3245 BlockingNetworkDelegate::SYNCHRONOUS);
3246 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363247 network_delegate.set_auth_retval(
3248 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3249
[email protected]ef2bf422012-05-11 03:27:093250 TestURLRequestContext context(true);
3251 context.set_network_delegate(&network_delegate);
3252 context.Init();
[email protected]c2911d72011-10-03 22:16:363253
3254 {
3255 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193256 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363257 r.Start();
[email protected]255620da2013-08-19 13:14:293258 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363259
3260 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3261 EXPECT_EQ(OK, r.status().error());
3262 EXPECT_EQ(401, r.GetResponseCode());
3263 EXPECT_FALSE(d.auth_required_called());
3264 EXPECT_EQ(1, network_delegate.created_requests());
3265 EXPECT_EQ(0, network_delegate.destroyed_requests());
3266 }
3267 EXPECT_EQ(1, network_delegate.destroyed_requests());
3268}
3269
3270// Tests that the network delegate can asynchronously complete OnAuthRequired
3271// by taking no action. This indicates that the NetworkDelegate does not want
3272// to handle the challenge, and is passing the buck along to the
3273// URLRequest::Delegate.
3274TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3275 ASSERT_TRUE(test_server_.Start());
3276
3277 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303278 BlockingNetworkDelegate network_delegate(
3279 BlockingNetworkDelegate::AUTO_CALLBACK);
3280 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363281
[email protected]ef2bf422012-05-11 03:27:093282 TestURLRequestContext context(true);
3283 context.set_network_delegate(&network_delegate);
3284 context.Init();
[email protected]c2911d72011-10-03 22:16:363285
[email protected]f3cf9802011-10-28 18:44:583286 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363287
3288 {
3289 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193290 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363291 r.Start();
[email protected]255620da2013-08-19 13:14:293292 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363293
3294 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3295 EXPECT_EQ(0, r.status().error());
3296 EXPECT_EQ(200, r.GetResponseCode());
3297 EXPECT_TRUE(d.auth_required_called());
3298 EXPECT_EQ(1, network_delegate.created_requests());
3299 EXPECT_EQ(0, network_delegate.destroyed_requests());
3300 }
3301 EXPECT_EQ(1, network_delegate.destroyed_requests());
3302}
3303
3304// Tests that the network delegate can asynchronously complete OnAuthRequired
3305// by setting credentials.
3306TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3307 ASSERT_TRUE(test_server_.Start());
3308
3309 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303310 BlockingNetworkDelegate network_delegate(
3311 BlockingNetworkDelegate::AUTO_CALLBACK);
3312 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363313 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363314 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3315
[email protected]f3cf9802011-10-28 18:44:583316 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363317 network_delegate.set_auth_credentials(auth_credentials);
3318
[email protected]ef2bf422012-05-11 03:27:093319 TestURLRequestContext context(true);
3320 context.set_network_delegate(&network_delegate);
3321 context.Init();
[email protected]c2911d72011-10-03 22:16:363322
3323 {
3324 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193325 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363326 r.Start();
[email protected]255620da2013-08-19 13:14:293327 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363328
3329 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3330 EXPECT_EQ(0, r.status().error());
3331
3332 EXPECT_EQ(200, r.GetResponseCode());
3333 EXPECT_FALSE(d.auth_required_called());
3334 EXPECT_EQ(1, network_delegate.created_requests());
3335 EXPECT_EQ(0, network_delegate.destroyed_requests());
3336 }
3337 EXPECT_EQ(1, network_delegate.destroyed_requests());
3338}
3339
3340// Tests that the network delegate can asynchronously complete OnAuthRequired
3341// by cancelling authentication.
3342TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3343 ASSERT_TRUE(test_server_.Start());
3344
3345 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303346 BlockingNetworkDelegate network_delegate(
3347 BlockingNetworkDelegate::AUTO_CALLBACK);
3348 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363349 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363350 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3351
[email protected]ef2bf422012-05-11 03:27:093352 TestURLRequestContext context(true);
3353 context.set_network_delegate(&network_delegate);
3354 context.Init();
[email protected]c2911d72011-10-03 22:16:363355
3356 {
3357 GURL url(test_server_.GetURL("auth-basic"));
[email protected]2ca01e52013-10-31 22:05:193358 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
[email protected]c2911d72011-10-03 22:16:363359 r.Start();
[email protected]255620da2013-08-19 13:14:293360 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363361
3362 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3363 EXPECT_EQ(OK, r.status().error());
3364 EXPECT_EQ(401, r.GetResponseCode());
3365 EXPECT_FALSE(d.auth_required_called());
3366 EXPECT_EQ(1, network_delegate.created_requests());
3367 EXPECT_EQ(0, network_delegate.destroyed_requests());
3368 }
3369 EXPECT_EQ(1, network_delegate.destroyed_requests());
3370}
3371
[email protected]9045b8822012-01-13 20:35:353372// Tests that we can handle when a network request was canceled while we were
3373// waiting for the network delegate.
3374// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3375TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3376 ASSERT_TRUE(test_server_.Start());
3377
3378 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303379 BlockingNetworkDelegate network_delegate(
3380 BlockingNetworkDelegate::USER_CALLBACK);
3381 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353382
[email protected]ef2bf422012-05-11 03:27:093383 TestURLRequestContext context(true);
3384 context.set_network_delegate(&network_delegate);
3385 context.Init();
[email protected]9045b8822012-01-13 20:35:353386
3387 {
[email protected]2ca01e52013-10-31 22:05:193388 URLRequest r(
3389 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353390
3391 r.Start();
[email protected]255620da2013-08-19 13:14:293392 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303393 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3394 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353395 EXPECT_EQ(0, network_delegate.completed_requests());
3396 // Cancel before callback.
3397 r.Cancel();
3398 // Ensure that network delegate is notified.
3399 EXPECT_EQ(1, network_delegate.completed_requests());
3400 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3401 EXPECT_EQ(ERR_ABORTED, r.status().error());
3402 EXPECT_EQ(1, network_delegate.created_requests());
3403 EXPECT_EQ(0, network_delegate.destroyed_requests());
3404 }
3405 EXPECT_EQ(1, network_delegate.destroyed_requests());
3406}
3407
3408// Tests that we can handle when a network request was canceled while we were
3409// waiting for the network delegate.
3410// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3411TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3412 ASSERT_TRUE(test_server_.Start());
3413
3414 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303415 BlockingNetworkDelegate network_delegate(
3416 BlockingNetworkDelegate::USER_CALLBACK);
3417 network_delegate.set_block_on(
3418 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353419
[email protected]ef2bf422012-05-11 03:27:093420 TestURLRequestContext context(true);
3421 context.set_network_delegate(&network_delegate);
3422 context.Init();
[email protected]9045b8822012-01-13 20:35:353423
3424 {
[email protected]2ca01e52013-10-31 22:05:193425 URLRequest r(
3426 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353427
3428 r.Start();
[email protected]255620da2013-08-19 13:14:293429 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303430 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3431 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353432 EXPECT_EQ(0, network_delegate.completed_requests());
3433 // Cancel before callback.
3434 r.Cancel();
3435 // Ensure that network delegate is notified.
3436 EXPECT_EQ(1, network_delegate.completed_requests());
3437 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3438 EXPECT_EQ(ERR_ABORTED, r.status().error());
3439 EXPECT_EQ(1, network_delegate.created_requests());
3440 EXPECT_EQ(0, network_delegate.destroyed_requests());
3441 }
3442 EXPECT_EQ(1, network_delegate.destroyed_requests());
3443}
3444
3445// Tests that we can handle when a network request was canceled while we were
3446// waiting for the network delegate.
3447// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3448TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3449 ASSERT_TRUE(test_server_.Start());
3450
3451 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303452 BlockingNetworkDelegate network_delegate(
3453 BlockingNetworkDelegate::USER_CALLBACK);
3454 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353455
[email protected]ef2bf422012-05-11 03:27:093456 TestURLRequestContext context(true);
3457 context.set_network_delegate(&network_delegate);
3458 context.Init();
[email protected]9045b8822012-01-13 20:35:353459
3460 {
[email protected]2ca01e52013-10-31 22:05:193461 URLRequest r(
3462 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353463
3464 r.Start();
[email protected]255620da2013-08-19 13:14:293465 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303466 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3467 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353468 EXPECT_EQ(0, network_delegate.completed_requests());
3469 // Cancel before callback.
3470 r.Cancel();
3471 // Ensure that network delegate is notified.
3472 EXPECT_EQ(1, network_delegate.completed_requests());
3473 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3474 EXPECT_EQ(ERR_ABORTED, r.status().error());
3475 EXPECT_EQ(1, network_delegate.created_requests());
3476 EXPECT_EQ(0, network_delegate.destroyed_requests());
3477 }
3478 EXPECT_EQ(1, network_delegate.destroyed_requests());
3479}
3480
3481// Tests that we can handle when a network request was canceled while we were
3482// waiting for the network delegate.
3483// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023484TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353485 ASSERT_TRUE(test_server_.Start());
3486
3487 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303488 BlockingNetworkDelegate network_delegate(
3489 BlockingNetworkDelegate::USER_CALLBACK);
3490 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353491
[email protected]ef2bf422012-05-11 03:27:093492 TestURLRequestContext context(true);
3493 context.set_network_delegate(&network_delegate);
3494 context.Init();
[email protected]9045b8822012-01-13 20:35:353495
3496 {
[email protected]2ca01e52013-10-31 22:05:193497 URLRequest r(
3498 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, &context);
[email protected]9045b8822012-01-13 20:35:353499
3500 r.Start();
[email protected]255620da2013-08-19 13:14:293501 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303502 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3503 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353504 EXPECT_EQ(0, network_delegate.completed_requests());
3505 // Cancel before callback.
3506 r.Cancel();
3507 // Ensure that network delegate is notified.
3508 EXPECT_EQ(1, network_delegate.completed_requests());
3509 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3510 EXPECT_EQ(ERR_ABORTED, r.status().error());
3511 EXPECT_EQ(1, network_delegate.created_requests());
3512 EXPECT_EQ(0, network_delegate.destroyed_requests());
3513 }
3514 EXPECT_EQ(1, network_delegate.destroyed_requests());
3515}
3516
[email protected]95409e12010-08-17 20:07:113517// In this unit test, we're using the HTTPTestServer as a proxy server and
3518// issuing a CONNECT request with the magic host name "www.server-auth.com".
3519// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353520TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113521 ASSERT_TRUE(test_server_.Start());
3522
[email protected]ceefd7fd2012-11-29 00:36:243523 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043524 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193525 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503526
[email protected]dc651782009-02-14 01:45:083527 TestDelegate d;
3528 {
[email protected]2ca01e52013-10-31 22:05:193529 URLRequest r(
3530 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, &context);
[email protected]dc651782009-02-14 01:45:083531
3532 r.Start();
3533 EXPECT_TRUE(r.is_pending());
3534
[email protected]255620da2013-08-19 13:14:293535 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083536
[email protected]7461a402011-03-24 23:19:513537 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d8fc4722014-06-13 13:17:153538 // The proxy server is not set before failure.
3539 EXPECT_TRUE(r.proxy_server().IsEmpty());
[email protected]d0cc35b2011-09-08 12:02:053540 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:083541 }
3542}
3543
[email protected]b89290212009-08-14 22:37:353544TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113545 ASSERT_TRUE(test_server_.Start());
3546
initial.commit586acc5fe2008-07-26 22:42:523547 TestDelegate d;
3548 {
[email protected]2ca01e52013-10-31 22:05:193549 URLRequest r(test_server_.GetURL(std::string()),
3550 DEFAULT_PRIORITY,
3551 &d,
3552 &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523553
3554 r.Start();
3555 EXPECT_TRUE(r.is_pending());
3556
[email protected]255620da2013-08-19 13:14:293557 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523558
3559 EXPECT_EQ(1, d.response_started_count());
3560 EXPECT_FALSE(d.received_data_before_response());
3561 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193562 EXPECT_EQ(test_server_.host_port_pair().host(),
3563 r.GetSocketAddress().host());
3564 EXPECT_EQ(test_server_.host_port_pair().port(),
3565 r.GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163566
[email protected]9e743cd2010-03-16 07:03:533567 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523568 }
initial.commit586acc5fe2008-07-26 22:42:523569}
3570
[email protected]263163f2012-06-14 22:40:343571// This test has the server send a large number of cookies to the client.
3572// To ensure that no number of cookies causes a crash, a galloping binary
3573// search is used to estimate that maximum number of cookies that are accepted
3574// by the browser. Beyond the maximum number, the request will fail with
3575// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303576#if defined(OS_WIN)
3577// http://crbug.com/177916
3578#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3579#else
3580#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3581#endif // defined(OS_WIN)
3582TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343583 ASSERT_TRUE(test_server_.Start());
3584
3585 int lower_bound = 0;
3586 int upper_bound = 1;
3587
3588 // Double the number of cookies until the response header limits are
3589 // exceeded.
3590 while (DoManyCookiesRequest(upper_bound)) {
3591 lower_bound = upper_bound;
3592 upper_bound *= 2;
3593 ASSERT_LT(upper_bound, 1000000);
3594 }
3595
3596 int tolerance = upper_bound * 0.005;
3597 if (tolerance < 2)
3598 tolerance = 2;
3599
3600 // Perform a binary search to find the highest possible number of cookies,
3601 // within the desired tolerance.
3602 while (upper_bound - lower_bound >= tolerance) {
3603 int num_cookies = (lower_bound + upper_bound) / 2;
3604
3605 if (DoManyCookiesRequest(num_cookies))
3606 lower_bound = num_cookies;
3607 else
3608 upper_bound = num_cookies;
3609 }
3610 // Success: the test did not crash.
3611}
3612
[email protected]b89290212009-08-14 22:37:353613TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113614 ASSERT_TRUE(test_server_.Start());
3615
initial.commit586acc5fe2008-07-26 22:42:523616 TestDelegate d;
3617 {
[email protected]2ca01e52013-10-31 22:05:193618 URLRequest r(test_server_.GetURL(std::string()),
3619 DEFAULT_PRIORITY,
3620 &d,
3621 &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523622
3623 r.Start();
3624 EXPECT_TRUE(r.is_pending());
3625
[email protected]255620da2013-08-19 13:14:293626 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523627
3628 EXPECT_EQ(1, d.response_started_count());
3629 EXPECT_FALSE(d.received_data_before_response());
3630 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193631 EXPECT_EQ(test_server_.host_port_pair().host(),
3632 r.GetSocketAddress().host());
3633 EXPECT_EQ(test_server_.host_port_pair().port(),
3634 r.GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523635 }
[email protected]5d7b373e2009-09-02 07:19:033636}
3637
[email protected]79e1fd62013-06-20 06:50:043638TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3639 ASSERT_TRUE(test_server_.Start());
3640
3641 TestDelegate d;
3642 {
3643 GURL test_url(test_server_.GetURL(std::string()));
[email protected]2ca01e52013-10-31 22:05:193644 URLRequest r(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:043645
3646 HttpRequestHeaders headers;
3647 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3648
3649 r.Start();
3650 EXPECT_TRUE(r.is_pending());
3651
[email protected]255620da2013-08-19 13:14:293652 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043653
3654 EXPECT_EQ(1, d.response_started_count());
3655 EXPECT_FALSE(d.received_data_before_response());
3656 EXPECT_NE(0, d.bytes_received());
3657 EXPECT_EQ(test_server_.host_port_pair().host(),
3658 r.GetSocketAddress().host());
3659 EXPECT_EQ(test_server_.host_port_pair().port(),
3660 r.GetSocketAddress().port());
3661
3662 EXPECT_TRUE(d.have_full_request_headers());
3663 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3664 }
3665}
3666
[email protected]58e32bb2013-01-21 18:23:253667TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3668 ASSERT_TRUE(test_server_.Start());
3669
3670 TestDelegate d;
3671 {
[email protected]2ca01e52013-10-31 22:05:193672 URLRequest r(test_server_.GetURL(std::string()),
3673 DEFAULT_PRIORITY,
3674 &d,
3675 &default_context_);
[email protected]58e32bb2013-01-21 18:23:253676
3677 r.Start();
3678 EXPECT_TRUE(r.is_pending());
3679
[email protected]255620da2013-08-19 13:14:293680 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253681
3682 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173683 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253684 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3685
3686 EXPECT_EQ(1, d.response_started_count());
3687 EXPECT_FALSE(d.received_data_before_response());
3688 EXPECT_NE(0, d.bytes_received());
3689 EXPECT_EQ(test_server_.host_port_pair().host(),
3690 r.GetSocketAddress().host());
3691 EXPECT_EQ(test_server_.host_port_pair().port(),
3692 r.GetSocketAddress().port());
3693 }
3694}
3695
[email protected]aad63572011-05-24 20:14:393696TEST_F(URLRequestTestHTTP, GetZippedTest) {
3697 ASSERT_TRUE(test_server_.Start());
3698
3699 // Parameter that specifies the Content-Length field in the response:
3700 // C - Compressed length.
3701 // U - Uncompressed length.
3702 // L - Large length (larger than both C & U).
3703 // M - Medium length (between C & U).
3704 // S - Small length (smaller than both C & U).
3705 const char test_parameters[] = "CULMS";
3706 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3707 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:443708 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:393709 // S has too little data, but we seem to accept it.
3710 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:373711 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:393712
3713 for (int i = 0; i < num_tests ; i++) {
3714 TestDelegate d;
3715 {
3716 std::string test_file =
3717 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3718 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:393719
[email protected]ceefd7fd2012-11-29 00:36:243720 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:093721 TestURLRequestContext context(true);
3722 context.set_network_delegate(&network_delegate);
3723 context.Init();
[email protected]87a09a92011-07-14 15:50:503724
[email protected]2ca01e52013-10-31 22:05:193725 URLRequest r(
3726 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, &context);
[email protected]aad63572011-05-24 20:14:393727 r.Start();
3728 EXPECT_TRUE(r.is_pending());
3729
[email protected]255620da2013-08-19 13:14:293730 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:393731
3732 EXPECT_EQ(1, d.response_started_count());
3733 EXPECT_FALSE(d.received_data_before_response());
3734 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3735 << " status = " << r.status().status()
[email protected]d0cc35b2011-09-08 12:02:053736 << " error = " << r.status().error();
[email protected]aad63572011-05-24 20:14:393737 if (test_expect_success[i]) {
3738 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3739 << " Parameter = \"" << test_file << "\"";
3740 } else {
3741 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]5543cbb2012-04-20 16:35:233742 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
[email protected]aad63572011-05-24 20:14:393743 << " Parameter = \"" << test_file << "\"";
3744 }
3745 }
3746 }
3747}
3748
[email protected]c044616e2013-02-20 02:01:263749TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
[email protected]95409e12010-08-17 20:07:113750 ASSERT_TRUE(test_server_.Start());
3751
[email protected]ce7d0cbc2013-05-03 18:57:223752 SpawnedTestServer https_test_server(
3753 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:153754 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:113755 ASSERT_TRUE(https_test_server.Start());
[email protected]7844480a2009-12-16 21:18:583756
3757 // An https server is sent a request with an https referer,
3758 // and responds with a redirect to an http url. The http
3759 // server should not be sent the referer.
[email protected]007b3f82013-04-09 08:46:453760 GURL http_destination = test_server_.GetURL(std::string());
[email protected]7844480a2009-12-16 21:18:583761 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193762 URLRequest req(
3763 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3764 DEFAULT_PRIORITY,
3765 &d,
3766 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:133767 req.SetReferrer("https://www.referrer.com/");
[email protected]7844480a2009-12-16 21:18:583768 req.Start();
[email protected]255620da2013-08-19 13:14:293769 base::RunLoop().Run();
[email protected]7844480a2009-12-16 21:18:583770
3771 EXPECT_EQ(1, d.response_started_count());
3772 EXPECT_EQ(1, d.received_redirect_count());
3773 EXPECT_EQ(http_destination, req.url());
3774 EXPECT_EQ(std::string(), req.referrer());
3775}
3776
[email protected]58e32bb2013-01-21 18:23:253777TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3778 ASSERT_TRUE(test_server_.Start());
3779
[email protected]007b3f82013-04-09 08:46:453780 GURL destination_url = test_server_.GetURL(std::string());
3781 GURL original_url =
3782 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:253783 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193784 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]58e32bb2013-01-21 18:23:253785 req.Start();
[email protected]255620da2013-08-19 13:14:293786 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253787
3788 EXPECT_EQ(1, d.response_started_count());
3789 EXPECT_EQ(1, d.received_redirect_count());
3790 EXPECT_EQ(destination_url, req.url());
3791 EXPECT_EQ(original_url, req.original_url());
3792 ASSERT_EQ(2U, req.url_chain().size());
3793 EXPECT_EQ(original_url, req.url_chain()[0]);
3794 EXPECT_EQ(destination_url, req.url_chain()[1]);
3795
3796 LoadTimingInfo load_timing_info_before_redirect;
3797 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3798 &load_timing_info_before_redirect));
3799 TestLoadTimingNotReused(load_timing_info_before_redirect,
3800 CONNECT_TIMING_HAS_DNS_TIMES);
3801
3802 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173803 req.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253804 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3805
3806 // Check that a new socket was used on redirect, since the server does not
3807 // supposed keep-alive sockets, and that the times before the redirect are
3808 // before the ones recorded for the second request.
3809 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3810 load_timing_info.socket_log_id);
3811 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3812 load_timing_info.connect_timing.connect_start);
3813}
3814
[email protected]8f1ac082011-04-19 21:14:133815TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3816 ASSERT_TRUE(test_server_.Start());
3817
[email protected]007b3f82013-04-09 08:46:453818 GURL destination_url = test_server_.GetURL(std::string());
3819 GURL middle_redirect_url =
3820 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:133821 GURL original_url = test_server_.GetURL(
3822 "server-redirect?" + middle_redirect_url.spec());
3823 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:193824 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]8f1ac082011-04-19 21:14:133825 req.Start();
[email protected]255620da2013-08-19 13:14:293826 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:133827
3828 EXPECT_EQ(1, d.response_started_count());
3829 EXPECT_EQ(2, d.received_redirect_count());
3830 EXPECT_EQ(destination_url, req.url());
3831 EXPECT_EQ(original_url, req.original_url());
3832 ASSERT_EQ(3U, req.url_chain().size());
3833 EXPECT_EQ(original_url, req.url_chain()[0]);
3834 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3835 EXPECT_EQ(destination_url, req.url_chain()[2]);
3836}
3837
[email protected]abe1c4a2013-10-25 19:28:513838// First and second pieces of information logged by delegates to URLRequests.
3839const char kFirstDelegateInfo[] = "Wonderful delegate";
3840const char kSecondDelegateInfo[] = "Exciting delegate";
3841
3842// Logs delegate information to a URLRequest. The first string is logged
3843// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3844// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3845// another asynchronous call is used to clear the delegate information
3846// before calling a callback. The object then deletes itself.
3847class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3848 public:
3849 typedef base::Callback<void()> Callback;
3850
3851 // Each time delegate information is added to the URLRequest, the resulting
3852 // load state is checked. The expected load state after each request is
3853 // passed in as an argument.
3854 static void Run(URLRequest* url_request,
3855 LoadState expected_first_load_state,
3856 LoadState expected_second_load_state,
3857 LoadState expected_third_load_state,
3858 const Callback& callback) {
3859 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3860 url_request,
3861 expected_first_load_state,
3862 expected_second_load_state,
3863 expected_third_load_state,
3864 callback);
3865 logger->Start();
3866 }
3867
3868 // Checks that the log entries, starting with log_position, contain the
3869 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3870 // recorded. Returns the index of entry after the expected number of
3871 // events this logged, or entries.size() if there aren't enough entries.
3872 static size_t CheckDelegateInfo(
3873 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3874 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3875 if (log_position + 3 >= entries.size()) {
3876 ADD_FAILURE() << "Not enough log entries";
3877 return entries.size();
3878 }
3879 std::string delegate_info;
3880 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3881 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3882 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3883 &delegate_info));
3884 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3885
3886 ++log_position;
3887 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3888 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3889
3890 ++log_position;
3891 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3892 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3893 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3894 &delegate_info));
3895 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3896
3897 ++log_position;
3898 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3899 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3900
3901 return log_position + 1;
3902 }
3903
[email protected]1826a402014-01-08 15:40:483904 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3905 // Returns the position of the end message.
3906 static size_t ExpectBeforeNetworkEvents(
3907 const CapturingNetLog::CapturedEntryList& entries,
3908 size_t log_position) {
3909 log_position =
3910 ExpectLogContainsSomewhereAfter(entries,
3911 log_position,
3912 NetLog::TYPE_URL_REQUEST_DELEGATE,
3913 NetLog::PHASE_BEGIN);
3914 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3915 entries[log_position + 1].type);
3916 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3917 return log_position + 1;
3918 }
3919
[email protected]abe1c4a2013-10-25 19:28:513920 private:
3921 friend class base::RefCounted<AsyncDelegateLogger>;
3922
3923 AsyncDelegateLogger(URLRequest* url_request,
3924 LoadState expected_first_load_state,
3925 LoadState expected_second_load_state,
3926 LoadState expected_third_load_state,
3927 const Callback& callback)
3928 : url_request_(url_request),
3929 expected_first_load_state_(expected_first_load_state),
3930 expected_second_load_state_(expected_second_load_state),
3931 expected_third_load_state_(expected_third_load_state),
3932 callback_(callback) {
3933 }
3934
3935 ~AsyncDelegateLogger() {}
3936
3937 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:533938 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:513939 LoadStateWithParam load_state = url_request_->GetLoadState();
3940 EXPECT_EQ(expected_first_load_state_, load_state.state);
3941 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3942 base::MessageLoop::current()->PostTask(
3943 FROM_HERE,
3944 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3945 }
3946
3947 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:533948 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:513949 LoadStateWithParam load_state = url_request_->GetLoadState();
3950 EXPECT_EQ(expected_second_load_state_, load_state.state);
3951 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3952 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3953 } else {
3954 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3955 }
3956 base::MessageLoop::current()->PostTask(
3957 FROM_HERE,
3958 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3959 }
3960
3961 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:533962 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:513963 LoadStateWithParam load_state = url_request_->GetLoadState();
3964 EXPECT_EQ(expected_third_load_state_, load_state.state);
3965 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:083966 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:513967 callback_.Run();
3968 }
3969
3970 URLRequest* url_request_;
3971 const int expected_first_load_state_;
3972 const int expected_second_load_state_;
3973 const int expected_third_load_state_;
3974 const Callback callback_;
3975
3976 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3977};
3978
3979// NetworkDelegate that logs delegate information before a request is started,
3980// before headers are sent, when headers are read, and when auth information
3981// is requested. Uses AsyncDelegateLogger.
3982class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3983 public:
3984 AsyncLoggingNetworkDelegate() {}
3985 virtual ~AsyncLoggingNetworkDelegate() {}
3986
3987 // NetworkDelegate implementation.
3988 virtual int OnBeforeURLRequest(URLRequest* request,
3989 const CompletionCallback& callback,
3990 GURL* new_url) OVERRIDE {
3991 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3992 return RunCallbackAsynchronously(request, callback);
3993 }
3994
3995 virtual int OnBeforeSendHeaders(URLRequest* request,
3996 const CompletionCallback& callback,
3997 HttpRequestHeaders* headers) OVERRIDE {
3998 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3999 return RunCallbackAsynchronously(request, callback);
4000 }
4001
4002 virtual int OnHeadersReceived(
4003 URLRequest* request,
4004 const CompletionCallback& callback,
4005 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164006 scoped_refptr<HttpResponseHeaders>* override_response_headers,
4007 GURL* allowed_unsafe_redirect_url) OVERRIDE {
4008 TestNetworkDelegate::OnHeadersReceived(request,
4009 callback,
[email protected]abe1c4a2013-10-25 19:28:514010 original_response_headers,
[email protected]5f714132014-03-26 10:41:164011 override_response_headers,
4012 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514013 return RunCallbackAsynchronously(request, callback);
4014 }
4015
4016 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
4017 URLRequest* request,
4018 const AuthChallengeInfo& auth_info,
4019 const AuthCallback& callback,
4020 AuthCredentials* credentials) OVERRIDE {
4021 AsyncDelegateLogger::Run(
4022 request,
4023 LOAD_STATE_WAITING_FOR_DELEGATE,
4024 LOAD_STATE_WAITING_FOR_DELEGATE,
4025 LOAD_STATE_WAITING_FOR_DELEGATE,
4026 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4027 callback, credentials));
4028 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4029 }
4030
4031 private:
4032 static int RunCallbackAsynchronously(
4033 URLRequest* request,
4034 const CompletionCallback& callback) {
4035 AsyncDelegateLogger::Run(
4036 request,
4037 LOAD_STATE_WAITING_FOR_DELEGATE,
4038 LOAD_STATE_WAITING_FOR_DELEGATE,
4039 LOAD_STATE_WAITING_FOR_DELEGATE,
4040 base::Bind(callback, OK));
4041 return ERR_IO_PENDING;
4042 }
4043
4044 static void SetAuthAndResume(const AuthCallback& callback,
4045 AuthCredentials* credentials) {
4046 *credentials = AuthCredentials(kUser, kSecret);
4047 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4048 }
4049
4050 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4051};
4052
4053// URLRequest::Delegate that logs delegate information when the headers
4054// are received, when each read completes, and during redirects. Uses
4055// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4056//
4057// Inherits from TestDelegate to reuse the TestDelegate code to handle
4058// advancing to the next step in most cases, as well as cancellation.
4059class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4060 public:
4061 enum CancelStage {
4062 NO_CANCEL = 0,
4063 CANCEL_ON_RECEIVED_REDIRECT,
4064 CANCEL_ON_RESPONSE_STARTED,
4065 CANCEL_ON_READ_COMPLETED
4066 };
4067
4068 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4069 : cancel_stage_(cancel_stage) {
4070 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4071 set_cancel_in_received_redirect(true);
4072 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4073 set_cancel_in_response_started(true);
4074 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4075 set_cancel_in_received_data(true);
4076 }
4077 virtual ~AsyncLoggingUrlRequestDelegate() {}
4078
4079 // URLRequest::Delegate implementation:
4080 void virtual OnReceivedRedirect(URLRequest* request,
4081 const GURL& new_url,
4082 bool* defer_redirect) OVERRIDE {
4083 *defer_redirect = true;
4084 AsyncDelegateLogger::Run(
4085 request,
4086 LOAD_STATE_WAITING_FOR_DELEGATE,
4087 LOAD_STATE_WAITING_FOR_DELEGATE,
4088 LOAD_STATE_WAITING_FOR_DELEGATE,
4089 base::Bind(
4090 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4091 base::Unretained(this), request, new_url));
4092 }
4093
4094 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4095 AsyncDelegateLogger::Run(
4096 request,
4097 LOAD_STATE_WAITING_FOR_DELEGATE,
4098 LOAD_STATE_WAITING_FOR_DELEGATE,
4099 LOAD_STATE_WAITING_FOR_DELEGATE,
4100 base::Bind(
4101 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4102 base::Unretained(this), request));
4103 }
4104
4105 virtual void OnReadCompleted(URLRequest* request,
4106 int bytes_read) OVERRIDE {
4107 AsyncDelegateLogger::Run(
4108 request,
4109 LOAD_STATE_IDLE,
4110 LOAD_STATE_IDLE,
4111 LOAD_STATE_IDLE,
4112 base::Bind(
4113 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4114 base::Unretained(this), request, bytes_read));
4115 }
4116
4117 private:
4118 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4119 const GURL& new_url) {
4120 bool defer_redirect = false;
4121 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
4122 // FollowDeferredRedirect should not be called after cancellation.
4123 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4124 return;
4125 if (!defer_redirect)
4126 request->FollowDeferredRedirect();
4127 }
4128
4129 void OnResponseStartedLoggingComplete(URLRequest* request) {
4130 // The parent class continues the request.
4131 TestDelegate::OnResponseStarted(request);
4132 }
4133
4134 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4135 // The parent class continues the request.
4136 TestDelegate::OnReadCompleted(request, bytes_read);
4137 }
4138
4139 const CancelStage cancel_stage_;
4140
4141 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4142};
4143
4144// Tests handling of delegate info before a request starts.
4145TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4146 ASSERT_TRUE(test_server_.Start());
4147
4148 TestDelegate request_delegate;
4149 TestURLRequestContext context(true);
4150 context.set_network_delegate(NULL);
4151 context.set_net_log(&net_log_);
4152 context.Init();
4153
4154 {
4155 URLRequest r(test_server_.GetURL("empty.html"),
[email protected]2ca01e52013-10-31 22:05:194156 DEFAULT_PRIORITY,
4157 &request_delegate,
4158 &context);
[email protected]abe1c4a2013-10-25 19:28:514159 LoadStateWithParam load_state = r.GetLoadState();
4160 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084161 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514162
4163 AsyncDelegateLogger::Run(
4164 &r,
4165 LOAD_STATE_WAITING_FOR_DELEGATE,
4166 LOAD_STATE_WAITING_FOR_DELEGATE,
4167 LOAD_STATE_IDLE,
4168 base::Bind(&URLRequest::Start, base::Unretained(&r)));
4169
4170 base::RunLoop().Run();
4171
4172 EXPECT_EQ(200, r.GetResponseCode());
4173 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4174 }
4175
4176 CapturingNetLog::CapturedEntryList entries;
4177 net_log_.GetEntries(&entries);
4178 size_t log_position = ExpectLogContainsSomewhereAfter(
4179 entries,
4180 0,
4181 NetLog::TYPE_DELEGATE_INFO,
4182 NetLog::PHASE_BEGIN);
4183
4184 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4185
4186 // Nothing else should add any delegate info to the request.
4187 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4188 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4189}
4190
4191// Tests handling of delegate info from a network delegate.
4192TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4193 ASSERT_TRUE(test_server_.Start());
4194
4195 TestDelegate request_delegate;
4196 AsyncLoggingNetworkDelegate network_delegate;
4197 TestURLRequestContext context(true);
4198 context.set_network_delegate(&network_delegate);
4199 context.set_net_log(&net_log_);
4200 context.Init();
4201
4202 {
4203 URLRequest r(test_server_.GetURL("simple.html"),
[email protected]2ca01e52013-10-31 22:05:194204 DEFAULT_PRIORITY,
4205 &request_delegate,
4206 &context);
[email protected]abe1c4a2013-10-25 19:28:514207 LoadStateWithParam load_state = r.GetLoadState();
4208 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084209 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514210
4211 r.Start();
4212 base::RunLoop().Run();
4213
4214 EXPECT_EQ(200, r.GetResponseCode());
4215 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4216 EXPECT_EQ(1, network_delegate.created_requests());
4217 EXPECT_EQ(0, network_delegate.destroyed_requests());
4218 }
4219 EXPECT_EQ(1, network_delegate.destroyed_requests());
4220
4221 size_t log_position = 0;
4222 CapturingNetLog::CapturedEntryList entries;
4223 net_log_.GetEntries(&entries);
4224 for (size_t i = 0; i < 3; ++i) {
4225 log_position = ExpectLogContainsSomewhereAfter(
4226 entries,
4227 log_position + 1,
4228 NetLog::TYPE_URL_REQUEST_DELEGATE,
4229 NetLog::PHASE_BEGIN);
4230
4231 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4232 log_position + 1);
4233
4234 ASSERT_LT(log_position, entries.size());
4235 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4236 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484237
4238 if (i == 1) {
4239 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4240 entries, log_position + 1);
4241 }
[email protected]abe1c4a2013-10-25 19:28:514242 }
4243
4244 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4245 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4246}
4247
4248// Tests handling of delegate info from a network delegate in the case of an
4249// HTTP redirect.
4250TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4251 ASSERT_TRUE(test_server_.Start());
4252
4253 TestDelegate request_delegate;
4254 AsyncLoggingNetworkDelegate network_delegate;
4255 TestURLRequestContext context(true);
4256 context.set_network_delegate(&network_delegate);
4257 context.set_net_log(&net_log_);
4258 context.Init();
4259
4260 {
4261 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194262 DEFAULT_PRIORITY,
4263 &request_delegate,
4264 &context);
[email protected]abe1c4a2013-10-25 19:28:514265 LoadStateWithParam load_state = r.GetLoadState();
4266 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084267 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514268
4269 r.Start();
4270 base::RunLoop().Run();
4271
4272 EXPECT_EQ(200, r.GetResponseCode());
4273 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4274 EXPECT_EQ(2, network_delegate.created_requests());
4275 EXPECT_EQ(0, network_delegate.destroyed_requests());
4276 }
4277 EXPECT_EQ(1, network_delegate.destroyed_requests());
4278
4279 size_t log_position = 0;
4280 CapturingNetLog::CapturedEntryList entries;
4281 net_log_.GetEntries(&entries);
4282 // The NetworkDelegate logged information in OnBeforeURLRequest,
4283 // OnBeforeSendHeaders, and OnHeadersReceived.
4284 for (size_t i = 0; i < 3; ++i) {
4285 log_position = ExpectLogContainsSomewhereAfter(
4286 entries,
4287 log_position + 1,
4288 NetLog::TYPE_URL_REQUEST_DELEGATE,
4289 NetLog::PHASE_BEGIN);
4290
4291 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4292 log_position + 1);
4293
4294 ASSERT_LT(log_position, entries.size());
4295 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4296 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484297
4298 if (i == 1) {
4299 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4300 entries, log_position + 1);
4301 }
[email protected]abe1c4a2013-10-25 19:28:514302 }
4303
4304 // The URLRequest::Delegate then gets informed about the redirect.
4305 log_position = ExpectLogContainsSomewhereAfter(
4306 entries,
4307 log_position + 1,
4308 NetLog::TYPE_URL_REQUEST_DELEGATE,
4309 NetLog::PHASE_BEGIN);
4310
4311 // The NetworkDelegate logged information in the same three events as before.
4312 for (size_t i = 0; i < 3; ++i) {
4313 log_position = ExpectLogContainsSomewhereAfter(
4314 entries,
4315 log_position + 1,
4316 NetLog::TYPE_URL_REQUEST_DELEGATE,
4317 NetLog::PHASE_BEGIN);
4318
4319 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4320 log_position + 1);
4321
4322 ASSERT_LT(log_position, entries.size());
4323 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4324 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4325 }
4326
4327 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4328 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4329}
4330
4331// Tests handling of delegate info from a network delegate in the case of HTTP
4332// AUTH.
4333TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4334 ASSERT_TRUE(test_server_.Start());
4335
4336 TestDelegate request_delegate;
4337 AsyncLoggingNetworkDelegate network_delegate;
4338 TestURLRequestContext context(true);
4339 context.set_network_delegate(&network_delegate);
4340 context.set_net_log(&net_log_);
4341 context.Init();
4342
4343 {
4344 URLRequest r(test_server_.GetURL("auth-basic"),
[email protected]2ca01e52013-10-31 22:05:194345 DEFAULT_PRIORITY,
4346 &request_delegate,
4347 &context);
[email protected]abe1c4a2013-10-25 19:28:514348 LoadStateWithParam load_state = r.GetLoadState();
4349 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084350 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514351
4352 r.Start();
4353 base::RunLoop().Run();
4354
4355 EXPECT_EQ(200, r.GetResponseCode());
4356 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4357 EXPECT_EQ(1, network_delegate.created_requests());
4358 EXPECT_EQ(0, network_delegate.destroyed_requests());
4359 }
4360 EXPECT_EQ(1, network_delegate.destroyed_requests());
4361
4362 size_t log_position = 0;
4363 CapturingNetLog::CapturedEntryList entries;
4364 net_log_.GetEntries(&entries);
4365 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4366 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4367 // OnBeforeURLRequest and OnBeforeSendHeaders.
4368 for (size_t i = 0; i < 6; ++i) {
4369 log_position = ExpectLogContainsSomewhereAfter(
4370 entries,
4371 log_position + 1,
4372 NetLog::TYPE_URL_REQUEST_DELEGATE,
4373 NetLog::PHASE_BEGIN);
4374
4375 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4376 log_position + 1);
4377
4378 ASSERT_LT(log_position, entries.size());
4379 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4380 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484381
4382 if (i == 1) {
4383 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4384 entries, log_position + 1);
4385 }
[email protected]abe1c4a2013-10-25 19:28:514386 }
4387
4388 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4389 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4390}
4391
4392// Tests handling of delegate info from a URLRequest::Delegate.
4393TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4394 ASSERT_TRUE(test_server_.Start());
4395
4396 AsyncLoggingUrlRequestDelegate request_delegate(
4397 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4398 TestURLRequestContext context(true);
4399 context.set_network_delegate(NULL);
4400 context.set_net_log(&net_log_);
4401 context.Init();
4402
4403 {
4404 // A chunked response with delays between chunks is used to make sure that
4405 // attempts by the URLRequest delegate to log information while reading the
4406 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484407 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514408 // that it occurs.
4409 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
[email protected]2ca01e52013-10-31 22:05:194410 DEFAULT_PRIORITY,
4411 &request_delegate,
4412 &context);
[email protected]abe1c4a2013-10-25 19:28:514413 LoadStateWithParam load_state = r.GetLoadState();
4414 r.Start();
4415 base::RunLoop().Run();
4416
4417 EXPECT_EQ(200, r.GetResponseCode());
4418 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4419 }
4420
4421 CapturingNetLog::CapturedEntryList entries;
4422 net_log_.GetEntries(&entries);
4423
[email protected]1826a402014-01-08 15:40:484424 size_t log_position = 0;
4425
4426 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4427 entries, log_position);
4428
[email protected]abe1c4a2013-10-25 19:28:514429 // The delegate info should only have been logged on header complete. Other
4430 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484431 log_position =
4432 ExpectLogContainsSomewhereAfter(entries,
4433 log_position + 1,
4434 NetLog::TYPE_URL_REQUEST_DELEGATE,
4435 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514436
4437 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4438 log_position + 1);
4439
4440 ASSERT_LT(log_position, entries.size());
4441 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4442 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4443
4444 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4445 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4446 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4447 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4448}
4449
4450// Tests handling of delegate info from a URLRequest::Delegate in the case of
4451// an HTTP redirect.
4452TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4453 ASSERT_TRUE(test_server_.Start());
4454
4455 AsyncLoggingUrlRequestDelegate request_delegate(
4456 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4457 TestURLRequestContext context(true);
4458 context.set_network_delegate(NULL);
4459 context.set_net_log(&net_log_);
4460 context.Init();
4461
4462 {
4463 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194464 DEFAULT_PRIORITY,
4465 &request_delegate,
4466 &context);
[email protected]abe1c4a2013-10-25 19:28:514467 LoadStateWithParam load_state = r.GetLoadState();
4468 r.Start();
4469 base::RunLoop().Run();
4470
4471 EXPECT_EQ(200, r.GetResponseCode());
4472 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4473 }
4474
4475 CapturingNetLog::CapturedEntryList entries;
4476 net_log_.GetEntries(&entries);
4477
4478 // Delegate info should only have been logged in OnReceivedRedirect and
4479 // OnResponseStarted.
4480 size_t log_position = 0;
4481 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484482 if (i == 0) {
4483 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4484 entries, log_position) + 1;
4485 }
4486
[email protected]abe1c4a2013-10-25 19:28:514487 log_position = ExpectLogContainsSomewhereAfter(
4488 entries,
4489 log_position,
4490 NetLog::TYPE_URL_REQUEST_DELEGATE,
4491 NetLog::PHASE_BEGIN);
4492
4493 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4494 log_position + 1);
4495
4496 ASSERT_LT(log_position, entries.size());
4497 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4498 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4499 }
4500
4501 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4502 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4503 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4504 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4505}
4506
4507// Tests handling of delegate info from a URLRequest::Delegate in the case of
4508// an HTTP redirect, with cancellation at various points.
4509TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4510 ASSERT_TRUE(test_server_.Start());
4511
4512 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4513 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4514 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4515 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4516 };
4517
4518 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4519 ++test_case) {
4520 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4521 TestURLRequestContext context(true);
4522 CapturingNetLog net_log;
4523 context.set_network_delegate(NULL);
4524 context.set_net_log(&net_log);
4525 context.Init();
4526
4527 {
4528 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
[email protected]2ca01e52013-10-31 22:05:194529 DEFAULT_PRIORITY,
4530 &request_delegate,
4531 &context);
[email protected]abe1c4a2013-10-25 19:28:514532 LoadStateWithParam load_state = r.GetLoadState();
4533 r.Start();
4534 base::RunLoop().Run();
4535 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4536 }
4537
4538 CapturingNetLog::CapturedEntryList entries;
4539 net_log.GetEntries(&entries);
4540
4541 // Delegate info is always logged in both OnReceivedRedirect and
4542 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4543 // OnResponseStarted delegate call is after cancellation, but logging is
4544 // still currently supported in that call.
4545 size_t log_position = 0;
4546 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484547 if (i == 0) {
4548 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4549 entries, log_position) + 1;
4550 }
4551
[email protected]abe1c4a2013-10-25 19:28:514552 log_position = ExpectLogContainsSomewhereAfter(
4553 entries,
4554 log_position,
4555 NetLog::TYPE_URL_REQUEST_DELEGATE,
4556 NetLog::PHASE_BEGIN);
4557
4558 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4559 log_position + 1);
4560
4561 ASSERT_LT(log_position, entries.size());
4562 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4563 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4564 }
4565
4566 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4567 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4568 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4569 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4570 }
4571}
4572
[email protected]847c0fa92012-11-06 16:37:424573namespace {
4574
4575const char kExtraHeader[] = "Allow-Snafu";
4576const char kExtraValue[] = "fubar";
4577
4578class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164579 virtual void OnReceivedRedirect(net::URLRequest* request,
4580 const GURL& new_url,
4581 bool* defer_redirect) OVERRIDE {
[email protected]847c0fa92012-11-06 16:37:424582 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4583 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4584 }
4585};
4586
4587} // namespace
4588
4589TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4590 ASSERT_TRUE(test_server_.Start());
4591
4592 GURL destination_url = test_server_.GetURL(
4593 "echoheader?" + std::string(kExtraHeader));
4594 GURL original_url = test_server_.GetURL(
4595 "server-redirect?" + destination_url.spec());
4596 RedirectWithAdditionalHeadersDelegate d;
[email protected]2ca01e52013-10-31 22:05:194597 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]847c0fa92012-11-06 16:37:424598 req.Start();
[email protected]255620da2013-08-19 13:14:294599 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424600
4601 std::string value;
4602 const HttpRequestHeaders& headers = req.extra_request_headers();
4603 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4604 EXPECT_EQ(kExtraValue, value);
4605 EXPECT_FALSE(req.is_pending());
4606 EXPECT_FALSE(req.is_redirecting());
4607 EXPECT_EQ(kExtraValue, d.data_received());
4608}
4609
[email protected]251a1b92012-11-13 11:01:094610namespace {
4611
4612const char kExtraHeaderToRemove[] = "To-Be-Removed";
4613
4614class RedirectWithHeaderRemovalDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164615 virtual void OnReceivedRedirect(net::URLRequest* request,
[email protected]251a1b92012-11-13 11:01:094616 const GURL& new_url,
[email protected]46fadfd2013-02-06 09:40:164617 bool* defer_redirect) OVERRIDE {
[email protected]251a1b92012-11-13 11:01:094618 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4619 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4620 }
4621};
4622
4623} // namespace
4624
4625TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4626 ASSERT_TRUE(test_server_.Start());
4627
4628 GURL destination_url = test_server_.GetURL(
4629 "echoheader?" + std::string(kExtraHeaderToRemove));
4630 GURL original_url = test_server_.GetURL(
4631 "server-redirect?" + destination_url.spec());
4632 RedirectWithHeaderRemovalDelegate d;
[email protected]2ca01e52013-10-31 22:05:194633 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]251a1b92012-11-13 11:01:094634 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4635 req.Start();
[email protected]255620da2013-08-19 13:14:294636 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094637
4638 std::string value;
4639 const HttpRequestHeaders& headers = req.extra_request_headers();
4640 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4641 EXPECT_FALSE(req.is_pending());
4642 EXPECT_FALSE(req.is_redirecting());
4643 EXPECT_EQ("None", d.data_received());
4644}
4645
[email protected]316c1e5e2012-09-12 15:17:444646TEST_F(URLRequestTestHTTP, CancelTest) {
4647 TestDelegate d;
4648 {
[email protected]2ca01e52013-10-31 22:05:194649 URLRequest r(GURL("http://www.google.com/"),
4650 DEFAULT_PRIORITY,
4651 &d,
4652 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444653
4654 r.Start();
4655 EXPECT_TRUE(r.is_pending());
4656
4657 r.Cancel();
4658
[email protected]255620da2013-08-19 13:14:294659 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444660
4661 // We expect to receive OnResponseStarted even though the request has been
4662 // cancelled.
4663 EXPECT_EQ(1, d.response_started_count());
4664 EXPECT_EQ(0, d.bytes_received());
4665 EXPECT_FALSE(d.received_data_before_response());
4666 }
4667}
4668
4669TEST_F(URLRequestTestHTTP, CancelTest2) {
4670 ASSERT_TRUE(test_server_.Start());
4671
4672 TestDelegate d;
4673 {
[email protected]2ca01e52013-10-31 22:05:194674 URLRequest r(test_server_.GetURL(std::string()),
4675 DEFAULT_PRIORITY,
4676 &d,
4677 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444678
4679 d.set_cancel_in_response_started(true);
4680
4681 r.Start();
4682 EXPECT_TRUE(r.is_pending());
4683
[email protected]255620da2013-08-19 13:14:294684 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444685
4686 EXPECT_EQ(1, d.response_started_count());
4687 EXPECT_EQ(0, d.bytes_received());
4688 EXPECT_FALSE(d.received_data_before_response());
4689 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4690 }
4691}
4692
4693TEST_F(URLRequestTestHTTP, CancelTest3) {
4694 ASSERT_TRUE(test_server_.Start());
4695
4696 TestDelegate d;
4697 {
[email protected]2ca01e52013-10-31 22:05:194698 URLRequest r(test_server_.GetURL(std::string()),
4699 DEFAULT_PRIORITY,
4700 &d,
4701 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444702
4703 d.set_cancel_in_received_data(true);
4704
4705 r.Start();
4706 EXPECT_TRUE(r.is_pending());
4707
[email protected]255620da2013-08-19 13:14:294708 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444709
4710 EXPECT_EQ(1, d.response_started_count());
4711 // There is no guarantee about how much data was received
4712 // before the cancel was issued. It could have been 0 bytes,
4713 // or it could have been all the bytes.
4714 // EXPECT_EQ(0, d.bytes_received());
4715 EXPECT_FALSE(d.received_data_before_response());
4716 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4717 }
4718}
4719
4720TEST_F(URLRequestTestHTTP, CancelTest4) {
4721 ASSERT_TRUE(test_server_.Start());
4722
4723 TestDelegate d;
4724 {
[email protected]2ca01e52013-10-31 22:05:194725 URLRequest r(test_server_.GetURL(std::string()),
4726 DEFAULT_PRIORITY,
4727 &d,
4728 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444729
4730 r.Start();
4731 EXPECT_TRUE(r.is_pending());
4732
4733 // The request will be implicitly canceled when it is destroyed. The
4734 // test delegate must not post a quit message when this happens because
4735 // this test doesn't actually have a message loop. The quit message would
4736 // get put on this thread's message queue and the next test would exit
4737 // early, causing problems.
4738 d.set_quit_on_complete(false);
4739 }
4740 // expect things to just cleanup properly.
4741
4742 // we won't actually get a received reponse here because we've never run the
4743 // message loop
4744 EXPECT_FALSE(d.received_data_before_response());
4745 EXPECT_EQ(0, d.bytes_received());
4746}
4747
4748TEST_F(URLRequestTestHTTP, CancelTest5) {
4749 ASSERT_TRUE(test_server_.Start());
4750
4751 // populate cache
4752 {
4753 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194754 URLRequest r(test_server_.GetURL("cachetime"),
4755 DEFAULT_PRIORITY,
4756 &d,
4757 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444758 r.Start();
[email protected]255620da2013-08-19 13:14:294759 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444760 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4761 }
4762
4763 // cancel read from cache (see bug 990242)
4764 {
4765 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194766 URLRequest r(test_server_.GetURL("cachetime"),
4767 DEFAULT_PRIORITY,
4768 &d,
4769 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444770 r.Start();
4771 r.Cancel();
[email protected]255620da2013-08-19 13:14:294772 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444773
4774 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4775 EXPECT_EQ(1, d.response_started_count());
4776 EXPECT_EQ(0, d.bytes_received());
4777 EXPECT_FALSE(d.received_data_before_response());
4778 }
4779}
4780
4781TEST_F(URLRequestTestHTTP, PostTest) {
4782 ASSERT_TRUE(test_server_.Start());
4783 HTTPUploadDataOperationTest("POST");
4784}
4785
4786TEST_F(URLRequestTestHTTP, PutTest) {
4787 ASSERT_TRUE(test_server_.Start());
4788 HTTPUploadDataOperationTest("PUT");
4789}
4790
4791TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4792 ASSERT_TRUE(test_server_.Start());
4793
4794 TestDelegate d;
4795 {
[email protected]2ca01e52013-10-31 22:05:194796 URLRequest r(
4797 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444798 r.set_method("POST");
4799
4800 r.Start();
4801 EXPECT_TRUE(r.is_pending());
4802
[email protected]255620da2013-08-19 13:14:294803 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444804
[email protected]329b68b2012-11-14 17:54:274805 ASSERT_EQ(1, d.response_started_count())
4806 << "request failed: " << r.status().status()
4807 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444808
4809 EXPECT_FALSE(d.received_data_before_response());
4810 EXPECT_TRUE(d.data_received().empty());
4811 }
4812}
4813
4814TEST_F(URLRequestTestHTTP, PostFileTest) {
4815 ASSERT_TRUE(test_server_.Start());
4816
4817 TestDelegate d;
4818 {
[email protected]2ca01e52013-10-31 22:05:194819 URLRequest r(
4820 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444821 r.set_method("POST");
4822
[email protected]6cdfd7f2013-02-08 20:40:154823 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:444824 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:024825 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:444826
[email protected]f288ef02012-12-15 20:28:284827 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:444828
[email protected]6cdfd7f2013-02-08 20:40:154829 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:444830 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4831 path = path.Append(FILE_PATH_LITERAL("net"));
4832 path = path.Append(FILE_PATH_LITERAL("data"));
4833 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4834 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:364835 element_readers.push_back(
4836 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4837 path,
4838 0,
4839 kuint64max,
4840 base::Time()));
[email protected]96c77a72013-09-24 09:49:204841 r.set_upload(make_scoped_ptr(
4842 new UploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:444843
4844 r.Start();
4845 EXPECT_TRUE(r.is_pending());
4846
[email protected]255620da2013-08-19 13:14:294847 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444848
[email protected]329b68b2012-11-14 17:54:274849 int64 size = 0;
[email protected]56285702013-12-04 18:22:494850 ASSERT_EQ(true, base::GetFileSize(path, &size));
[email protected]4356f0f2013-04-07 00:58:174851 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:444852
[email protected]7600d0b2013-12-08 21:43:304853 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:444854
[email protected]329b68b2012-11-14 17:54:274855 ASSERT_EQ(1, d.response_started_count())
4856 << "request failed: " << r.status().status()
4857 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444858
4859 EXPECT_FALSE(d.received_data_before_response());
4860
[email protected]329b68b2012-11-14 17:54:274861 EXPECT_EQ(size, d.bytes_received());
4862 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:444863 }
4864}
4865
[email protected]999dd8c2013-11-12 06:45:544866TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4867 ASSERT_TRUE(test_server_.Start());
4868
4869 TestDelegate d;
4870 {
4871 URLRequest r(test_server_.GetURL("echo"), DEFAULT_PRIORITY,
4872 &d, &default_context_);
4873 r.set_method("POST");
4874
4875 ScopedVector<UploadElementReader> element_readers;
4876
4877 element_readers.push_back(new UploadFileElementReader(
4878 base::MessageLoopProxy::current().get(),
4879 base::FilePath(FILE_PATH_LITERAL(
4880 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4881 0,
4882 kuint64max,
4883 base::Time()));
4884 r.set_upload(make_scoped_ptr(
4885 new UploadDataStream(element_readers.Pass(), 0)));
4886
4887 r.Start();
4888 EXPECT_TRUE(r.is_pending());
4889
4890 base::RunLoop().Run();
4891
[email protected]999dd8c2013-11-12 06:45:544892 EXPECT_TRUE(d.request_failed());
4893 EXPECT_FALSE(d.received_data_before_response());
4894 EXPECT_EQ(0, d.bytes_received());
4895 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
4896 EXPECT_EQ(ERR_FILE_NOT_FOUND, r.status().error());
[email protected]999dd8c2013-11-12 06:45:544897 }
4898}
4899
[email protected]316c1e5e2012-09-12 15:17:444900TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4901 ASSERT_TRUE(test_server_.Start());
4902
4903 TestDelegate d;
4904 {
[email protected]2ca01e52013-10-31 22:05:194905 URLRequest r(
4906 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444907 r.EnableChunkedUpload();
4908 r.set_method("POST");
4909 AddChunksToUpload(&r);
4910 r.Start();
4911 EXPECT_TRUE(r.is_pending());
4912
[email protected]255620da2013-08-19 13:14:294913 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444914
4915 VerifyReceivedDataMatchesChunks(&r, &d);
4916 }
4917}
4918
[email protected]329b68b2012-11-14 17:54:274919TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4920 ASSERT_TRUE(test_server_.Start());
4921
4922 TestDelegate d;
4923 {
[email protected]2ca01e52013-10-31 22:05:194924 URLRequest r(
4925 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]329b68b2012-11-14 17:54:274926 r.EnableChunkedUpload();
4927 r.set_method("POST");
4928 r.Start();
4929 EXPECT_TRUE(r.is_pending());
4930 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294931 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:274932
4933 VerifyReceivedDataMatchesChunks(&r, &d);
4934 }
4935}
4936
[email protected]316c1e5e2012-09-12 15:17:444937TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4938 ASSERT_TRUE(test_server_.Start());
4939
4940 TestDelegate d;
4941 {
[email protected]2ca01e52013-10-31 22:05:194942 URLRequest r(
4943 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444944 r.EnableChunkedUpload();
4945 r.set_method("POST");
4946 r.Start();
4947 EXPECT_TRUE(r.is_pending());
4948
[email protected]255620da2013-08-19 13:14:294949 base::RunLoop().RunUntilIdle();
[email protected]316c1e5e2012-09-12 15:17:444950 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294951 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444952
4953 VerifyReceivedDataMatchesChunks(&r, &d);
4954 }
4955}
4956
4957TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4958 ASSERT_TRUE(test_server_.Start());
4959
4960 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194961 URLRequest req(test_server_.GetURL("files/with-headers.html"),
4962 DEFAULT_PRIORITY,
4963 &d,
4964 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444965 req.Start();
[email protected]255620da2013-08-19 13:14:294966 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444967
4968 const HttpResponseHeaders* headers = req.response_headers();
4969
4970 // Simple sanity check that response_info() accesses the same data.
4971 EXPECT_EQ(headers, req.response_info().headers.get());
4972
4973 std::string header;
4974 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4975 EXPECT_EQ("private", header);
4976
4977 header.clear();
4978 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4979 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4980
4981 // The response has two "X-Multiple-Entries" headers.
4982 // This verfies our output has them concatenated together.
4983 header.clear();
4984 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4985 EXPECT_EQ("a, b", header);
4986}
4987
[email protected]242d8562012-10-30 21:20:464988TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:224989 SpawnedTestServer::SSLOptions ssl_options;
4990 SpawnedTestServer https_test_server(
4991 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:464992 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154993 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:464994 ASSERT_TRUE(https_test_server.Start());
4995
4996 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:194997 URLRequest request(https_test_server.GetURL("files/hsts-headers.html"),
4998 DEFAULT_PRIORITY,
4999 &d,
5000 &default_context_);
[email protected]242d8562012-10-30 21:20:465001 request.Start();
[email protected]255620da2013-08-19 13:14:295002 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465003
5004 TransportSecurityState* security_state =
5005 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465006 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265007 EXPECT_TRUE(security_state->GetDynamicDomainState(
5008 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465009 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265010 domain_state.sts.upgrade_mode);
5011 EXPECT_TRUE(domain_state.sts.include_subdomains);
5012 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275013#if defined(OS_ANDROID)
5014 // Android's CertVerifyProc does not (yet) handle pins.
5015#else
5016 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5017#endif
5018}
5019
5020// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5021// reject HPKP headers, and a test setting only HPKP headers will fail (no
5022// DomainState present because header rejected).
5023#if defined(OS_ANDROID)
5024#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5025#else
5026#define MAYBE_ProcessPKP ProcessPKP
5027#endif
5028
5029// Tests that enabling HPKP on a domain does not affect the HSTS
5030// validity/expiration.
5031TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5032 SpawnedTestServer::SSLOptions ssl_options;
5033 SpawnedTestServer https_test_server(
5034 SpawnedTestServer::TYPE_HTTPS,
5035 ssl_options,
5036 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5037 ASSERT_TRUE(https_test_server.Start());
5038
5039 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195040 URLRequest request(https_test_server.GetURL("files/hpkp-headers.html"),
5041 DEFAULT_PRIORITY,
5042 &d,
5043 &default_context_);
[email protected]37fd55fb2013-06-29 13:13:275044 request.Start();
[email protected]255620da2013-08-19 13:14:295045 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275046
5047 TransportSecurityState* security_state =
5048 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275049 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265050 EXPECT_TRUE(security_state->GetDynamicDomainState(
5051 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275052 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[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]37fd55fb2013-06-29 13:13:275056 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265057 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465058}
5059
5060TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:225061 SpawnedTestServer::SSLOptions ssl_options;
5062 SpawnedTestServer https_test_server(
5063 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465064 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155065 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465066 ASSERT_TRUE(https_test_server.Start());
5067
5068 TestDelegate d;
5069 URLRequest request(
5070 https_test_server.GetURL("files/hsts-multiple-headers.html"),
[email protected]2ca01e52013-10-31 22:05:195071 DEFAULT_PRIORITY,
[email protected]242d8562012-10-30 21:20:465072 &d,
5073 &default_context_);
5074 request.Start();
[email protected]255620da2013-08-19 13:14:295075 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465076
5077 // We should have set parameters from the first header, not the second.
5078 TransportSecurityState* security_state =
5079 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465080 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265081 EXPECT_TRUE(security_state->GetDynamicDomainState(
5082 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465083 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265084 domain_state.sts.upgrade_mode);
5085 EXPECT_FALSE(domain_state.sts.include_subdomains);
5086 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465087}
5088
[email protected]9f972ec2013-04-10 20:24:365089TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:225090 SpawnedTestServer::SSLOptions ssl_options;
5091 SpawnedTestServer https_test_server(
5092 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:365093 ssl_options,
5094 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5095 ASSERT_TRUE(https_test_server.Start());
5096
5097 TestDelegate d;
5098 URLRequest request(
5099 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
[email protected]2ca01e52013-10-31 22:05:195100 DEFAULT_PRIORITY,
[email protected]9f972ec2013-04-10 20:24:365101 &d,
5102 &default_context_);
5103 request.Start();
[email protected]255620da2013-08-19 13:14:295104 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365105
5106 // We should have set parameters from the first header, not the second.
5107 TransportSecurityState* security_state =
5108 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365109 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265110 EXPECT_TRUE(security_state->GetDynamicDomainState(
5111 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]9f972ec2013-04-10 20:24:365112 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265113 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365114#if defined(OS_ANDROID)
5115 // Android's CertVerifyProc does not (yet) handle pins.
5116#else
5117 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5118#endif
[email protected]9e6968d2014-05-07 21:46:265119 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365120
[email protected]a165f092013-06-12 16:10:055121 // Even though there is an HSTS header asserting includeSubdomains, it is
5122 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265123 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055124 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265125 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365126}
5127
[email protected]37fd55fb2013-06-29 13:13:275128// Tests that when multiple HPKP headers are present, asserting different
5129// policies, that only the first such policy is processed.
5130TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5131 SpawnedTestServer::SSLOptions ssl_options;
5132 SpawnedTestServer https_test_server(
5133 SpawnedTestServer::TYPE_HTTPS,
5134 ssl_options,
5135 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5136 ASSERT_TRUE(https_test_server.Start());
5137
5138 TestDelegate d;
5139 URLRequest request(
5140 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
[email protected]2ca01e52013-10-31 22:05:195141 DEFAULT_PRIORITY,
[email protected]37fd55fb2013-06-29 13:13:275142 &d,
5143 &default_context_);
5144 request.Start();
[email protected]255620da2013-08-19 13:14:295145 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275146
5147 TransportSecurityState* security_state =
5148 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275149 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265150 EXPECT_TRUE(security_state->GetDynamicDomainState(
5151 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275152 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265153 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275154#if defined(OS_ANDROID)
5155 // Android's CertVerifyProc does not (yet) handle pins.
5156#else
5157 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5158#endif
[email protected]9e6968d2014-05-07 21:46:265159 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275160
[email protected]9e6968d2014-05-07 21:46:265161 EXPECT_TRUE(domain_state.sts.include_subdomains);
5162 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275163}
5164
[email protected]316c1e5e2012-09-12 15:17:445165TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5166 ASSERT_TRUE(test_server_.Start());
5167
5168 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195169 URLRequest req(test_server_.GetURL("files/content-type-normalization.html"),
5170 DEFAULT_PRIORITY,
5171 &d,
5172 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445173 req.Start();
[email protected]255620da2013-08-19 13:14:295174 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445175
5176 std::string mime_type;
5177 req.GetMimeType(&mime_type);
5178 EXPECT_EQ("text/html", mime_type);
5179
5180 std::string charset;
5181 req.GetCharset(&charset);
5182 EXPECT_EQ("utf-8", charset);
5183 req.Cancel();
5184}
5185
[email protected]02494ec2014-05-07 15:05:295186TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345187 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345188 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345189 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025190 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345191
5192 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
[email protected]588614c22013-08-16 00:09:025193 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345194}
5195
[email protected]02494ec2014-05-07 15:05:295196#if !defined(DISABLE_FILE_SUPPORT)
5197TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5198 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5199 GURL file_url("file:///foo.txt");
5200 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5201 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5202
5203 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5204 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
5205}
5206
[email protected]588614c22013-08-16 00:09:025207TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445208 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-file.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_UNSAFE_REDIRECT, req.status().error());
5220}
[email protected]02494ec2014-05-07 15:05:295221#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445222
[email protected]588614c22013-08-16 00:09:025223TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5224 ASSERT_TRUE(test_server_.Start());
5225
5226 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195227 URLRequest req(test_server_.GetURL("files/redirect-to-data.html"),
5228 DEFAULT_PRIORITY,
5229 &d,
5230 &default_context_);
[email protected]588614c22013-08-16 00:09:025231 req.Start();
5232 base::MessageLoop::current()->Run();
5233
5234 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5235 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5236}
5237
[email protected]316c1e5e2012-09-12 15:17:445238TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5239 ASSERT_TRUE(test_server_.Start());
5240
5241 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195242 URLRequest req(test_server_.GetURL("files/redirect-to-invalid-url.html"),
5243 DEFAULT_PRIORITY,
5244 &d,
5245 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445246 req.Start();
[email protected]255620da2013-08-19 13:14:295247 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445248
5249 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5250 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
5251}
5252
[email protected]e50efea2014-03-24 18:41:005253// Make sure redirects are cached, despite not reading their bodies.
5254TEST_F(URLRequestTestHTTP, CacheRedirect) {
5255 ASSERT_TRUE(test_server_.Start());
5256 GURL redirect_url =
5257 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5258
5259 {
5260 TestDelegate d;
5261 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5262 req.Start();
5263 base::RunLoop().Run();
5264 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5265 EXPECT_EQ(1, d.received_redirect_count());
5266 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5267 }
5268
5269 {
5270 TestDelegate d;
5271 d.set_quit_on_redirect(true);
5272 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5273 req.Start();
5274 base::RunLoop().Run();
5275
5276 EXPECT_EQ(1, d.received_redirect_count());
5277 EXPECT_EQ(0, d.response_started_count());
5278 EXPECT_TRUE(req.was_cached());
5279
5280 req.FollowDeferredRedirect();
5281 base::RunLoop().Run();
5282 EXPECT_EQ(1, d.received_redirect_count());
5283 EXPECT_EQ(1, d.response_started_count());
5284 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5285 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5286 }
5287}
5288
5289// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5290// when the headers are read, since the body won't have been read.
5291TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5292 ASSERT_TRUE(test_server_.Start());
5293 // URL that is normally cached.
5294 GURL initial_url = test_server_.GetURL("cachetime");
5295
5296 {
5297 // Set up the TestNetworkDelegate tp force a redirect.
5298 GURL redirect_to_url = test_server_.GetURL("echo");
5299 default_network_delegate_.set_redirect_on_headers_received_url(
5300 redirect_to_url);
5301
5302 TestDelegate d;
5303 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5304 req.Start();
5305 base::RunLoop().Run();
5306 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5307 EXPECT_EQ(1, d.received_redirect_count());
5308 EXPECT_EQ(redirect_to_url, req.url());
5309 }
5310
5311 {
5312 TestDelegate d;
5313 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5314 req.Start();
5315 base::RunLoop().Run();
5316
5317 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5318 EXPECT_FALSE(req.was_cached());
5319 EXPECT_EQ(0, d.received_redirect_count());
5320 EXPECT_EQ(initial_url, req.url());
5321 }
5322}
5323
[email protected]5f714132014-03-26 10:41:165324// Tests that redirection to an unsafe URL is allowed when it has been marked as
5325// safe.
5326TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5327 ASSERT_TRUE(test_server_.Start());
5328
5329 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5330 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5331 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5332
5333 TestDelegate d;
5334 {
5335 URLRequest r(test_server_.GetURL("whatever"),
5336 DEFAULT_PRIORITY,
5337 &d,
5338 &default_context_);
5339
5340 r.Start();
5341 base::RunLoop().Run();
5342
5343 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5344
5345 EXPECT_EQ(2U, r.url_chain().size());
5346 EXPECT_EQ(net::OK, r.status().error());
5347 EXPECT_EQ(unsafe_url, r.url());
5348 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5349 }
5350}
5351
5352// Tests that a redirect to a different unsafe URL is blocked, even after adding
5353// some other URL to the whitelist.
5354TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5355 ASSERT_TRUE(test_server_.Start());
5356
5357 GURL unsafe_url("data:text/html,something");
5358 GURL different_unsafe_url("data:text/html,something-else");
5359 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5360 default_network_delegate_.set_allowed_unsafe_redirect_url(
5361 different_unsafe_url);
5362
5363 TestDelegate d;
5364 {
5365 URLRequest r(test_server_.GetURL("whatever"),
5366 DEFAULT_PRIORITY,
5367 &d,
5368 &default_context_);
5369
5370 r.Start();
5371 base::RunLoop().Run();
5372
5373 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
5374 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r.status().error());
5375 }
5376}
5377
[email protected]5f714132014-03-26 10:41:165378// Redirects from an URL with fragment to an unsafe URL with fragment should
5379// be allowed, and the reference fragment of the target URL should be preserved.
5380TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5381 ASSERT_TRUE(test_server_.Start());
5382
5383 GURL original_url(test_server_.GetURL("original#fragment1"));
5384 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5385 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5386
5387 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5388 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5389
5390 TestDelegate d;
5391 {
5392 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5393
5394 r.Start();
5395 base::RunLoop().Run();
5396
5397 EXPECT_EQ(2U, r.url_chain().size());
5398 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5399 EXPECT_EQ(net::OK, r.status().error());
5400 EXPECT_EQ(original_url, r.original_url());
5401 EXPECT_EQ(expected_url, r.url());
5402 }
5403}
5404
5405// When a delegate has specified a safe redirect URL, but it does not match the
5406// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145407TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165408 ASSERT_TRUE(test_server_.Start());
5409
5410 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5411 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5412 GURL redirect_url(test_server_.GetURL("target"));
5413 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5414
5415 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5416 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5417
5418 TestDelegate d;
5419 {
5420 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5421
5422 r.Start();
5423 base::RunLoop().Run();
5424
5425 EXPECT_EQ(2U, r.url_chain().size());
5426 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5427 EXPECT_EQ(net::OK, r.status().error());
5428 EXPECT_EQ(original_url, r.original_url());
5429 EXPECT_EQ(expected_redirect_url, r.url());
5430 }
5431}
5432
[email protected]f878230e2014-04-03 15:36:145433// When a delegate has specified a safe redirect URL, assume that the redirect
5434// URL should not be changed. In particular, the reference fragment should not
5435// be modified.
5436TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5437 ASSERT_TRUE(test_server_.Start());
5438
5439 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5440 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5441
5442 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5443 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5444
5445 TestDelegate d;
5446 {
5447 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5448
5449 r.Start();
5450 base::RunLoop().Run();
5451
5452 EXPECT_EQ(2U, r.url_chain().size());
5453 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5454 EXPECT_EQ(net::OK, r.status().error());
5455 EXPECT_EQ(original_url, r.original_url());
5456 EXPECT_EQ(redirect_url, r.url());
5457 }
5458}
5459
5460// When a URLRequestRedirectJob is created, the redirection must be followed and
5461// the reference fragment of the target URL must not be modified.
5462TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5463 ASSERT_TRUE(test_server_.Start());
5464
5465 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5466 GURL redirect_url(test_server_.GetURL("echo"));
5467
5468 TestDelegate d;
5469 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5470
5471 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5472 &r, &default_network_delegate_, redirect_url,
5473 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5474 AddTestInterceptor()->set_main_intercept_job(job);
5475
5476 r.Start();
5477 base::RunLoop().Run();
5478
5479 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5480 EXPECT_EQ(net::OK, r.status().error());
5481 EXPECT_EQ(original_url, r.original_url());
5482 EXPECT_EQ(redirect_url, r.url());
5483}
5484
[email protected]316c1e5e2012-09-12 15:17:445485TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5486 ASSERT_TRUE(test_server_.Start());
5487
5488 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195489 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5490 DEFAULT_PRIORITY,
5491 &d,
5492 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135493 req.SetReferrer("http://user:[email protected]/");
[email protected]316c1e5e2012-09-12 15:17:445494 req.Start();
[email protected]255620da2013-08-19 13:14:295495 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445496
5497 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5498}
5499
[email protected]99ecf6e2013-04-10 22:46:135500TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5501 ASSERT_TRUE(test_server_.Start());
5502
5503 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195504 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5505 DEFAULT_PRIORITY,
5506 &d,
5507 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135508 req.SetReferrer("http://foo.com/test#fragment");
5509 req.Start();
[email protected]255620da2013-08-19 13:14:295510 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135511
5512 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5513}
5514
5515TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5516 ASSERT_TRUE(test_server_.Start());
5517
5518 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195519 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5520 DEFAULT_PRIORITY,
5521 &d,
5522 &default_context_);
[email protected]99ecf6e2013-04-10 22:46:135523 req.SetReferrer("http://foo.com/test#fragment");
5524 req.SetReferrer("");
5525 req.Start();
[email protected]255620da2013-08-19 13:14:295526 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135527
5528 EXPECT_EQ(std::string("None"), d.data_received());
5529}
5530
[email protected]1826a402014-01-08 15:40:485531// Defer network start and then resume, checking that the request was a success
5532// and bytes were received.
5533TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5534 ASSERT_TRUE(test_server_.Start());
5535
5536 TestDelegate d;
5537 {
5538 d.set_quit_on_network_start(true);
5539 GURL test_url(test_server_.GetURL("echo"));
5540 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5541
5542 req.Start();
5543 base::RunLoop().Run();
5544
5545 EXPECT_EQ(1, d.received_before_network_start_count());
5546 EXPECT_EQ(0, d.response_started_count());
5547
5548 req.ResumeNetworkStart();
5549 base::RunLoop().Run();
5550
5551 EXPECT_EQ(1, d.response_started_count());
5552 EXPECT_NE(0, d.bytes_received());
5553 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5554 }
5555}
5556
5557// Check that OnBeforeNetworkStart is only called once even if there is a
5558// redirect.
5559TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5560 ASSERT_TRUE(test_server_.Start());
5561
5562 TestDelegate d;
5563 {
5564 d.set_quit_on_redirect(true);
5565 d.set_quit_on_network_start(true);
5566 URLRequest req(test_server_.GetURL("server-redirect?echo"),
5567 DEFAULT_PRIORITY,
5568 &d,
5569 &default_context_);
5570
5571 req.Start();
5572 base::RunLoop().Run();
5573
5574 EXPECT_EQ(1, d.received_before_network_start_count());
5575 EXPECT_EQ(0, d.response_started_count());
5576 EXPECT_EQ(0, d.received_redirect_count());
5577
5578 req.ResumeNetworkStart();
5579 base::RunLoop().Run();
5580
5581 EXPECT_EQ(1, d.received_redirect_count());
5582 req.FollowDeferredRedirect();
5583 base::RunLoop().Run();
5584
5585 // Check that the redirect's new network transaction does not get propagated
5586 // to a second OnBeforeNetworkStart() notification.
5587 EXPECT_EQ(1, d.received_before_network_start_count());
5588
5589 EXPECT_EQ(1, d.response_started_count());
5590 EXPECT_NE(0, d.bytes_received());
5591 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5592 }
5593}
5594
5595// Cancel the request after learning that the request would use the network.
5596TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5597 ASSERT_TRUE(test_server_.Start());
5598
5599 TestDelegate d;
5600 {
5601 d.set_quit_on_network_start(true);
5602 GURL test_url(test_server_.GetURL("echo"));
5603 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5604
5605 req.Start();
5606 base::RunLoop().Run();
5607
5608 EXPECT_EQ(1, d.received_before_network_start_count());
5609 EXPECT_EQ(0, d.response_started_count());
5610
5611 req.Cancel();
5612 base::RunLoop().Run();
5613
5614 EXPECT_EQ(1, d.response_started_count());
5615 EXPECT_EQ(0, d.bytes_received());
5616 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5617 }
5618}
5619
[email protected]316c1e5e2012-09-12 15:17:445620TEST_F(URLRequestTestHTTP, CancelRedirect) {
5621 ASSERT_TRUE(test_server_.Start());
5622
5623 TestDelegate d;
5624 {
5625 d.set_cancel_in_received_redirect(true);
[email protected]2ca01e52013-10-31 22:05:195626 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5627 DEFAULT_PRIORITY,
5628 &d,
5629 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445630 req.Start();
[email protected]255620da2013-08-19 13:14:295631 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445632
5633 EXPECT_EQ(1, d.response_started_count());
5634 EXPECT_EQ(0, d.bytes_received());
5635 EXPECT_FALSE(d.received_data_before_response());
5636 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5637 }
5638}
5639
5640TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5641 ASSERT_TRUE(test_server_.Start());
5642
5643 TestDelegate d;
5644 {
5645 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:045646 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]2ca01e52013-10-31 22:05:195647 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:045648
[email protected]316c1e5e2012-09-12 15:17:445649 req.Start();
[email protected]255620da2013-08-19 13:14:295650 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445651
5652 EXPECT_EQ(1, d.received_redirect_count());
5653
5654 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295655 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445656
5657 EXPECT_EQ(1, d.response_started_count());
5658 EXPECT_FALSE(d.received_data_before_response());
5659 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5660
[email protected]6cdfd7f2013-02-08 20:40:155661 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445662 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5663 path = path.Append(FILE_PATH_LITERAL("net"));
5664 path = path.Append(FILE_PATH_LITERAL("data"));
5665 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5666 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5667
5668 std::string contents;
[email protected]82f84b92013-08-30 18:23:505669 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:445670 EXPECT_EQ(contents, d.data_received());
5671 }
5672}
5673
[email protected]79e1fd62013-06-20 06:50:045674TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5675 ASSERT_TRUE(test_server_.Start());
5676
5677 TestDelegate d;
5678 {
5679 d.set_quit_on_redirect(true);
5680 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]2ca01e52013-10-31 22:05:195681 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]79e1fd62013-06-20 06:50:045682
5683 EXPECT_FALSE(d.have_full_request_headers());
5684
5685 req.Start();
[email protected]255620da2013-08-19 13:14:295686 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045687
5688 EXPECT_EQ(1, d.received_redirect_count());
5689 EXPECT_TRUE(d.have_full_request_headers());
5690 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5691 d.ClearFullRequestHeaders();
5692
5693 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295694 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045695
5696 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5697 EXPECT_EQ(1, d.response_started_count());
5698 EXPECT_TRUE(d.have_full_request_headers());
5699 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5700 EXPECT_FALSE(d.received_data_before_response());
5701 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5702
5703 base::FilePath path;
5704 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5705 path = path.Append(FILE_PATH_LITERAL("net"));
5706 path = path.Append(FILE_PATH_LITERAL("data"));
5707 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5708 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5709
5710 std::string contents;
[email protected]82f84b92013-08-30 18:23:505711 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:045712 EXPECT_EQ(contents, d.data_received());
5713 }
5714}
5715
[email protected]316c1e5e2012-09-12 15:17:445716TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5717 ASSERT_TRUE(test_server_.Start());
5718
5719 TestDelegate d;
5720 {
5721 d.set_quit_on_redirect(true);
[email protected]2ca01e52013-10-31 22:05:195722 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5723 DEFAULT_PRIORITY,
5724 &d,
5725 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445726 req.Start();
[email protected]255620da2013-08-19 13:14:295727 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445728
5729 EXPECT_EQ(1, d.received_redirect_count());
5730
5731 req.Cancel();
[email protected]255620da2013-08-19 13:14:295732 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445733
5734 EXPECT_EQ(1, d.response_started_count());
5735 EXPECT_EQ(0, d.bytes_received());
5736 EXPECT_FALSE(d.received_data_before_response());
5737 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5738 }
5739}
5740
5741TEST_F(URLRequestTestHTTP, VaryHeader) {
5742 ASSERT_TRUE(test_server_.Start());
5743
[email protected]3b23a222013-05-15 21:33:255744 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:445745 {
5746 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195747 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5748 DEFAULT_PRIORITY,
5749 &d,
5750 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445751 HttpRequestHeaders headers;
5752 headers.SetHeader("foo", "1");
5753 req.SetExtraRequestHeaders(headers);
5754 req.Start();
[email protected]255620da2013-08-19 13:14:295755 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:255756
5757 LoadTimingInfo load_timing_info;
5758 req.GetLoadTimingInfo(&load_timing_info);
5759 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445760 }
5761
[email protected]3b23a222013-05-15 21:33:255762 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:445763 {
5764 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195765 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5766 DEFAULT_PRIORITY,
5767 &d,
5768 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445769 HttpRequestHeaders headers;
5770 headers.SetHeader("foo", "1");
5771 req.SetExtraRequestHeaders(headers);
5772 req.Start();
[email protected]255620da2013-08-19 13:14:295773 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445774
5775 EXPECT_TRUE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255776
5777 LoadTimingInfo load_timing_info;
5778 req.GetLoadTimingInfo(&load_timing_info);
5779 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:445780 }
5781
[email protected]3b23a222013-05-15 21:33:255782 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:445783 {
5784 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195785 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5786 DEFAULT_PRIORITY,
5787 &d,
5788 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445789 HttpRequestHeaders headers;
5790 headers.SetHeader("foo", "2");
5791 req.SetExtraRequestHeaders(headers);
5792 req.Start();
[email protected]255620da2013-08-19 13:14:295793 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445794
5795 EXPECT_FALSE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255796
5797 LoadTimingInfo load_timing_info;
5798 req.GetLoadTimingInfo(&load_timing_info);
5799 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445800 }
5801}
5802
5803TEST_F(URLRequestTestHTTP, BasicAuth) {
5804 ASSERT_TRUE(test_server_.Start());
5805
5806 // populate the cache
5807 {
5808 TestDelegate d;
5809 d.set_credentials(AuthCredentials(kUser, kSecret));
5810
[email protected]2ca01e52013-10-31 22:05:195811 URLRequest r(test_server_.GetURL("auth-basic"),
5812 DEFAULT_PRIORITY,
5813 &d,
5814 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445815 r.Start();
5816
[email protected]255620da2013-08-19 13:14:295817 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445818
5819 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5820 }
5821
5822 // repeat request with end-to-end validation. since auth-basic results in a
5823 // cachable page, we expect this test to result in a 304. in which case, the
5824 // response should be fetched from the cache.
5825 {
5826 TestDelegate d;
5827 d.set_credentials(AuthCredentials(kUser, kSecret));
5828
[email protected]2ca01e52013-10-31 22:05:195829 URLRequest r(test_server_.GetURL("auth-basic"),
5830 DEFAULT_PRIORITY,
5831 &d,
5832 &default_context_);
[email protected]bb1c4662013-11-14 00:00:075833 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
[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 // Should be the same cached document.
5841 EXPECT_TRUE(r.was_cached());
5842 }
5843}
5844
5845// Check that Set-Cookie headers in 401 responses are respected.
5846// http://crbug.com/6450
5847TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5848 ASSERT_TRUE(test_server_.Start());
5849
5850 GURL url_requiring_auth =
5851 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5852
5853 // Request a page that will give a 401 containing a Set-Cookie header.
5854 // Verify that when the transaction is restarted, it includes the new cookie.
5855 {
[email protected]ceefd7fd2012-11-29 00:36:245856 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445857 TestURLRequestContext context(true);
5858 context.set_network_delegate(&network_delegate);
5859 context.Init();
5860
5861 TestDelegate d;
5862 d.set_credentials(AuthCredentials(kUser, kSecret));
5863
[email protected]2ca01e52013-10-31 22:05:195864 URLRequest r(url_requiring_auth, DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445865 r.Start();
5866
[email protected]255620da2013-08-19 13:14:295867 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445868
5869 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5870
5871 // Make sure we sent the cookie in the restarted transaction.
5872 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5873 != std::string::npos);
5874 }
5875
5876 // Same test as above, except this time the restart is initiated earlier
5877 // (without user intervention since identity is embedded in the URL).
5878 {
[email protected]ceefd7fd2012-11-29 00:36:245879 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445880 TestURLRequestContext context(true);
5881 context.set_network_delegate(&network_delegate);
5882 context.Init();
5883
5884 TestDelegate d;
5885
5886 GURL::Replacements replacements;
5887 std::string username("user2");
5888 std::string password("secret");
5889 replacements.SetUsernameStr(username);
5890 replacements.SetPasswordStr(password);
5891 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5892
[email protected]2ca01e52013-10-31 22:05:195893 URLRequest r(url_with_identity, DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445894 r.Start();
5895
[email protected]255620da2013-08-19 13:14:295896 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445897
5898 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5899
5900 // Make sure we sent the cookie in the restarted transaction.
5901 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5902 != std::string::npos);
5903 }
5904}
5905
[email protected]58e32bb2013-01-21 18:23:255906// Tests that load timing works as expected with auth and the cache.
5907TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5908 ASSERT_TRUE(test_server_.Start());
5909
5910 // populate the cache
5911 {
5912 TestDelegate d;
5913 d.set_credentials(AuthCredentials(kUser, kSecret));
5914
[email protected]2ca01e52013-10-31 22:05:195915 URLRequest r(test_server_.GetURL("auth-basic"),
5916 DEFAULT_PRIORITY,
5917 &d,
5918 &default_context_);
[email protected]58e32bb2013-01-21 18:23:255919 r.Start();
5920
[email protected]255620da2013-08-19 13:14:295921 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255922
5923 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5924
5925 LoadTimingInfo load_timing_info_before_auth;
5926 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5927 &load_timing_info_before_auth));
5928 TestLoadTimingNotReused(load_timing_info_before_auth,
5929 CONNECT_TIMING_HAS_DNS_TIMES);
5930
5931 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175932 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255933 // The test server does not support keep alive sockets, so the second
5934 // request with auth should use a new socket.
5935 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5936 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5937 load_timing_info.socket_log_id);
5938 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5939 load_timing_info.connect_timing.connect_start);
5940 }
5941
[email protected]3b23a222013-05-15 21:33:255942 // Repeat request with end-to-end validation. Since auth-basic results in a
5943 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:255944 // response should be fetched from the cache.
5945 {
5946 TestDelegate d;
5947 d.set_credentials(AuthCredentials(kUser, kSecret));
5948
[email protected]2ca01e52013-10-31 22:05:195949 URLRequest r(test_server_.GetURL("auth-basic"),
5950 DEFAULT_PRIORITY,
5951 &d,
5952 &default_context_);
[email protected]bb1c4662013-11-14 00:00:075953 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]58e32bb2013-01-21 18:23:255954 r.Start();
5955
[email protected]255620da2013-08-19 13:14:295956 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255957
5958 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5959
5960 // Should be the same cached document.
5961 EXPECT_TRUE(r.was_cached());
5962
[email protected]3b23a222013-05-15 21:33:255963 // Since there was a request that went over the wire, the load timing
5964 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:255965 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175966 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255967 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:255968 }
5969}
5970
[email protected]316c1e5e2012-09-12 15:17:445971// In this test, we do a POST which the server will 302 redirect.
5972// The subsequent transaction should use GET, and should not send the
5973// Content-Type header.
5974// http://code.google.com/p/chromium/issues/detail?id=843
5975TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5976 ASSERT_TRUE(test_server_.Start());
5977
5978 const char kData[] = "hello world";
5979
5980 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:195981 URLRequest req(test_server_.GetURL("files/redirect-to-echoall"),
5982 DEFAULT_PRIORITY,
5983 &d,
5984 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445985 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285986 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445987
5988 // Set headers (some of which are specific to the POST).
5989 HttpRequestHeaders headers;
5990 headers.AddHeadersFromString(
5991 "Content-Type: multipart/form-data; "
5992 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5993 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5994 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5995 "Accept-Language: en-US,en\r\n"
5996 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5997 "Content-Length: 11\r\n"
5998 "Origin: http://localhost:1337/");
5999 req.SetExtraRequestHeaders(headers);
6000 req.Start();
[email protected]255620da2013-08-19 13:14:296001 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446002
6003 std::string mime_type;
6004 req.GetMimeType(&mime_type);
6005 EXPECT_EQ("text/html", mime_type);
6006
6007 const std::string& data = d.data_received();
6008
6009 // Check that the post-specific headers were stripped:
6010 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6011 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6012 EXPECT_FALSE(ContainsString(data, "Origin:"));
6013
6014 // These extra request headers should not have been stripped.
6015 EXPECT_TRUE(ContainsString(data, "Accept:"));
6016 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6017 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6018}
6019
6020// The following tests check that we handle mutating the request method for
6021// HTTP redirects as expected.
6022// See http://crbug.com/56373 and http://crbug.com/102130.
6023
6024TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6025 ASSERT_TRUE(test_server_.Start());
6026
6027 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
6028
6029 HTTPRedirectMethodTest(url, "POST", "GET", true);
6030 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6031 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6032}
6033
6034TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6035 ASSERT_TRUE(test_server_.Start());
6036
6037 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6038
6039 HTTPRedirectMethodTest(url, "POST", "GET", true);
6040 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6041 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6042}
6043
6044TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6045 ASSERT_TRUE(test_server_.Start());
6046
6047 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6048
6049 HTTPRedirectMethodTest(url, "POST", "GET", true);
6050 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6051 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6052}
6053
6054TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6055 ASSERT_TRUE(test_server_.Start());
6056
6057 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6058
6059 HTTPRedirectMethodTest(url, "POST", "POST", true);
6060 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6061 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6062}
6063
[email protected]0a17aab32014-04-24 03:32:376064TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6065 ASSERT_TRUE(test_server_.Start());
6066
6067 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6068
6069 HTTPRedirectMethodTest(url, "POST", "POST", true);
6070 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6071 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6072}
6073
6074// Make sure that 308 responses without bodies are not treated as redirects.
6075// Certain legacy apis that pre-date the response code expect this behavior
6076// (Like Google Drive).
6077TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6078 ASSERT_TRUE(test_server_.Start());
6079
6080 TestDelegate d;
6081 const GURL url = test_server_.GetURL("files/308-without-location-header");
6082
6083 URLRequest request(url, DEFAULT_PRIORITY, &d, &default_context_);
6084
6085 request.Start();
6086 base::RunLoop().Run();
6087 EXPECT_EQ(URLRequestStatus::SUCCESS, request.status().status());
6088 EXPECT_EQ(OK, request.status().error());
6089 EXPECT_EQ(0, d.received_redirect_count());
6090 EXPECT_EQ(308, request.response_headers()->response_code());
6091 EXPECT_EQ("This is not a redirect.", d.data_received());
6092}
6093
[email protected]f878230e2014-04-03 15:36:146094TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6095 ASSERT_TRUE(test_server_.Start());
6096
6097 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6098 GURL expected_url(test_server_.GetURL("echo#fragment"));
6099
6100 TestDelegate d;
6101 {
6102 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
6103
6104 r.Start();
6105 base::RunLoop().Run();
6106
6107 EXPECT_EQ(2U, r.url_chain().size());
6108 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
6109 EXPECT_EQ(net::OK, r.status().error());
6110 EXPECT_EQ(original_url, r.original_url());
6111 EXPECT_EQ(expected_url, r.url());
6112 }
6113}
6114
[email protected]316c1e5e2012-09-12 15:17:446115TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6116 ASSERT_TRUE(test_server_.Start());
6117
6118 const char kData[] = "hello world";
6119
6120 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196121 URLRequest req(test_server_.GetURL("empty.html"),
6122 DEFAULT_PRIORITY,
6123 &d,
6124 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446125 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:286126 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:446127 HttpRequestHeaders headers;
6128 headers.SetHeader(HttpRequestHeaders::kContentLength,
6129 base::UintToString(arraysize(kData) - 1));
6130 req.SetExtraRequestHeaders(headers);
6131
6132 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:416133 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096134 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446135 AddTestInterceptor()->set_main_intercept_job(job);
6136
6137 req.Start();
[email protected]255620da2013-08-19 13:14:296138 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446139 EXPECT_EQ("GET", req.method());
6140}
6141
6142TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6143 ASSERT_TRUE(test_server_.Start());
6144
6145 const char kData[] = "hello world";
6146
6147 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196148 URLRequest req(test_server_.GetURL("empty.html"),
6149 DEFAULT_PRIORITY,
6150 &d,
6151 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446152 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:286153 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:446154 HttpRequestHeaders headers;
6155 headers.SetHeader(HttpRequestHeaders::kContentLength,
6156 base::UintToString(arraysize(kData) - 1));
6157 req.SetExtraRequestHeaders(headers);
6158
6159 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:416160 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096161 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6162 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446163 AddTestInterceptor()->set_main_intercept_job(job);
6164
6165 req.Start();
[email protected]255620da2013-08-19 13:14:296166 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446167 EXPECT_EQ("POST", req.method());
6168 EXPECT_EQ(kData, d.data_received());
6169}
6170
6171// Check that default A-L header is sent.
6172TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6173 ASSERT_TRUE(test_server_.Start());
6174
[email protected]8790210c2013-12-02 05:29:536175 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246176 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446177 TestURLRequestContext context(true);
6178 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436179 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446180 context.Init();
6181
6182 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196183 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6184 DEFAULT_PRIORITY,
6185 &d,
6186 &context);
[email protected]316c1e5e2012-09-12 15:17:446187 req.Start();
[email protected]255620da2013-08-19 13:14:296188 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446189 EXPECT_EQ("en", d.data_received());
6190}
6191
6192// Check that an empty A-L header is not sent. http://crbug.com/77365.
6193TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6194 ASSERT_TRUE(test_server_.Start());
6195
[email protected]8790210c2013-12-02 05:29:536196 std::string empty_string; // Avoid most vexing parse on line below.
6197 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246198 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446199 TestURLRequestContext context(true);
6200 context.set_network_delegate(&network_delegate);
6201 context.Init();
6202 // We override the language after initialization because empty entries
6203 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436204 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446205
6206 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196207 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6208 DEFAULT_PRIORITY,
6209 &d,
6210 &context);
[email protected]316c1e5e2012-09-12 15:17:446211 req.Start();
[email protected]255620da2013-08-19 13:14:296212 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446213 EXPECT_EQ("None", d.data_received());
6214}
6215
6216// Check that if request overrides the A-L header, the default is not appended.
6217// See http://crbug.com/20894
6218TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6219 ASSERT_TRUE(test_server_.Start());
6220
6221 TestDelegate d;
6222 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
[email protected]2ca01e52013-10-31 22:05:196223 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446224 &d,
6225 &default_context_);
6226 HttpRequestHeaders headers;
6227 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6228 req.SetExtraRequestHeaders(headers);
6229 req.Start();
[email protected]255620da2013-08-19 13:14:296230 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446231 EXPECT_EQ(std::string("ru"), d.data_received());
6232}
6233
6234// Check that default A-E header is sent.
6235TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6236 ASSERT_TRUE(test_server_.Start());
6237
6238 TestDelegate d;
6239 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
[email protected]2ca01e52013-10-31 22:05:196240 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446241 &d,
6242 &default_context_);
6243 HttpRequestHeaders headers;
6244 req.SetExtraRequestHeaders(headers);
6245 req.Start();
[email protected]255620da2013-08-19 13:14:296246 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446247 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6248}
6249
6250// Check that if request overrides the A-E header, the default is not appended.
6251// See http://crbug.com/47381
6252TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6253 ASSERT_TRUE(test_server_.Start());
6254
6255 TestDelegate d;
6256 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
[email protected]2ca01e52013-10-31 22:05:196257 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446258 &d,
6259 &default_context_);
6260 HttpRequestHeaders headers;
6261 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6262 req.SetExtraRequestHeaders(headers);
6263 req.Start();
[email protected]255620da2013-08-19 13:14:296264 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446265 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6266 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6267}
6268
[email protected]84f05432013-03-15 01:00:126269// Check that setting the A-C header sends the proper header.
6270TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446271 ASSERT_TRUE(test_server_.Start());
6272
6273 TestDelegate d;
6274 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
[email protected]2ca01e52013-10-31 22:05:196275 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446276 &d,
6277 &default_context_);
6278 HttpRequestHeaders headers;
6279 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6280 req.SetExtraRequestHeaders(headers);
6281 req.Start();
[email protected]255620da2013-08-19 13:14:296282 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446283 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6284}
6285
6286// Check that default User-Agent header is sent.
6287TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6288 ASSERT_TRUE(test_server_.Start());
6289
6290 TestDelegate d;
6291 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
[email protected]2ca01e52013-10-31 22:05:196292 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446293 &d,
6294 &default_context_);
6295 req.Start();
[email protected]255620da2013-08-19 13:14:296296 base::RunLoop().Run();
[email protected]aa051272014-03-10 05:56:566297 EXPECT_EQ(req.context()->http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376298 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446299}
6300
6301// Check that if request overrides the User-Agent header,
6302// the default is not appended.
6303TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6304 ASSERT_TRUE(test_server_.Start());
6305
6306 TestDelegate d;
6307 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
[email protected]2ca01e52013-10-31 22:05:196308 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446309 &d,
6310 &default_context_);
6311 HttpRequestHeaders headers;
6312 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6313 req.SetExtraRequestHeaders(headers);
6314 req.Start();
[email protected]255620da2013-08-19 13:14:296315 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356316 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446317}
6318
[email protected]ee4c30d2012-11-07 15:08:436319// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6320// User-Agent header to be sent but does not send the Accept-Language and
6321// Accept-Charset headers.
6322TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6323 ASSERT_TRUE(test_server_.Start());
6324
[email protected]ceefd7fd2012-11-29 00:36:246325 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436326 TestURLRequestContext context(true);
6327 context.set_network_delegate(&network_delegate);
6328 context.Init();
6329 // We override the HttpUserAgentSettings after initialization because empty
6330 // entries get overridden by Init().
6331 context.set_http_user_agent_settings(NULL);
6332
6333 struct {
6334 const char* request;
6335 const char* expected_response;
6336 } tests[] = { { "echoheader?Accept-Language", "None" },
6337 { "echoheader?Accept-Charset", "None" },
6338 { "echoheader?User-Agent", "" } };
6339
6340 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
6341 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196342 URLRequest req(
6343 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, &context);
[email protected]ee4c30d2012-11-07 15:08:436344 req.Start();
[email protected]255620da2013-08-19 13:14:296345 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436346 EXPECT_EQ(tests[i].expected_response, d.data_received())
6347 << " Request = \"" << tests[i].request << "\"";
6348 }
6349}
6350
[email protected]5033ab82013-03-22 20:17:466351// Make sure that URLRequest passes on its priority updates to
6352// newly-created jobs after the first one.
6353TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6354 ASSERT_TRUE(test_server_.Start());
6355
6356 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196357 URLRequest req(test_server_.GetURL("empty.html"),
6358 DEFAULT_PRIORITY,
6359 &d,
6360 &default_context_);
[email protected]5033ab82013-03-22 20:17:466361 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
6362
6363 scoped_refptr<URLRequestRedirectJob> redirect_job =
6364 new URLRequestRedirectJob(
6365 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096366 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506367 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466368
6369 req.SetPriority(LOW);
6370 req.Start();
6371 EXPECT_TRUE(req.is_pending());
6372
6373 scoped_refptr<URLRequestTestJob> job =
6374 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506375 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466376
6377 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296378 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466379 EXPECT_EQ(LOW, job->priority());
6380}
6381
[email protected]80abdad2014-03-15 00:20:546382// Check that creating a network request while entering/exiting suspend mode
6383// fails as it should. This is the only case where an HttpTransactionFactory
6384// does not return an HttpTransaction.
6385TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6386 // Create a new HttpNetworkLayer that thinks it's suspended.
6387 HttpNetworkSession::Params params;
6388 params.host_resolver = default_context_.host_resolver();
6389 params.cert_verifier = default_context_.cert_verifier();
6390 params.transport_security_state = default_context_.transport_security_state();
6391 params.proxy_service = default_context_.proxy_service();
6392 params.ssl_config_service = default_context_.ssl_config_service();
6393 params.http_auth_handler_factory =
6394 default_context_.http_auth_handler_factory();
6395 params.network_delegate = &default_network_delegate_;
6396 params.http_server_properties = default_context_.http_server_properties();
6397 scoped_ptr<HttpNetworkLayer> network_layer(
6398 new HttpNetworkLayer(new HttpNetworkSession(params)));
6399 network_layer->OnSuspend();
6400
6401 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6402 HttpCache::DefaultBackend::InMemory(0));
6403
6404 TestURLRequestContext context(true);
6405 context.set_http_transaction_factory(&http_cache);
6406 context.Init();
6407
6408 TestDelegate d;
6409 URLRequest req(GURL("http://127.0.0.1/"),
6410 DEFAULT_PRIORITY,
6411 &d,
6412 &context);
6413 req.Start();
6414 base::RunLoop().Run();
6415
6416 EXPECT_TRUE(d.request_failed());
6417 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6418 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6419}
6420
6421// Check that creating a network request while entering/exiting suspend mode
6422// fails as it should in the case there is no cache. This is the only case
6423// where an HttpTransactionFactory does not return an HttpTransaction.
6424TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6425 // Create a new HttpNetworkLayer that thinks it's suspended.
6426 HttpNetworkSession::Params params;
6427 params.host_resolver = default_context_.host_resolver();
6428 params.cert_verifier = default_context_.cert_verifier();
6429 params.transport_security_state = default_context_.transport_security_state();
6430 params.proxy_service = default_context_.proxy_service();
6431 params.ssl_config_service = default_context_.ssl_config_service();
6432 params.http_auth_handler_factory =
6433 default_context_.http_auth_handler_factory();
6434 params.network_delegate = &default_network_delegate_;
6435 params.http_server_properties = default_context_.http_server_properties();
6436 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6437 network_layer.OnSuspend();
6438
6439 TestURLRequestContext context(true);
6440 context.set_http_transaction_factory(&network_layer);
6441 context.Init();
6442
6443 TestDelegate d;
6444 URLRequest req(GURL("http://127.0.0.1/"),
6445 DEFAULT_PRIORITY,
6446 &d,
6447 &context);
6448 req.Start();
6449 base::RunLoop().Run();
6450
6451 EXPECT_TRUE(d.request_failed());
6452 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6453 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6454}
6455
[email protected]73e0bba2009-02-19 22:57:096456class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:506457 public:
[email protected]ef2bf422012-05-11 03:27:096458 HTTPSRequestTest() : default_context_(true) {
6459 default_context_.set_network_delegate(&default_network_delegate_);
6460 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:506461 }
6462 virtual ~HTTPSRequestTest() {}
6463
6464 protected:
[email protected]ceefd7fd2012-11-29 00:36:246465 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:096466 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:466467};
6468
[email protected]c044616e2013-02-20 02:01:266469TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226470 SpawnedTestServer test_server(
6471 SpawnedTestServer::TYPE_HTTPS,
6472 SpawnedTestServer::kLocalhost,
6473 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116474 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:466475
[email protected]ea224582008-12-07 20:25:466476 TestDelegate d;
6477 {
[email protected]2ca01e52013-10-31 22:05:196478 URLRequest r(test_server.GetURL(std::string()),
6479 DEFAULT_PRIORITY,
6480 &d,
6481 &default_context_);
[email protected]ea224582008-12-07 20:25:466482 r.Start();
6483 EXPECT_TRUE(r.is_pending());
6484
[email protected]255620da2013-08-19 13:14:296485 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:466486
6487 EXPECT_EQ(1, d.response_started_count());
6488 EXPECT_FALSE(d.received_data_before_response());
6489 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176490 CheckSSLInfo(r.ssl_info());
[email protected]6d81b482011-02-22 19:47:196491 EXPECT_EQ(test_server.host_port_pair().host(),
6492 r.GetSocketAddress().host());
6493 EXPECT_EQ(test_server.host_port_pair().port(),
6494 r.GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:466495 }
[email protected]ea224582008-12-07 20:25:466496}
6497
[email protected]5774ada2010-07-15 06:30:546498TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226499 SpawnedTestServer::SSLOptions ssl_options(
6500 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6501 SpawnedTestServer test_server(
6502 SpawnedTestServer::TYPE_HTTPS,
6503 ssl_options,
6504 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116505 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:336506
6507 bool err_allowed = true;
6508 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6509 TestDelegate d;
6510 {
6511 d.set_allow_certificate_errors(err_allowed);
[email protected]2ca01e52013-10-31 22:05:196512 URLRequest r(test_server.GetURL(std::string()),
6513 DEFAULT_PRIORITY,
6514 &d,
6515 &default_context_);
[email protected]bacff652009-03-31 17:50:336516
6517 r.Start();
6518 EXPECT_TRUE(r.is_pending());
6519
[email protected]255620da2013-08-19 13:14:296520 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:336521
6522 EXPECT_EQ(1, d.response_started_count());
6523 EXPECT_FALSE(d.received_data_before_response());
6524 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:176525 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:336526 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176527 CheckSSLInfo(r.ssl_info());
6528 } else {
[email protected]bacff652009-03-31 17:50:336529 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176530 }
[email protected]bacff652009-03-31 17:50:336531 }
6532 }
6533}
6534
[email protected]5774ada2010-07-15 06:30:546535TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226536 SpawnedTestServer::SSLOptions ssl_options(
6537 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6538 SpawnedTestServer test_server(
6539 SpawnedTestServer::TYPE_HTTPS,
6540 ssl_options,
6541 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116542 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:336543
6544 // Iterate from false to true, just so that we do the opposite of the
6545 // previous test in order to increase test coverage.
6546 bool err_allowed = false;
6547 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6548 TestDelegate d;
6549 {
6550 d.set_allow_certificate_errors(err_allowed);
[email protected]2ca01e52013-10-31 22:05:196551 URLRequest r(test_server.GetURL(std::string()),
6552 DEFAULT_PRIORITY,
6553 &d,
6554 &default_context_);
[email protected]bacff652009-03-31 17:50:336555
6556 r.Start();
6557 EXPECT_TRUE(r.is_pending());
6558
[email protected]255620da2013-08-19 13:14:296559 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:336560
6561 EXPECT_EQ(1, d.response_started_count());
6562 EXPECT_FALSE(d.received_data_before_response());
6563 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:176564 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:336565 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176566 CheckSSLInfo(r.ssl_info());
6567 } else {
[email protected]bacff652009-03-31 17:50:336568 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176569 }
[email protected]bacff652009-03-31 17:50:336570 }
6571 }
6572}
[email protected]73e0bba2009-02-19 22:57:096573
[email protected]316c1e5e2012-09-12 15:17:446574// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
6575// than necessary.
6576TEST_F(HTTPSRequestTest, TLSv1Fallback) {
[email protected]316c1e5e2012-09-12 15:17:446577 // The OpenSSL library in use may not support TLS 1.1.
6578#if !defined(USE_OPENSSL)
[email protected]c091d3602014-03-24 02:32:486579 EXPECT_GT(kDefaultSSLVersionMax, SSL_PROTOCOL_VERSION_TLS1);
[email protected]316c1e5e2012-09-12 15:17:446580#endif
[email protected]c091d3602014-03-24 02:32:486581 if (kDefaultSSLVersionMax <= SSL_PROTOCOL_VERSION_TLS1)
[email protected]316c1e5e2012-09-12 15:17:446582 return;
6583
[email protected]ce7d0cbc2013-05-03 18:57:226584 SpawnedTestServer::SSLOptions ssl_options(
6585 SpawnedTestServer::SSLOptions::CERT_OK);
[email protected]316c1e5e2012-09-12 15:17:446586 ssl_options.tls_intolerant =
[email protected]ce7d0cbc2013-05-03 18:57:226587 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
6588 SpawnedTestServer test_server(
6589 SpawnedTestServer::TYPE_HTTPS,
6590 ssl_options,
6591 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446592 ASSERT_TRUE(test_server.Start());
6593
6594 TestDelegate d;
6595 TestURLRequestContext context(true);
6596 context.Init();
6597 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:196598 URLRequest r(
6599 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:446600 r.Start();
6601
[email protected]255620da2013-08-19 13:14:296602 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446603
6604 EXPECT_EQ(1, d.response_started_count());
6605 EXPECT_NE(0, d.bytes_received());
6606 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
6607 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6608 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6609}
6610
[email protected]974fbdfb2013-12-11 20:16:136611// Tests that we don't fallback with servers that implement TLS_FALLBACK_SCSV.
6612#if defined(USE_OPENSSL)
6613TEST_F(HTTPSRequestTest, DISABLED_FallbackSCSV) {
6614#else
6615TEST_F(HTTPSRequestTest, FallbackSCSV) {
6616#endif
6617 SpawnedTestServer::SSLOptions ssl_options(
6618 SpawnedTestServer::SSLOptions::CERT_OK);
6619 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
6620 // a version fallback.
6621 ssl_options.tls_intolerant =
6622 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6623 // Have the server process TLS_FALLBACK_SCSV so that version fallback
6624 // connections are rejected.
6625 ssl_options.fallback_scsv_enabled = true;
6626
6627 SpawnedTestServer test_server(
6628 SpawnedTestServer::TYPE_HTTPS,
6629 ssl_options,
6630 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6631 ASSERT_TRUE(test_server.Start());
6632
6633 TestDelegate d;
6634 TestURLRequestContext context(true);
6635 context.Init();
6636 d.set_allow_certificate_errors(true);
6637 URLRequest r(
6638 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6639 r.Start();
6640
6641 base::RunLoop().Run();
6642
6643 EXPECT_EQ(1, d.response_started_count());
6644 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
6645 // intolerance. If the fallback SCSV is processed when the original error
6646 // that caused the fallback should be returned, which should be
6647 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
6648 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, r.status().error());
6649}
6650
[email protected]316c1e5e2012-09-12 15:17:446651// This tests that a load of www.google.com with a certificate error sets
6652// the |certificate_errors_are_fatal| flag correctly. This flag will cause
6653// the interstitial to be fatal.
6654TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226655 SpawnedTestServer::SSLOptions ssl_options(
6656 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6657 SpawnedTestServer test_server(
6658 SpawnedTestServer::TYPE_HTTPS,
6659 ssl_options,
6660 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446661 ASSERT_TRUE(test_server.Start());
6662
6663 // We require that the URL be www.google.com in order to pick up the
6664 // preloaded HSTS entries in the TransportSecurityState. This means that we
6665 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:246666 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:446667
6668 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:246669 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446670 TestURLRequestContext context(true);
6671 context.set_network_delegate(&network_delegate);
6672 context.set_host_resolver(&host_resolver);
6673 TransportSecurityState transport_security_state;
6674 context.set_transport_security_state(&transport_security_state);
6675 context.Init();
6676
6677 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:046678 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6679 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196680 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446681 &d,
6682 &context);
6683
6684 r.Start();
6685 EXPECT_TRUE(r.is_pending());
6686
[email protected]255620da2013-08-19 13:14:296687 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446688
6689 EXPECT_EQ(1, d.response_started_count());
6690 EXPECT_FALSE(d.received_data_before_response());
6691 EXPECT_TRUE(d.have_certificate_errors());
6692 EXPECT_TRUE(d.certificate_errors_are_fatal());
6693}
6694
6695// This tests that cached HTTPS page loads do not cause any updates to the
6696// TransportSecurityState.
6697TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6698 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6699 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:226700 SpawnedTestServer::SSLOptions ssl_options(
6701 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6702 SpawnedTestServer test_server(
6703 SpawnedTestServer::TYPE_HTTPS,
6704 ssl_options,
6705 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446706 ASSERT_TRUE(test_server.Start());
6707
[email protected]9e6968d2014-05-07 21:46:266708 // We require that the URL be www.google.com in order to pick up the static
6709 // and dynamic STS and PKP entries in the TransportSecurityState. This means
6710 // that we have to use a MockHostResolver in order to direct www.google.com to
6711 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:446712
6713 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:246714 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446715 TestURLRequestContext context(true);
6716 context.set_network_delegate(&network_delegate);
6717 context.set_host_resolver(&host_resolver);
6718 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:266719
6720 TransportSecurityState::DomainState static_domain_state;
6721 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6722 "www.google.com", true, &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:446723 context.set_transport_security_state(&transport_security_state);
6724 context.Init();
6725
[email protected]9e6968d2014-05-07 21:46:266726 TransportSecurityState::DomainState dynamic_domain_state;
6727 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6728 "www.google.com", &dynamic_domain_state));
6729
[email protected]316c1e5e2012-09-12 15:17:446730 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:046731 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6732 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196733 DEFAULT_PRIORITY,
[email protected]316c1e5e2012-09-12 15:17:446734 &d,
6735 &context);
6736
6737 r.Start();
6738 EXPECT_TRUE(r.is_pending());
6739
[email protected]255620da2013-08-19 13:14:296740 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446741
6742 EXPECT_EQ(1, d.response_started_count());
6743 EXPECT_FALSE(d.received_data_before_response());
6744 EXPECT_TRUE(d.have_certificate_errors());
6745 EXPECT_TRUE(d.certificate_errors_are_fatal());
6746
[email protected]9e6968d2014-05-07 21:46:266747 // Get a fresh copy of the states, and check that they haven't changed.
6748 TransportSecurityState::DomainState new_static_domain_state;
6749 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6750 "www.google.com", true, &new_static_domain_state));
6751 TransportSecurityState::DomainState new_dynamic_domain_state;
6752 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6753 "www.google.com", &new_dynamic_domain_state));
6754
6755 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
6756 static_domain_state.sts.upgrade_mode);
6757 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
6758 static_domain_state.sts.include_subdomains);
6759 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
6760 static_domain_state.pkp.include_subdomains);
6761 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
6762 static_domain_state.pkp.spki_hashes));
6763 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
6764 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:446765}
6766
[email protected]8ccc69f2012-11-28 19:52:146767// Make sure HSTS preserves a POST request's method and body.
6768TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6769 static const char kData[] = "hello world";
6770
[email protected]ce7d0cbc2013-05-03 18:57:226771 SpawnedTestServer::SSLOptions ssl_options(
6772 SpawnedTestServer::SSLOptions::CERT_OK);
6773 SpawnedTestServer test_server(
6774 SpawnedTestServer::TYPE_HTTPS,
6775 ssl_options,
6776 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:146777 ASSERT_TRUE(test_server.Start());
6778
6779
6780 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6781 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:226782 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6783 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:146784 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:146785
6786 // Force https for www.somewhere.com.
6787 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:206788 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6789 bool include_subdomains = false;
6790 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6791 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:146792
6793 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6794
6795 TestURLRequestContext context(true);
6796 context.set_host_resolver(&host_resolver);
6797 context.set_transport_security_state(&transport_security_state);
6798 context.set_network_delegate(&network_delegate);
6799 context.Init();
6800
6801 TestDelegate d;
6802 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6803 // cause a certificate error. Ignore the error.
6804 d.set_allow_certificate_errors(true);
6805
[email protected]7d3cbc92013-03-18 22:33:046806 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6807 test_server.host_port_pair().port())),
[email protected]2ca01e52013-10-31 22:05:196808 DEFAULT_PRIORITY,
[email protected]8ccc69f2012-11-28 19:52:146809 &d,
6810 &context);
6811 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:286812 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]8ccc69f2012-11-28 19:52:146813
6814 req.Start();
[email protected]255620da2013-08-19 13:14:296815 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:146816
6817 EXPECT_EQ("https", req.url().scheme());
6818 EXPECT_EQ("POST", req.method());
6819 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:406820
6821 LoadTimingInfo load_timing_info;
6822 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6823 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6824 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:146825}
6826
[email protected]316c1e5e2012-09-12 15:17:446827TEST_F(HTTPSRequestTest, SSLv3Fallback) {
[email protected]ce7d0cbc2013-05-03 18:57:226828 SpawnedTestServer::SSLOptions ssl_options(
6829 SpawnedTestServer::SSLOptions::CERT_OK);
6830 ssl_options.tls_intolerant =
6831 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6832 SpawnedTestServer test_server(
6833 SpawnedTestServer::TYPE_HTTPS,
6834 ssl_options,
6835 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446836 ASSERT_TRUE(test_server.Start());
6837
6838 TestDelegate d;
6839 TestURLRequestContext context(true);
6840 context.Init();
6841 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:196842 URLRequest r(
6843 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
[email protected]316c1e5e2012-09-12 15:17:446844 r.Start();
6845
[email protected]255620da2013-08-19 13:14:296846 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446847
6848 EXPECT_EQ(1, d.response_started_count());
6849 EXPECT_NE(0, d.bytes_received());
6850 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
6851 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6852 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6853}
6854
6855namespace {
6856
6857class SSLClientAuthTestDelegate : public TestDelegate {
6858 public:
6859 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6860 }
6861 virtual void OnCertificateRequested(
6862 URLRequest* request,
[email protected]46fadfd2013-02-06 09:40:166863 SSLCertRequestInfo* cert_request_info) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:446864 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:346865 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:446866 }
6867 int on_certificate_requested_count() {
6868 return on_certificate_requested_count_;
6869 }
6870 private:
6871 int on_certificate_requested_count_;
6872};
6873
6874} // namespace
6875
6876// TODO(davidben): Test the rest of the code. Specifically,
6877// - Filtering which certificates to select.
6878// - Sending a certificate back.
6879// - Getting a certificate request in an SSL renegotiation sending the
6880// HTTP request.
6881TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226882 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446883 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:226884 SpawnedTestServer test_server(
6885 SpawnedTestServer::TYPE_HTTPS,
6886 ssl_options,
6887 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446888 ASSERT_TRUE(test_server.Start());
6889
6890 SSLClientAuthTestDelegate d;
6891 {
[email protected]2ca01e52013-10-31 22:05:196892 URLRequest r(test_server.GetURL(std::string()),
6893 DEFAULT_PRIORITY,
6894 &d,
6895 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446896
6897 r.Start();
6898 EXPECT_TRUE(r.is_pending());
6899
[email protected]255620da2013-08-19 13:14:296900 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446901
6902 EXPECT_EQ(1, d.on_certificate_requested_count());
6903 EXPECT_FALSE(d.received_data_before_response());
6904 EXPECT_EQ(0, d.bytes_received());
6905
6906 // Send no certificate.
6907 // TODO(davidben): Get temporary client cert import (with keys) working on
6908 // all platforms so we can test sending a cert as well.
6909 r.ContinueWithCertificate(NULL);
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 EXPECT_FALSE(d.received_data_before_response());
6915 EXPECT_NE(0, d.bytes_received());
6916 }
6917}
6918
6919TEST_F(HTTPSRequestTest, ResumeTest) {
6920 // Test that we attempt a session resume when making two connections to the
6921 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:226922 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446923 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:226924 SpawnedTestServer test_server(
6925 SpawnedTestServer::TYPE_HTTPS,
6926 ssl_options,
6927 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446928 ASSERT_TRUE(test_server.Start());
6929
6930 SSLClientSocket::ClearSessionCache();
6931
6932 {
6933 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196934 URLRequest r(test_server.GetURL("ssl-session-cache"),
6935 DEFAULT_PRIORITY,
6936 &d,
6937 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446938
6939 r.Start();
6940 EXPECT_TRUE(r.is_pending());
6941
[email protected]255620da2013-08-19 13:14:296942 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446943
6944 EXPECT_EQ(1, d.response_started_count());
6945 }
6946
6947 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6948 CloseAllConnections();
6949
6950 {
6951 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:196952 URLRequest r(test_server.GetURL("ssl-session-cache"),
6953 DEFAULT_PRIORITY,
6954 &d,
6955 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:446956
6957 r.Start();
6958 EXPECT_TRUE(r.is_pending());
6959
[email protected]255620da2013-08-19 13:14:296960 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446961
6962 // The response will look like;
6963 // insert abc
6964 // lookup abc
6965 // insert xyz
6966 //
6967 // With a newline at the end which makes the split think that there are
6968 // four lines.
6969
6970 EXPECT_EQ(1, d.response_started_count());
6971 std::vector<std::string> lines;
6972 base::SplitString(d.data_received(), '\n', &lines);
6973 ASSERT_EQ(4u, lines.size()) << d.data_received();
6974
6975 std::string session_id;
6976
6977 for (size_t i = 0; i < 2; i++) {
6978 std::vector<std::string> parts;
6979 base::SplitString(lines[i], '\t', &parts);
6980 ASSERT_EQ(2u, parts.size());
6981 if (i == 0) {
6982 EXPECT_EQ("insert", parts[0]);
6983 session_id = parts[1];
6984 } else {
6985 EXPECT_EQ("lookup", parts[0]);
6986 EXPECT_EQ(session_id, parts[1]);
6987 }
6988 }
6989 }
6990}
6991
6992TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6993 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6994 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:226995 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446996 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:226997 SpawnedTestServer test_server(
6998 SpawnedTestServer::TYPE_HTTPS,
6999 ssl_options,
7000 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447001 ASSERT_TRUE(test_server.Start());
7002
7003 SSLClientSocket::ClearSessionCache();
7004
7005 {
7006 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:197007 URLRequest r(test_server.GetURL("ssl-session-cache"),
7008 DEFAULT_PRIORITY,
7009 &d,
7010 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:447011
7012 r.Start();
7013 EXPECT_TRUE(r.is_pending());
7014
[email protected]255620da2013-08-19 13:14:297015 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447016
7017 EXPECT_EQ(1, d.response_started_count());
7018 }
7019
7020 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7021 HttpNetworkSession::Params params;
7022 params.host_resolver = default_context_.host_resolver();
7023 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117024 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447025 params.proxy_service = default_context_.proxy_service();
7026 params.ssl_config_service = default_context_.ssl_config_service();
7027 params.http_auth_handler_factory =
7028 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417029 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447030 params.http_server_properties = default_context_.http_server_properties();
7031 params.ssl_session_cache_shard = "alternate";
7032
7033 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
7034 new net::HttpNetworkSession(params),
7035 net::HttpCache::DefaultBackend::InMemory(0)));
7036
7037 default_context_.set_http_transaction_factory(cache.get());
7038
7039 {
7040 TestDelegate d;
[email protected]2ca01e52013-10-31 22:05:197041 URLRequest r(test_server.GetURL("ssl-session-cache"),
7042 DEFAULT_PRIORITY,
7043 &d,
7044 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:447045
7046 r.Start();
7047 EXPECT_TRUE(r.is_pending());
7048
[email protected]255620da2013-08-19 13:14:297049 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447050
7051 // The response will look like;
7052 // insert abc
7053 // insert xyz
7054 //
7055 // With a newline at the end which makes the split think that there are
7056 // three lines.
7057
7058 EXPECT_EQ(1, d.response_started_count());
7059 std::vector<std::string> lines;
7060 base::SplitString(d.data_received(), '\n', &lines);
7061 ASSERT_EQ(3u, lines.size());
7062
7063 std::string session_id;
7064 for (size_t i = 0; i < 2; i++) {
7065 std::vector<std::string> parts;
7066 base::SplitString(lines[i], '\t', &parts);
7067 ASSERT_EQ(2u, parts.size());
7068 EXPECT_EQ("insert", parts[0]);
7069 if (i == 0) {
7070 session_id = parts[1];
7071 } else {
7072 EXPECT_NE(session_id, parts[1]);
7073 }
7074 }
7075 }
7076}
7077
[email protected]a8fed1742013-12-27 02:14:247078class HTTPSSessionTest : public testing::Test {
7079 public:
7080 HTTPSSessionTest() : default_context_(true) {
7081 cert_verifier_.set_default_result(net::OK);
7082
7083 default_context_.set_network_delegate(&default_network_delegate_);
7084 default_context_.set_cert_verifier(&cert_verifier_);
7085 default_context_.Init();
7086 }
7087 virtual ~HTTPSSessionTest() {}
7088
7089 protected:
7090 MockCertVerifier cert_verifier_;
7091 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7092 TestURLRequestContext default_context_;
7093};
7094
7095// Tests that session resumption is not attempted if an invalid certificate
7096// is presented.
7097TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7098 SpawnedTestServer::SSLOptions ssl_options;
7099 ssl_options.record_resume = true;
7100 SpawnedTestServer test_server(
7101 SpawnedTestServer::TYPE_HTTPS,
7102 ssl_options,
7103 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7104 ASSERT_TRUE(test_server.Start());
7105
7106 SSLClientSocket::ClearSessionCache();
7107
7108 // Simulate the certificate being expired and attempt a connection.
7109 cert_verifier_.set_default_result(net::ERR_CERT_DATE_INVALID);
7110 {
7111 TestDelegate d;
7112 URLRequest r(test_server.GetURL("ssl-session-cache"),
7113 DEFAULT_PRIORITY,
7114 &d,
7115 &default_context_);
7116
7117 r.Start();
7118 EXPECT_TRUE(r.is_pending());
7119
7120 base::RunLoop().Run();
7121
7122 EXPECT_EQ(1, d.response_started_count());
7123 }
7124
7125 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7126 CloseAllConnections();
7127
7128 // Now change the certificate to be acceptable (so that the response is
7129 // loaded), and ensure that no session id is presented to the peer.
7130 cert_verifier_.set_default_result(net::OK);
7131 {
7132 TestDelegate d;
7133 URLRequest r(test_server.GetURL("ssl-session-cache"),
7134 DEFAULT_PRIORITY,
7135 &d,
7136 &default_context_);
7137
7138 r.Start();
7139 EXPECT_TRUE(r.is_pending());
7140
7141 base::RunLoop().Run();
7142
7143 // The response will look like;
7144 // insert abc
7145 // insert xyz
7146 //
7147 // With a newline at the end which makes the split think that there are
7148 // three lines.
7149 //
7150 // If a session was presented (eg: a bug), then the response would look
7151 // like;
7152 // insert abc
7153 // lookup abc
7154 // insert xyz
7155
7156 EXPECT_EQ(1, d.response_started_count());
7157 std::vector<std::string> lines;
7158 base::SplitString(d.data_received(), '\n', &lines);
7159 ASSERT_EQ(3u, lines.size()) << d.data_received();
7160
7161 std::string session_id;
7162 for (size_t i = 0; i < 2; i++) {
7163 std::vector<std::string> parts;
7164 base::SplitString(lines[i], '\t', &parts);
7165 ASSERT_EQ(2u, parts.size());
7166 EXPECT_EQ("insert", parts[0]);
7167 if (i == 0) {
7168 session_id = parts[1];
7169 } else {
7170 EXPECT_NE(session_id, parts[1]);
7171 }
7172 }
7173 }
7174}
7175
[email protected]a13234c2012-03-20 21:45:027176class TestSSLConfigService : public SSLConfigService {
[email protected]dffe8242012-03-20 15:14:277177 public:
[email protected]3a86a712013-07-30 07:16:207178 TestSSLConfigService(bool ev_enabled,
7179 bool online_rev_checking,
7180 bool rev_checking_required_local_anchors)
[email protected]a13234c2012-03-20 21:45:027181 : ev_enabled_(ev_enabled),
[email protected]3a86a712013-07-30 07:16:207182 online_rev_checking_(online_rev_checking),
7183 rev_checking_required_local_anchors_(
7184 rev_checking_required_local_anchors) {}
[email protected]a13234c2012-03-20 21:45:027185
[email protected]a9813302012-04-28 09:29:287186 // SSLConfigService:
7187 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
[email protected]dffe8242012-03-20 15:14:277188 *config = SSLConfig();
[email protected]a13234c2012-03-20 21:45:027189 config->rev_checking_enabled = online_rev_checking_;
7190 config->verify_ev_cert = ev_enabled_;
[email protected]3a86a712013-07-30 07:16:207191 config->rev_checking_required_local_anchors =
7192 rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:277193 }
[email protected]a13234c2012-03-20 21:45:027194
[email protected]a9813302012-04-28 09:29:287195 protected:
7196 virtual ~TestSSLConfigService() {}
7197
[email protected]a13234c2012-03-20 21:45:027198 private:
7199 const bool ev_enabled_;
7200 const bool online_rev_checking_;
[email protected]3a86a712013-07-30 07:16:207201 const bool rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:277202};
7203
7204// This the fingerprint of the "Testing CA" certificate used by the testserver.
7205// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:267206static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:277207 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7208 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7209
[email protected]51523f52013-07-31 21:57:287210// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7211// testserver.
7212static const SHA256HashValue kOCSPTestCertSPKI = { {
7213 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7214 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7215 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7216 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7217} };
7218
[email protected]dffe8242012-03-20 15:14:277219// This is the policy OID contained in the certificates that testserver
7220// generates.
7221static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
7222
7223class HTTPSOCSPTest : public HTTPSRequestTest {
7224 public:
7225 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:097226 : context_(true),
[email protected]b6f2de32012-08-17 04:35:087227 ev_test_policy_(
7228 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7229 kOCSPTestCertFingerprint,
7230 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:027231 }
7232
7233 virtual void SetUp() OVERRIDE {
[email protected]ef2bf422012-05-11 03:27:097234 SetupContext(&context_);
7235 context_.Init();
[email protected]dffe8242012-03-20 15:14:277236
7237 scoped_refptr<net::X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:207238 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
[email protected]dffe8242012-03-20 15:14:277239 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
[email protected]90499482013-06-01 00:39:507240 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:277241
[email protected]a592c0432012-12-01 18:10:297242#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:097243 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:277244 EnsureNSSHttpIOInit();
7245#endif
7246 }
7247
[email protected]ce7d0cbc2013-05-03 18:57:227248 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:277249 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:537250 // We always overwrite out_cert_status.
7251 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:227252 SpawnedTestServer test_server(
7253 SpawnedTestServer::TYPE_HTTPS,
7254 ssl_options,
7255 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:277256 ASSERT_TRUE(test_server.Start());
7257
7258 TestDelegate d;
7259 d.set_allow_certificate_errors(true);
[email protected]2ca01e52013-10-31 22:05:197260 URLRequest r(
7261 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context_);
[email protected]dffe8242012-03-20 15:14:277262 r.Start();
7263
[email protected]255620da2013-08-19 13:14:297264 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:277265
7266 EXPECT_EQ(1, d.response_started_count());
7267 *out_cert_status = r.ssl_info().cert_status;
7268 }
7269
[email protected]46fadfd2013-02-06 09:40:167270 virtual ~HTTPSOCSPTest() {
[email protected]a592c0432012-12-01 18:10:297271#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:277272 ShutdownNSSHttpIO();
7273#endif
7274 }
7275
[email protected]a13234c2012-03-20 21:45:027276 protected:
7277 // SetupContext configures the URLRequestContext that will be used for making
7278 // connetions to testserver. This can be overridden in test subclasses for
7279 // different behaviour.
7280 virtual void SetupContext(URLRequestContext* context) {
7281 context->set_ssl_config_service(
7282 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:207283 true /* online revocation checking */,
7284 false /* require rev. checking for local
7285 anchors */));
[email protected]a13234c2012-03-20 21:45:027286 }
7287
[email protected]dffe8242012-03-20 15:14:277288 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:097289 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:087290 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:277291};
7292
[email protected]a13234c2012-03-20 21:45:027293static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:017294#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:027295 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7296 // have that ability on other platforms.
7297 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
7298#else
7299 return 0;
7300#endif
7301}
7302
[email protected]3a86a712013-07-30 07:16:207303// SystemSupportsHardFailRevocationChecking returns true iff the current
7304// operating system supports revocation checking and can distinguish between
7305// situations where a given certificate lacks any revocation information (eg:
7306// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7307// revocation information cannot be obtained (eg: the CRL was unreachable).
7308// If it does not, then tests which rely on 'hard fail' behaviour should be
7309// skipped.
7310static bool SystemSupportsHardFailRevocationChecking() {
7311#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7312 return true;
7313#else
7314 return false;
7315#endif
7316}
7317
[email protected]a13234c2012-03-20 21:45:027318// SystemUsesChromiumEVMetadata returns true iff the current operating system
7319// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7320// several tests are effected because our testing EV certificate won't be
7321// recognised as EV.
7322static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:327323#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:577324 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7325 return false;
[email protected]e1b2d732014-03-28 16:20:327326#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7327 // On OS X and Android, we use the system to tell us whether a certificate is
7328 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:017329 return false;
7330#else
7331 return true;
7332#endif
7333}
7334
[email protected]b6f2de32012-08-17 04:35:087335static bool SystemSupportsOCSP() {
[email protected]5c504192012-03-27 19:00:577336#if defined(USE_OPENSSL)
7337 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7338 return false;
7339#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:027340 return base::win::GetVersion() >= base::win::VERSION_VISTA;
7341#elif defined(OS_ANDROID)
7342 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7343 return false;
7344#else
7345 return true;
7346#endif
7347}
7348
[email protected]dffe8242012-03-20 15:14:277349TEST_F(HTTPSOCSPTest, Valid) {
7350 if (!SystemSupportsOCSP()) {
7351 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7352 return;
7353 }
7354
[email protected]ce7d0cbc2013-05-03 18:57:227355 SpawnedTestServer::SSLOptions ssl_options(
7356 SpawnedTestServer::SSLOptions::CERT_AUTO);
7357 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:277358
[email protected]924e9f92012-12-16 22:00:537359 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127360 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:277361
7362 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7363
[email protected]a13234c2012-03-20 21:45:027364 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7365 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:277366
7367 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7368}
7369
7370TEST_F(HTTPSOCSPTest, Revoked) {
7371 if (!SystemSupportsOCSP()) {
7372 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7373 return;
7374 }
7375
[email protected]ce7d0cbc2013-05-03 18:57:227376 SpawnedTestServer::SSLOptions ssl_options(
7377 SpawnedTestServer::SSLOptions::CERT_AUTO);
7378 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:277379
7380 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127381 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:277382
[email protected]a592c0432012-12-01 18:10:297383#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:277384 // Doesn't pass on OS X yet for reasons that need to be investigated.
7385 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7386#endif
7387 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7388 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7389}
7390
7391TEST_F(HTTPSOCSPTest, Invalid) {
7392 if (!SystemSupportsOCSP()) {
7393 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7394 return;
7395 }
7396
[email protected]ce7d0cbc2013-05-03 18:57:227397 SpawnedTestServer::SSLOptions ssl_options(
7398 SpawnedTestServer::SSLOptions::CERT_AUTO);
7399 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:277400
[email protected]924e9f92012-12-16 22:00:537401 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127402 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:277403
[email protected]a13234c2012-03-20 21:45:027404 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:277405 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:277406
7407 // Without a positive OCSP response, we shouldn't show the EV status.
7408 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7409 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7410}
[email protected]a13234c2012-03-20 21:45:027411
[email protected]3a86a712013-07-30 07:16:207412class HTTPSHardFailTest : public HTTPSOCSPTest {
7413 protected:
7414 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7415 context->set_ssl_config_service(
7416 new TestSSLConfigService(false /* check for EV */,
7417 false /* online revocation checking */,
7418 true /* require rev. checking for local
7419 anchors */));
7420 }
7421};
7422
7423
7424TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
7425 if (!SystemSupportsOCSP()) {
7426 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7427 return;
7428 }
7429
7430 if (!SystemSupportsHardFailRevocationChecking()) {
7431 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
7432 << "revocation checking";
7433 return;
7434 }
7435
7436 SpawnedTestServer::SSLOptions ssl_options(
7437 SpawnedTestServer::SSLOptions::CERT_AUTO);
7438 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7439
7440 CertStatus cert_status;
7441 DoConnection(ssl_options, &cert_status);
7442
7443 EXPECT_EQ(CERT_STATUS_REVOKED,
7444 cert_status & CERT_STATUS_REVOKED);
7445
7446 // Without a positive OCSP response, we shouldn't show the EV status.
7447 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7448}
7449
[email protected]a13234c2012-03-20 21:45:027450class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
7451 protected:
7452 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7453 context->set_ssl_config_service(
7454 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:207455 false /* online revocation checking */,
7456 false /* require rev. checking for local
7457 anchors */));
[email protected]a13234c2012-03-20 21:45:027458 }
7459};
7460
7461TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
7462 if (!SystemSupportsOCSP()) {
7463 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7464 return;
7465 }
7466
[email protected]ce7d0cbc2013-05-03 18:57:227467 SpawnedTestServer::SSLOptions ssl_options(
7468 SpawnedTestServer::SSLOptions::CERT_AUTO);
7469 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027470 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7471
[email protected]924e9f92012-12-16 22:00:537472 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127473 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027474
7475 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7476 cert_status & CERT_STATUS_ALL_ERRORS);
7477
7478 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:087479 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7480 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027481}
7482
[email protected]be0fff62013-08-29 23:37:487483TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
7484 if (!SystemSupportsOCSP()) {
7485 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7486 return;
7487 }
7488
7489 SpawnedTestServer::SSLOptions ssl_options(
7490 SpawnedTestServer::SSLOptions::CERT_AUTO);
7491 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7492 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7493
7494 CertStatus cert_status;
7495 DoConnection(ssl_options, &cert_status);
7496
7497 // Currently only works for Windows. When using NSS or OS X, it's not
7498 // possible to determine whether the check failed because of actual
7499 // revocation or because there was an OCSP failure.
7500#if defined(OS_WIN)
7501 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7502#else
7503 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7504#endif
7505
7506 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7507 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7508 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7509}
7510
[email protected]a13234c2012-03-20 21:45:027511TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
7512 if (!SystemSupportsOCSP()) {
7513 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7514 return;
7515 }
7516
[email protected]ce7d0cbc2013-05-03 18:57:227517 SpawnedTestServer::SSLOptions ssl_options(
7518 SpawnedTestServer::SSLOptions::CERT_AUTO);
7519 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:027520 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7521
7522 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127523 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027524
7525 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7526
7527 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7528 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:087529 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7530 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027531}
7532
7533TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
7534 if (!SystemSupportsOCSP()) {
7535 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7536 return;
7537 }
7538
[email protected]ce7d0cbc2013-05-03 18:57:227539 SpawnedTestServer::SSLOptions ssl_options(
7540 SpawnedTestServer::SSLOptions::CERT_AUTO);
7541 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027542 SSLConfigService::SetCRLSet(
7543 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7544
7545 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127546 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027547
7548 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7549 cert_status & CERT_STATUS_ALL_ERRORS);
7550
7551 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:087552 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7553 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027554}
7555
[email protected]51523f52013-07-31 21:57:287556TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
7557 if (!SystemSupportsOCSP()) {
7558 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7559 return;
7560 }
7561
7562 SpawnedTestServer::SSLOptions ssl_options(
7563 SpawnedTestServer::SSLOptions::CERT_AUTO);
7564 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7565 SSLConfigService::SetCRLSet(
7566 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7567 false, &kOCSPTestCertSPKI, "")));
7568
7569 CertStatus cert_status;
7570 DoConnection(ssl_options, &cert_status);
7571
7572 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7573 // revocation check for EV.
7574 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7575 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7576 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7577 EXPECT_FALSE(
7578 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7579}
7580
7581TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
7582 if (!SystemSupportsOCSP()) {
7583 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7584 return;
7585 }
7586
[email protected]ce7d0cbc2013-05-03 18:57:227587 SpawnedTestServer::SSLOptions ssl_options(
7588 SpawnedTestServer::SSLOptions::CERT_AUTO);
7589 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027590 SSLConfigService::SetCRLSet(
7591 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
7592
[email protected]51523f52013-07-31 21:57:287593 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:127594 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027595
[email protected]51523f52013-07-31 21:57:287596 // Even with a fresh CRLSet, we should still do online revocation checks when
7597 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7598 // test.
7599 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7600 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:027601
[email protected]51523f52013-07-31 21:57:287602 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:027603 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:287604 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:027605}
7606
[email protected]b6f2de32012-08-17 04:35:087607TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
7608 // Test that when EV verification is requested, but online revocation
7609 // checking is disabled, and the leaf certificate is not in fact EV, that
7610 // no revocation checking actually happens.
7611 if (!SystemSupportsOCSP()) {
7612 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7613 return;
7614 }
7615
7616 // Unmark the certificate's OID as EV, which should disable revocation
7617 // checking (as per the user preference)
7618 ev_test_policy_.reset();
7619
[email protected]ce7d0cbc2013-05-03 18:57:227620 SpawnedTestServer::SSLOptions ssl_options(
7621 SpawnedTestServer::SSLOptions::CERT_AUTO);
7622 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:087623 SSLConfigService::SetCRLSet(
7624 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7625
7626 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127627 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:087628
7629 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7630
7631 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7632 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7633}
7634
[email protected]a13234c2012-03-20 21:45:027635class HTTPSCRLSetTest : public HTTPSOCSPTest {
7636 protected:
7637 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7638 context->set_ssl_config_service(
7639 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:207640 false /* online revocation checking */,
7641 false /* require rev. checking for local
7642 anchors */));
[email protected]a13234c2012-03-20 21:45:027643 }
7644};
7645
7646TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:227647 SpawnedTestServer::SSLOptions ssl_options(
7648 SpawnedTestServer::SSLOptions::CERT_AUTO);
7649 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:027650 SSLConfigService::SetCRLSet(
7651 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7652
[email protected]924e9f92012-12-16 22:00:537653 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:127654 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:027655
7656 // If we're not trying EV verification then, even if the CRLSet has expired,
7657 // we don't fall back to online revocation checks.
7658 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7659 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7660 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7661}
[email protected]51523f52013-07-31 21:57:287662
7663TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
7664#if defined(USE_OPENSSL)
7665 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
7666 return;
7667#endif
7668
7669 SpawnedTestServer::SSLOptions ssl_options(
7670 SpawnedTestServer::SSLOptions::CERT_AUTO);
7671 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7672 ssl_options.cert_serial = 10;
7673 SSLConfigService::SetCRLSet(
7674 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7675 false, &kOCSPTestCertSPKI, "\x0a")));
7676
7677 CertStatus cert_status = 0;
7678 DoConnection(ssl_options, &cert_status);
7679
7680 // If the certificate is recorded as revoked in the CRLSet, that should be
7681 // reflected without online revocation checking.
7682 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7683 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7684 EXPECT_FALSE(
7685 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7686}
[email protected]316c1e5e2012-09-12 15:17:447687#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:277688
[email protected]316c1e5e2012-09-12 15:17:447689#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:317690class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:117691 public:
[email protected]d9fca99a2012-02-24 16:16:207692 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:227693 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:157694 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:117695 }
7696
[email protected]b89ca032009-08-31 21:41:317697 protected:
[email protected]ce7d0cbc2013-05-03 18:57:227698 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:317699};
7700
[email protected]d2a133182012-08-05 16:44:087701// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:097702TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:087703 ASSERT_TRUE(test_server_.Start());
7704
[email protected]9d5730b2012-08-24 17:42:497705 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:347706 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:087707
7708 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:087709 job_factory.SetProtocolHandler(
7710 "ftp",
[email protected]e0f35c92013-05-08 16:04:347711 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:087712 default_context_.set_job_factory(&job_factory);
7713
7714 TestDelegate d;
7715 {
[email protected]2ca01e52013-10-31 22:05:197716 URLRequest r(url, DEFAULT_PRIORITY, &d, &default_context_);
[email protected]d2a133182012-08-05 16:44:087717 r.Start();
7718 EXPECT_TRUE(r.is_pending());
7719
[email protected]255620da2013-08-19 13:14:297720 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:087721
7722 EXPECT_FALSE(r.is_pending());
7723 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
7724 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
7725 }
7726}
7727
[email protected]5accf7332009-11-24 03:41:387728// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127729TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:117730 ASSERT_TRUE(test_server_.Start());
7731
[email protected]a25e90e2009-09-09 17:05:377732 TestDelegate d;
7733 {
[email protected]2ca01e52013-10-31 22:05:197734 URLRequest r(
7735 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, &default_context_);
[email protected]a25e90e2009-09-09 17:05:377736 r.Start();
7737 EXPECT_TRUE(r.is_pending());
7738
[email protected]255620da2013-08-19 13:14:297739 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:377740
7741 EXPECT_FALSE(r.is_pending());
7742 EXPECT_EQ(1, d.response_started_count());
7743 EXPECT_FALSE(d.received_data_before_response());
7744 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:197745 EXPECT_EQ(test_server_.host_port_pair().host(),
7746 r.GetSocketAddress().host());
7747 EXPECT_EQ(test_server_.host_port_pair().port(),
7748 r.GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:377749 }
7750}
7751
[email protected]7df70012010-02-04 00:09:557752// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127753TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:117754 ASSERT_TRUE(test_server_.Start());
7755
[email protected]6cdfd7f2013-02-08 20:40:157756 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277757 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027758 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277759 TestDelegate d;
7760 {
[email protected]2ca01e52013-10-31 22:05:197761 URLRequest r(test_server_.GetURL("/LICENSE"),
7762 DEFAULT_PRIORITY,
7763 &d,
7764 &default_context_);
[email protected]dd265012009-01-08 20:45:277765 r.Start();
7766 EXPECT_TRUE(r.is_pending());
7767
[email protected]255620da2013-08-19 13:14:297768 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277769
7770 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497771 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277772
[email protected]ba2f3342009-07-30 18:08:427773 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277774 EXPECT_EQ(1, d.response_started_count());
7775 EXPECT_FALSE(d.received_data_before_response());
7776 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:197777 EXPECT_EQ(test_server_.host_port_pair().host(),
7778 r.GetSocketAddress().host());
7779 EXPECT_EQ(test_server_.host_port_pair().port(),
7780 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:277781 }
7782}
7783
[email protected]e9ecbd12009-12-20 18:44:407784// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127785TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:117786 ASSERT_TRUE(test_server_.Start());
7787
[email protected]6cdfd7f2013-02-08 20:40:157788 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277789 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027790 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277791 TestDelegate d;
7792 {
[email protected]ef2bf422012-05-11 03:27:097793 URLRequest r(
[email protected]95409e12010-08-17 20:07:117794 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]2ca01e52013-10-31 22:05:197795 DEFAULT_PRIORITY,
[email protected]94e2bbe2012-06-22 15:26:137796 &d,
7797 &default_context_);
[email protected]dd265012009-01-08 20:45:277798 r.Start();
7799 EXPECT_TRUE(r.is_pending());
7800
[email protected]255620da2013-08-19 13:14:297801 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277802
7803 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497804 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277805
[email protected]ba2f3342009-07-30 18:08:427806 EXPECT_FALSE(r.is_pending());
[email protected]6d81b482011-02-22 19:47:197807 EXPECT_EQ(test_server_.host_port_pair().host(),
7808 r.GetSocketAddress().host());
7809 EXPECT_EQ(test_server_.host_port_pair().port(),
7810 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:277811 EXPECT_EQ(1, d.response_started_count());
7812 EXPECT_FALSE(d.received_data_before_response());
7813 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:257814
7815 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:177816 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257817 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:277818 }
7819}
7820
[email protected]49abd652010-08-05 05:04:537821// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127822TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:117823 ASSERT_TRUE(test_server_.Start());
7824
[email protected]6cdfd7f2013-02-08 20:40:157825 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277826 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027827 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277828 TestDelegate d;
7829 {
[email protected]2ca01e52013-10-31 22:05:197830 URLRequest r(test_server_.GetURLWithUserAndPassword(
7831 "/LICENSE", "chrome", "wrong_password"),
7832 DEFAULT_PRIORITY,
7833 &d,
7834 &default_context_);
[email protected]dd265012009-01-08 20:45:277835 r.Start();
7836 EXPECT_TRUE(r.is_pending());
7837
[email protected]255620da2013-08-19 13:14:297838 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277839
7840 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497841 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277842
[email protected]ba2f3342009-07-30 18:08:427843 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277844 EXPECT_EQ(1, d.response_started_count());
7845 EXPECT_FALSE(d.received_data_before_response());
7846 EXPECT_EQ(d.bytes_received(), 0);
7847 }
7848}
7849
[email protected]cde4e80d2009-10-16 19:58:157850// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127851TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:117852 ASSERT_TRUE(test_server_.Start());
7853
[email protected]6cdfd7f2013-02-08 20:40:157854 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:587855 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7856 app_path = app_path.AppendASCII("LICENSE");
7857 TestDelegate d;
7858 // Set correct login credentials. The delegate will be asked for them when
7859 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587860 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:587861 {
[email protected]2ca01e52013-10-31 22:05:197862 URLRequest r(test_server_.GetURLWithUserAndPassword(
7863 "/LICENSE", "chrome", "wrong_password"),
7864 DEFAULT_PRIORITY,
7865 &d,
7866 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:587867 r.Start();
7868 EXPECT_TRUE(r.is_pending());
7869
[email protected]255620da2013-08-19 13:14:297870 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:587871
7872 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497873 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:587874
7875 EXPECT_FALSE(r.is_pending());
7876 EXPECT_EQ(1, d.response_started_count());
7877 EXPECT_FALSE(d.received_data_before_response());
7878 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7879 }
7880}
7881
[email protected]49abd652010-08-05 05:04:537882// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127883TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:117884 ASSERT_TRUE(test_server_.Start());
7885
[email protected]6cdfd7f2013-02-08 20:40:157886 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:277887 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:027888 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:277889 TestDelegate d;
7890 {
[email protected]2ca01e52013-10-31 22:05:197891 URLRequest r(test_server_.GetURLWithUserAndPassword(
7892 "/LICENSE", "wrong_user", "chrome"),
7893 DEFAULT_PRIORITY,
7894 &d,
7895 &default_context_);
[email protected]dd265012009-01-08 20:45:277896 r.Start();
7897 EXPECT_TRUE(r.is_pending());
7898
[email protected]255620da2013-08-19 13:14:297899 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:277900
7901 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497902 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:277903
[email protected]ba2f3342009-07-30 18:08:427904 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:277905 EXPECT_EQ(1, d.response_started_count());
7906 EXPECT_FALSE(d.received_data_before_response());
7907 EXPECT_EQ(d.bytes_received(), 0);
7908 }
7909}
[email protected]8b8a197d2009-08-26 15:57:587910
[email protected]cde4e80d2009-10-16 19:58:157911// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127912TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:117913 ASSERT_TRUE(test_server_.Start());
7914
[email protected]6cdfd7f2013-02-08 20:40:157915 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:587916 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7917 app_path = app_path.AppendASCII("LICENSE");
7918 TestDelegate d;
7919 // Set correct login credentials. The delegate will be asked for them when
7920 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:587921 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:587922 {
[email protected]2ca01e52013-10-31 22:05:197923 URLRequest r(test_server_.GetURLWithUserAndPassword(
7924 "/LICENSE", "wrong_user", "chrome"),
7925 DEFAULT_PRIORITY,
7926 &d,
7927 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:587928 r.Start();
7929 EXPECT_TRUE(r.is_pending());
7930
[email protected]255620da2013-08-19 13:14:297931 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:587932
7933 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497934 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:587935
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}
[email protected]60a3df52009-09-22 16:13:247942
[email protected]cde4e80d2009-10-16 19:58:157943// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127944TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:117945 ASSERT_TRUE(test_server_.Start());
7946
[email protected]6cdfd7f2013-02-08 20:40:157947 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:247948 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7949 app_path = app_path.AppendASCII("LICENSE");
7950
7951 scoped_ptr<TestDelegate> d(new TestDelegate);
7952 {
7953 // Pass correct login identity in the URL.
[email protected]ef2bf422012-05-11 03:27:097954 URLRequest r(
[email protected]2ca01e52013-10-31 22:05:197955 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7956 DEFAULT_PRIORITY,
[email protected]94e2bbe2012-06-22 15:26:137957 d.get(),
7958 &default_context_);
[email protected]60a3df52009-09-22 16:13:247959 r.Start();
7960 EXPECT_TRUE(r.is_pending());
7961
[email protected]255620da2013-08-19 13:14:297962 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247963
7964 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497965 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247966
7967 EXPECT_FALSE(r.is_pending());
7968 EXPECT_EQ(1, d->response_started_count());
7969 EXPECT_FALSE(d->received_data_before_response());
7970 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7971 }
7972
7973 d.reset(new TestDelegate);
7974 {
7975 // This request should use cached identity from previous request.
[email protected]2ca01e52013-10-31 22:05:197976 URLRequest r(test_server_.GetURL("/LICENSE"),
7977 DEFAULT_PRIORITY,
7978 d.get(),
7979 &default_context_);
[email protected]60a3df52009-09-22 16:13:247980 r.Start();
7981 EXPECT_TRUE(r.is_pending());
7982
[email protected]255620da2013-08-19 13:14:297983 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247984
7985 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:497986 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:247987
7988 EXPECT_FALSE(r.is_pending());
7989 EXPECT_EQ(1, d->response_started_count());
7990 EXPECT_FALSE(d->received_data_before_response());
7991 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7992 }
7993}
7994
[email protected]cde4e80d2009-10-16 19:58:157995// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:127996TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:117997 ASSERT_TRUE(test_server_.Start());
7998
[email protected]6cdfd7f2013-02-08 20:40:157999 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248000 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8001 app_path = app_path.AppendASCII("LICENSE");
8002
8003 scoped_ptr<TestDelegate> d(new TestDelegate);
8004 // Set correct login credentials. The delegate will be asked for them when
8005 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588006 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:248007 {
[email protected]2ca01e52013-10-31 22:05:198008 URLRequest r(test_server_.GetURLWithUserAndPassword(
8009 "/LICENSE", "chrome", "wrong_password"),
8010 DEFAULT_PRIORITY,
8011 d.get(),
8012 &default_context_);
[email protected]60a3df52009-09-22 16:13:248013 r.Start();
8014 EXPECT_TRUE(r.is_pending());
8015
[email protected]255620da2013-08-19 13:14:298016 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248017
8018 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498019 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248020
8021 EXPECT_FALSE(r.is_pending());
8022 EXPECT_EQ(1, d->response_started_count());
8023 EXPECT_FALSE(d->received_data_before_response());
8024 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8025 }
8026
8027 // Use a new delegate without explicit credentials. The cached ones should be
8028 // used.
8029 d.reset(new TestDelegate);
8030 {
8031 // Don't pass wrong credentials in the URL, they would override valid cached
8032 // ones.
[email protected]2ca01e52013-10-31 22:05:198033 URLRequest r(test_server_.GetURL("/LICENSE"),
8034 DEFAULT_PRIORITY,
8035 d.get(),
8036 &default_context_);
[email protected]60a3df52009-09-22 16:13:248037 r.Start();
8038 EXPECT_TRUE(r.is_pending());
8039
[email protected]255620da2013-08-19 13:14:298040 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248041
8042 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498043 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248044
8045 EXPECT_FALSE(r.is_pending());
8046 EXPECT_EQ(1, d->response_started_count());
8047 EXPECT_FALSE(d->received_data_before_response());
8048 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8049 }
8050}
[email protected]316c1e5e2012-09-12 15:17:448051#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:518052
8053} // namespace net