blob: 158618fd8b4129730ad4ca3f30357abee16dc341 [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
tbansalea2fb8c2015-05-22 22:23:0012#include <stdint.h>
13
initial.commit586acc5fe2008-07-26 22:42:5214#include <algorithm>
initial.commit586acc5fe2008-07-26 22:42:5215
[email protected]aad63572011-05-24 20:14:3916#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3817#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5818#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4719#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2920#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0721#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2822#include "base/format_macros.h"
mmenke19378d22014-09-09 04:12:5923#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4724#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2225#include "base/message_loop/message_loop.h"
[email protected]255620da2013-08-19 13:14:2926#include "base/message_loop/message_loop_proxy.h"
initial.commit586acc5fe2008-07-26 22:42:5227#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2928#include "base/run_loop.h"
[email protected]4dc3ad4f2013-06-11 07:15:5029#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5530#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2231#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2232#include "base/strings/string_util.h"
33#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0534#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0035#include "base/test/histogram_tester.h"
mmenkecbc2b712014-10-09 20:29:0736#include "net/base/chunked_upload_data_stream.h"
37#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5238#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2539#include "net/base/load_timing_info.h"
40#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0641#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5242#include "net/base/net_module.h"
43#include "net/base/net_util.h"
tbansalea2fb8c2015-05-22 22:23:0044#include "net/base/network_quality.h"
45#include "net/base/network_quality_estimator.h"
[email protected]2ca01e52013-10-31 22:05:1946#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4047#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2848#include "net/base/upload_bytes_element_reader.h"
49#include "net/base/upload_data_stream.h"
50#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1151#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2452#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1153#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4954#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0655#include "net/cookies/cookie_monster.h"
56#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5257#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5358#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3859#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5260#include "net/http/http_cache.h"
61#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1962#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2563#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2164#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0065#include "net/http/http_util.h"
eroman87c53d62015-04-02 06:51:0766#include "net/log/net_log.h"
vishal.b62985ca92015-04-17 08:45:5167#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4668#include "net/log/test_net_log_entry.h"
69#include "net/log/test_net_log_util.h"
[email protected]63de95b2008-12-10 04:11:2770#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1971#include "net/socket/ssl_client_socket.h"
davidben8ecc3072014-09-03 23:19:0972#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5773#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1174#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2175#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3476#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4377#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5278#include "net/url_request/url_request.h"
[email protected]bcb84f8b2009-08-31 16:20:1479#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5080#include "net/url_request/url_request_intercepting_job_factory.h"
81#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4982#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5183#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4784#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4485#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5286#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1587#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5288
[email protected]02494ec2014-05-07 15:05:2989#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:5590#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:2991#include "net/url_request/file_protocol_handler.h"
92#include "net/url_request/url_request_file_dir_job.h"
93#endif
94
mmenke9f2ec60c2015-06-01 20:59:4795#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
96#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:2997#include "net/url_request/ftp_protocol_handler.h"
98#endif
99
[email protected]dffe8242012-03-20 15:14:27100#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48101#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56102#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27103#include "base/win/windows_version.h"
104#endif
105
[email protected]ad65a3e2013-12-25 18:18:01106using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33107using base::Time;
halton.huoe4e45742014-12-08 07:55:46108using std::string;
[email protected]e1acf6f2008-10-27 20:43:33109
[email protected]7461a402011-03-24 23:19:51110namespace net {
111
initial.commit586acc5fe2008-07-26 22:42:52112namespace {
113
[email protected]42cba2fb2013-03-29 19:58:57114const base::string16 kChrome(ASCIIToUTF16("chrome"));
115const base::string16 kSecret(ASCIIToUTF16("secret"));
116const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44117
mmenke9f2ec60c2015-06-01 20:59:47118const base::FilePath::CharType kTestFilePath[] =
119 FILE_PATH_LITERAL("net/data/url_request_unittest");
120
121#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
122// Test file used in most FTP tests.
123const char kFtpTestFile[] = "BullRunSpeech.txt";
124#endif
125
[email protected]2bba3252013-04-08 19:50:59126// Tests load timing information in the case a fresh connection was used, with
127// no proxy.
[email protected]cba24642014-08-15 20:49:59128void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25129 int connect_timing_flags) {
130 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59131 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25132
133 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
134 EXPECT_FALSE(load_timing_info.request_start.is_null());
135
136 EXPECT_LE(load_timing_info.request_start,
137 load_timing_info.connect_timing.connect_start);
138 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
139 connect_timing_flags);
140 EXPECT_LE(load_timing_info.connect_timing.connect_end,
141 load_timing_info.send_start);
142 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
143 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
144
[email protected]58e32bb2013-01-21 18:23:25145 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
146 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
147}
148
[email protected]2bba3252013-04-08 19:50:59149// Same as above, but with proxy times.
150void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59151 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59152 int connect_timing_flags) {
153 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59154 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59155
156 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
157 EXPECT_FALSE(load_timing_info.request_start.is_null());
158
159 EXPECT_LE(load_timing_info.request_start,
160 load_timing_info.proxy_resolve_start);
161 EXPECT_LE(load_timing_info.proxy_resolve_start,
162 load_timing_info.proxy_resolve_end);
163 EXPECT_LE(load_timing_info.proxy_resolve_end,
164 load_timing_info.connect_timing.connect_start);
165 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
166 connect_timing_flags);
167 EXPECT_LE(load_timing_info.connect_timing.connect_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
173// Same as above, but with a reused socket and proxy times.
174void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59175 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59176 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59177 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59178
179 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
180 EXPECT_FALSE(load_timing_info.request_start.is_null());
181
182 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
183
184 EXPECT_LE(load_timing_info.request_start,
185 load_timing_info.proxy_resolve_start);
186 EXPECT_LE(load_timing_info.proxy_resolve_start,
187 load_timing_info.proxy_resolve_end);
188 EXPECT_LE(load_timing_info.proxy_resolve_end,
189 load_timing_info.send_start);
190 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
191 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
192}
193
xunjielia6888202015-04-14 21:34:25194#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25195// Tests load timing information in the case of a cache hit, when no cache
196// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17197base::StringPiece TestNetResourceProvider(int key) {
198 return "header";
199}
200
201void FillBuffer(char* buffer, size_t len) {
202 static bool called = false;
203 if (!called) {
204 called = true;
205 int seed = static_cast<int>(Time::Now().ToInternalValue());
206 srand(seed);
207 }
208
209 for (size_t i = 0; i < len; i++) {
210 buffer[i] = static_cast<char>(rand());
211 if (!buffer[i])
212 buffer[i] = 'g';
213 }
214}
xunjielia6888202015-04-14 21:34:25215#endif
[email protected]e3a85452013-11-14 01:46:17216
217#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25218void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59219 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25220 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59221 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25222
223 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
224 EXPECT_FALSE(load_timing_info.request_start.is_null());
225
226 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
227 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
228 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
229 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
230
231 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
232 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
233}
234
mmenke9f2ec60c2015-06-01 20:59:47235#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25236// Tests load timing in the case that there is no HTTP response. This can be
237// used to test in the case of errors or non-HTTP requests.
238void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59239 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25240 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59241 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25242
243 // Only the request times should be non-null.
244 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
245 EXPECT_FALSE(load_timing_info.request_start.is_null());
246
247 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
248
249 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
250 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
251 EXPECT_TRUE(load_timing_info.send_start.is_null());
252 EXPECT_TRUE(load_timing_info.send_end.is_null());
253 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
254}
xunjielia6888202015-04-14 21:34:25255#endif
[email protected]58e32bb2013-01-21 18:23:25256
[email protected]71c64f62008-11-15 04:36:51257// Do a case-insensitive search through |haystack| for |needle|.
258bool ContainsString(const std::string& haystack, const char* needle) {
259 std::string::const_iterator it =
260 std::search(haystack.begin(),
261 haystack.end(),
262 needle,
263 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35264 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51265 return it != haystack.end();
266}
267
mmenkecbc2b712014-10-09 20:29:07268scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28269 scoped_ptr<UploadElementReader> reader(
270 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07271 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23272}
273
[email protected]96adadb2010-08-28 01:16:17274// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51275void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17276 // -1 means unknown. 0 means no encryption.
277 EXPECT_GT(ssl_info.security_bits, 0);
278
279 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29280 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17281 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29282 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17283}
284
[email protected]79e1fd62013-06-20 06:50:04285void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
286 const GURL& host_url) {
287 std::string sent_value;
288
289 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
290 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
291
292 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
293 EXPECT_EQ("keep-alive", sent_value);
294}
295
[email protected]ede03212012-09-07 12:52:26296bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27297 size_t size = a.size();
298
299 if (size != b.size())
300 return false;
301
302 for (size_t i = 0; i < size; ++i) {
303 if (!a[i].Equals(b[i]))
304 return false;
305 }
306
307 return true;
308}
[email protected]e3a85452013-11-14 01:46:17309#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27310
[email protected]dc5a5cf2012-09-26 02:49:30311// A network delegate that allows the user to choose a subset of request stages
312// to block in. When blocking, the delegate can do one of the following:
313// * synchronously return a pre-specified error code, or
314// * asynchronously return that value via an automatically called callback,
315// or
316// * block and wait for the user to do a callback.
317// Additionally, the user may also specify a redirect URL -- then each request
318// with the current URL different from the redirect target will be redirected
319// to that target, in the on-before-URL-request stage, independent of whether
320// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12321class BlockingNetworkDelegate : public TestNetworkDelegate {
322 public:
[email protected]dc5a5cf2012-09-26 02:49:30323 // Stages in which the delegate can block.
324 enum Stage {
[email protected]9045b8822012-01-13 20:35:35325 NOT_BLOCKED = 0,
326 ON_BEFORE_URL_REQUEST = 1 << 0,
327 ON_BEFORE_SEND_HEADERS = 1 << 1,
328 ON_HEADERS_RECEIVED = 1 << 2,
329 ON_AUTH_REQUIRED = 1 << 3
330 };
331
[email protected]dc5a5cf2012-09-26 02:49:30332 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59333 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30334 enum BlockMode {
335 SYNCHRONOUS, // No callback, returns specified return values.
336 AUTO_CALLBACK, // |this| posts a task to run the callback using the
337 // specified return codes.
338 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
339 // |auth_retval_| are ignored. In every blocking stage the
340 // message loop is quit.
341 };
342
343 // Creates a delegate which does not block at all.
344 explicit BlockingNetworkDelegate(BlockMode block_mode);
345
346 // For users to trigger a callback returning |response|.
347 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
348 // Only call if |block_mode_| == USER_CALLBACK.
349 void DoCallback(int response);
350 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
351
352 // Setters.
353 void set_retval(int retval) {
354 ASSERT_NE(USER_CALLBACK, block_mode_);
355 ASSERT_NE(ERR_IO_PENDING, retval);
356 ASSERT_NE(OK, retval);
357 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35358 }
359
[email protected]dc5a5cf2012-09-26 02:49:30360 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
361 // |auth_credentials_| will be passed with the response.
362 void set_auth_retval(AuthRequiredResponse auth_retval) {
363 ASSERT_NE(USER_CALLBACK, block_mode_);
364 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
365 auth_retval_ = auth_retval;
366 }
367 void set_auth_credentials(const AuthCredentials& auth_credentials) {
368 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35369 }
370
[email protected]dc5a5cf2012-09-26 02:49:30371 void set_redirect_url(const GURL& url) {
372 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35373 }
374
[email protected]dc5a5cf2012-09-26 02:49:30375 void set_block_on(int block_on) {
376 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35377 }
378
[email protected]dc5a5cf2012-09-26 02:49:30379 // Allows the user to check in which state did we block.
380 Stage stage_blocked_for_callback() const {
381 EXPECT_EQ(USER_CALLBACK, block_mode_);
382 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35383 }
384
385 private:
[email protected]dc5a5cf2012-09-26 02:49:30386 void RunCallback(int response, const CompletionCallback& callback);
387 void RunAuthCallback(AuthRequiredResponse response,
388 const AuthCallback& callback);
389
[email protected]9045b8822012-01-13 20:35:35390 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20391 int OnBeforeURLRequest(URLRequest* request,
392 const CompletionCallback& callback,
393 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35394
dchengb03027d2014-10-21 12:00:20395 int OnBeforeSendHeaders(URLRequest* request,
396 const CompletionCallback& callback,
397 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35398
dchengb03027d2014-10-21 12:00:20399 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35400 URLRequest* request,
401 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32402 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16403 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13404 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35405
dchengb03027d2014-10-21 12:00:20406 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35407 URLRequest* request,
408 const AuthChallengeInfo& auth_info,
409 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13410 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35411
[email protected]dc5a5cf2012-09-26 02:49:30412 // Resets the callbacks and |stage_blocked_for_callback_|.
413 void Reset();
[email protected]9045b8822012-01-13 20:35:35414
[email protected]dc5a5cf2012-09-26 02:49:30415 // Checks whether we should block in |stage|. If yes, returns an error code
416 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
417 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
418
419 // Configuration parameters, can be adjusted by public methods:
420 const BlockMode block_mode_;
421
422 // Values returned on blocking stages when mode is SYNCHRONOUS or
423 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
424 int retval_; // To be returned in non-auth stages.
425 AuthRequiredResponse auth_retval_;
426
[email protected]5f714132014-03-26 10:41:16427 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30428 int block_on_; // Bit mask: in which stages to block.
429
430 // |auth_credentials_| will be copied to |*target_auth_credential_| on
431 // callback.
432 AuthCredentials auth_credentials_;
433 AuthCredentials* target_auth_credentials_;
434
435 // Internal variables, not set by not the user:
436 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
437 // USER_CALLBACK).
438 Stage stage_blocked_for_callback_;
439
440 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35441 CompletionCallback callback_;
442 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30443
444 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
445
446 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35447};
448
[email protected]dc5a5cf2012-09-26 02:49:30449BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
450 : block_mode_(block_mode),
451 retval_(OK),
452 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
453 block_on_(0),
454 target_auth_credentials_(NULL),
455 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32456 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30457}
458
459void BlockingNetworkDelegate::DoCallback(int response) {
460 ASSERT_EQ(USER_CALLBACK, block_mode_);
461 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
462 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
463 CompletionCallback callback = callback_;
464 Reset();
465 RunCallback(response, callback);
466}
467
468void BlockingNetworkDelegate::DoAuthCallback(
469 NetworkDelegate::AuthRequiredResponse response) {
470 ASSERT_EQ(USER_CALLBACK, block_mode_);
471 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
472 AuthCallback auth_callback = auth_callback_;
473 Reset();
474 RunAuthCallback(response, auth_callback);
475}
476
477void BlockingNetworkDelegate::RunCallback(int response,
478 const CompletionCallback& callback) {
479 callback.Run(response);
480}
481
482void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
483 const AuthCallback& callback) {
484 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
485 ASSERT_TRUE(target_auth_credentials_ != NULL);
486 *target_auth_credentials_ = auth_credentials_;
487 }
488 callback.Run(response);
489}
490
491int BlockingNetworkDelegate::OnBeforeURLRequest(
492 URLRequest* request,
493 const CompletionCallback& callback,
494 GURL* new_url) {
495 if (redirect_url_ == request->url())
496 return OK; // We've already seen this request and redirected elsewhere.
497
498 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
499
500 if (!redirect_url_.is_empty())
501 *new_url = redirect_url_;
502
503 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
504}
505
506int BlockingNetworkDelegate::OnBeforeSendHeaders(
507 URLRequest* request,
508 const CompletionCallback& callback,
509 HttpRequestHeaders* headers) {
510 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
511
512 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
513}
514
515int BlockingNetworkDelegate::OnHeadersReceived(
516 URLRequest* request,
517 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32518 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16519 scoped_refptr<HttpResponseHeaders>* override_response_headers,
520 GURL* allowed_unsafe_redirect_url) {
521 TestNetworkDelegate::OnHeadersReceived(request,
522 callback,
523 original_response_headers,
524 override_response_headers,
525 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30526
527 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
528}
529
530NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
531 URLRequest* request,
532 const AuthChallengeInfo& auth_info,
533 const AuthCallback& callback,
534 AuthCredentials* credentials) {
535 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
536 credentials);
537 // Check that the user has provided callback for the previous blocked stage.
538 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
539
540 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
541 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
542 }
543
544 target_auth_credentials_ = credentials;
545
546 switch (block_mode_) {
547 case SYNCHRONOUS:
548 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
549 *target_auth_credentials_ = auth_credentials_;
550 return auth_retval_;
551
552 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34553 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30554 FROM_HERE,
555 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
556 weak_factory_.GetWeakPtr(), auth_retval_, callback));
557 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
558
559 case USER_CALLBACK:
560 auth_callback_ = callback;
561 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34562 base::MessageLoop::current()->PostTask(FROM_HERE,
563 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30564 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
565 }
566 NOTREACHED();
567 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
568}
569
570void BlockingNetworkDelegate::Reset() {
571 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
572 stage_blocked_for_callback_ = NOT_BLOCKED;
573 callback_.Reset();
574 auth_callback_.Reset();
575}
576
577int BlockingNetworkDelegate::MaybeBlockStage(
578 BlockingNetworkDelegate::Stage stage,
579 const CompletionCallback& callback) {
580 // Check that the user has provided callback for the previous blocked stage.
581 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
582
583 if ((block_on_ & stage) == 0) {
584 return OK;
585 }
586
587 switch (block_mode_) {
588 case SYNCHRONOUS:
589 EXPECT_NE(OK, retval_);
590 return retval_;
591
592 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34593 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30594 FROM_HERE,
595 base::Bind(&BlockingNetworkDelegate::RunCallback,
596 weak_factory_.GetWeakPtr(), retval_, callback));
597 return ERR_IO_PENDING;
598
599 case USER_CALLBACK:
600 callback_ = callback;
601 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34602 base::MessageLoop::current()->PostTask(FROM_HERE,
603 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30604 return ERR_IO_PENDING;
605 }
606 NOTREACHED();
607 return 0;
608}
609
[email protected]d5a4dd62012-05-23 01:41:04610class TestURLRequestContextWithProxy : public TestURLRequestContext {
611 public:
612 // Does not own |delegate|.
613 TestURLRequestContextWithProxy(const std::string& proxy,
614 NetworkDelegate* delegate)
615 : TestURLRequestContext(true) {
616 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
617 set_network_delegate(delegate);
618 Init();
619 }
dchengb03027d2014-10-21 12:00:20620 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04621};
622
623} // namespace
624
[email protected]a592c0432012-12-01 18:10:29625// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48626class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00627 public:
[email protected]ef2bf422012-05-11 03:27:09628 URLRequestTest() : default_context_(true) {
629 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25630 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50631 job_factory_impl_ = new URLRequestJobFactoryImpl();
632 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50633 }
bengr1bf8e942014-11-07 01:36:50634
dcheng67be2b1f2014-10-27 21:47:29635 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18636 // URLRequestJobs may post clean-up tasks on destruction.
637 base::RunLoop().RunUntilIdle();
638 }
[email protected]87a09a92011-07-14 15:50:50639
dcheng2339883c2014-12-23 00:23:05640 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50641 SetUpFactory();
642 default_context_.set_job_factory(job_factory_.get());
643 default_context_.Init();
644 PlatformTest::SetUp();
645 }
646
647 virtual void SetUpFactory() {
648 job_factory_impl_->SetProtocolHandler("data", new DataProtocolHandler);
649#if !defined(DISABLE_FILE_SUPPORT)
650 job_factory_impl_->SetProtocolHandler(
651 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
652#endif
653 }
654
655 TestNetworkDelegate* default_network_delegate() {
656 return &default_network_delegate_;
657 }
658
659 const TestURLRequestContext& default_context() const {
660 return default_context_;
661 }
662
663
[email protected]3c5ca8c2011-09-29 01:14:51664 // Adds the TestJobInterceptor to the default context.
665 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23666 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
bengr1bf8e942014-11-07 01:36:50667 job_factory_impl_->SetProtocolHandler("http", NULL);
668 job_factory_impl_->SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23669 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51670 }
671
[email protected]87a09a92011-07-14 15:50:50672 protected:
vishal.b62985ca92015-04-17 08:45:51673 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24674 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50675 URLRequestJobFactoryImpl* job_factory_impl_;
676 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09677 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48678};
679
[email protected]316c1e5e2012-09-12 15:17:44680TEST_F(URLRequestTest, AboutBlankTest) {
681 TestDelegate d;
682 {
[email protected]f7022f32014-08-21 16:32:19683 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36684 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44685
[email protected]f7022f32014-08-21 16:32:19686 r->Start();
687 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44688
[email protected]255620da2013-08-19 13:14:29689 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44690
[email protected]f7022f32014-08-21 16:32:19691 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44692 EXPECT_FALSE(d.received_data_before_response());
693 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19694 EXPECT_EQ("", r->GetSocketAddress().host());
695 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04696
697 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19698 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44699 }
700}
701
702TEST_F(URLRequestTest, DataURLImageTest) {
703 TestDelegate d;
704 {
705 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19706 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19707 GURL(
davidben151423e2015-03-23 18:48:36708 "data:image/png;base64,"
709 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
710 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
711 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
712 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
713 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
714 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
715 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
716 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
717 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
718 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
719 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
720 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
721 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
722 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
723 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
724 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
725 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
726 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
727 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
728 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44729
[email protected]f7022f32014-08-21 16:32:19730 r->Start();
731 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44732
[email protected]255620da2013-08-19 13:14:29733 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44734
[email protected]f7022f32014-08-21 16:32:19735 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44736 EXPECT_FALSE(d.received_data_before_response());
737 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19738 EXPECT_EQ("", r->GetSocketAddress().host());
739 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04740
741 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19742 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44743 }
744}
745
[email protected]5ecf7cb282014-05-11 01:49:55746#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44747TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15748 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44749 PathService::Get(base::FILE_EXE, &app_path);
750 GURL app_url = FilePathToFileURL(app_path);
751
752 TestDelegate d;
753 {
davidben151423e2015-03-23 18:48:36754 scoped_ptr<URLRequest> r(
755 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44756
[email protected]f7022f32014-08-21 16:32:19757 r->Start();
758 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44759
[email protected]255620da2013-08-19 13:14:29760 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44761
762 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49763 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44764
[email protected]f7022f32014-08-21 16:32:19765 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44766 EXPECT_EQ(1, d.response_started_count());
767 EXPECT_FALSE(d.received_data_before_response());
768 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19769 EXPECT_EQ("", r->GetSocketAddress().host());
770 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04771
772 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19773 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44774 }
775}
776
[email protected]ba40bb762012-12-17 07:11:04777TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15778 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04779 PathService::Get(base::FILE_EXE, &app_path);
780 GURL app_url = FilePathToFileURL(app_path);
781
782 TestDelegate d;
783 {
davidben151423e2015-03-23 18:48:36784 scoped_ptr<URLRequest> r(
785 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04786
[email protected]f7022f32014-08-21 16:32:19787 r->Start();
788 EXPECT_TRUE(r->is_pending());
789 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04790 }
[email protected]79e1fd62013-06-20 06:50:04791 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04792 // destroyed.
[email protected]255620da2013-08-19 13:14:29793 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04794}
795
[email protected]316c1e5e2012-09-12 15:17:44796TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
797 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17798 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44799 FillBuffer(buffer.get(), buffer_size);
800
[email protected]6cdfd7f2013-02-08 20:40:15801 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52802 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44803 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30804 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44805
806 int64 file_size;
[email protected]56285702013-12-04 18:22:49807 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44808
809 const size_t first_byte_position = 500;
810 const size_t last_byte_position = buffer_size - first_byte_position;
811 const size_t content_length = last_byte_position - first_byte_position + 1;
812 std::string partial_buffer_string(buffer.get() + first_byte_position,
813 buffer.get() + last_byte_position + 1);
814
815 TestDelegate d;
816 {
davidben151423e2015-03-23 18:48:36817 scoped_ptr<URLRequest> r(
818 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44819
820 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38821 headers.SetHeader(
822 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59823 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38824 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19825 r->SetExtraRequestHeaders(headers);
826 r->Start();
827 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44828
[email protected]255620da2013-08-19 13:14:29829 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19830 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44831 EXPECT_EQ(1, d.response_started_count());
832 EXPECT_FALSE(d.received_data_before_response());
833 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
834 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
835 EXPECT_TRUE(partial_buffer_string == d.data_received());
836 }
837
[email protected]dd3aa792013-07-16 19:10:23838 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44839}
840
841TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
842 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17843 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44844 FillBuffer(buffer.get(), buffer_size);
845
[email protected]6cdfd7f2013-02-08 20:40:15846 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52847 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44848 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30849 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44850
851 int64 file_size;
[email protected]56285702013-12-04 18:22:49852 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44853
854 const size_t first_byte_position = 500;
855 const size_t last_byte_position = buffer_size - 1;
856 const size_t content_length = last_byte_position - first_byte_position + 1;
857 std::string partial_buffer_string(buffer.get() + first_byte_position,
858 buffer.get() + last_byte_position + 1);
859
860 TestDelegate d;
861 {
davidben151423e2015-03-23 18:48:36862 scoped_ptr<URLRequest> r(
863 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44864
865 HttpRequestHeaders headers;
866 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59867 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38868 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19869 r->SetExtraRequestHeaders(headers);
870 r->Start();
871 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44872
[email protected]255620da2013-08-19 13:14:29873 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19874 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44875 EXPECT_EQ(1, d.response_started_count());
876 EXPECT_FALSE(d.received_data_before_response());
877 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
878 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
879 EXPECT_TRUE(partial_buffer_string == d.data_received());
880 }
881
[email protected]dd3aa792013-07-16 19:10:23882 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44883}
884
885TEST_F(URLRequestTest, FileTestMultipleRanges) {
886 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17887 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44888 FillBuffer(buffer.get(), buffer_size);
889
[email protected]6cdfd7f2013-02-08 20:40:15890 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52891 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44892 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30893 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44894
895 int64 file_size;
[email protected]56285702013-12-04 18:22:49896 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44897
898 TestDelegate d;
899 {
davidben151423e2015-03-23 18:48:36900 scoped_ptr<URLRequest> r(
901 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44902
903 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38904 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19905 r->SetExtraRequestHeaders(headers);
906 r->Start();
907 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44908
[email protected]255620da2013-08-19 13:14:29909 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44910 EXPECT_TRUE(d.request_failed());
911 }
912
[email protected]dd3aa792013-07-16 19:10:23913 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44914}
915
[email protected]3ca8b362013-11-11 22:18:07916TEST_F(URLRequestTest, AllowFileURLs) {
917 base::ScopedTempDir temp_dir;
918 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
919 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52920 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07921 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30922 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59923 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07924
925 {
926 TestDelegate d;
927 TestNetworkDelegate network_delegate;
928 network_delegate.set_can_access_files(true);
929 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36930 scoped_ptr<URLRequest> r(
931 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19932 r->Start();
[email protected]3ca8b362013-11-11 22:18:07933 base::RunLoop().Run();
934 EXPECT_FALSE(d.request_failed());
935 EXPECT_EQ(test_data, d.data_received());
936 }
937
938 {
939 TestDelegate d;
940 TestNetworkDelegate network_delegate;
941 network_delegate.set_can_access_files(false);
942 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36943 scoped_ptr<URLRequest> r(
944 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19945 r->Start();
[email protected]3ca8b362013-11-11 22:18:07946 base::RunLoop().Run();
947 EXPECT_TRUE(d.request_failed());
948 EXPECT_EQ("", d.data_received());
949 }
950}
951
[email protected]316c1e5e2012-09-12 15:17:44952
953TEST_F(URLRequestTest, FileDirCancelTest) {
954 // Put in mock resource provider.
955 NetModule::SetResourceProvider(TestNetResourceProvider);
956
957 TestDelegate d;
958 {
[email protected]6cdfd7f2013-02-08 20:40:15959 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44960 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
961 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
962 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
963
[email protected]f7022f32014-08-21 16:32:19964 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36965 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19966 req->Start();
967 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44968
969 d.set_cancel_in_received_data_pending(true);
970
[email protected]255620da2013-08-19 13:14:29971 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44972 }
973
974 // Take out mock resource provider.
975 NetModule::SetResourceProvider(NULL);
976}
977
[email protected]5f9581402013-10-30 13:08:32978TEST_F(URLRequestTest, FileDirOutputSanity) {
979 // Verify the general sanity of the the output of the file:
980 // directory lister by checking for the output of a known existing
981 // file.
982 const char sentinel_name[] = "filedir-sentinel";
983
984 base::FilePath path;
985 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:47986 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:32987
988 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:19989 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36990 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19991 req->Start();
[email protected]5f9581402013-10-30 13:08:32992 base::RunLoop().Run();
993
994 // Generate entry for the sentinel file.
995 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:58996 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:49997 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:32998 EXPECT_GT(info.size, 0);
999 std::string sentinel_output = GetDirectoryListingEntry(
1000 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1001 std::string(sentinel_name),
1002 false /* is_dir */,
1003 info.size,
1004 info.last_modified);
1005
1006 ASSERT_LT(0, d.bytes_received());
1007 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191008 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321009 // Check for the entry generated for the "sentinel" file.
1010 const std::string& data = d.data_received();
1011 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1012}
1013
[email protected]316c1e5e2012-09-12 15:17:441014TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1015 // There is an implicit redirect when loading a file path that matches a
1016 // directory and does not end with a slash. Ensure that following such
1017 // redirects does not crash. See http://crbug.com/18686.
1018
[email protected]6cdfd7f2013-02-08 20:40:151019 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441020 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471021 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441022
1023 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191024 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361025 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191026 req->Start();
[email protected]255620da2013-08-19 13:14:291027 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441028
1029 ASSERT_EQ(1, d.received_redirect_count());
1030 ASSERT_LT(0, d.bytes_received());
1031 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191032 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441033}
1034
1035#if defined(OS_WIN)
1036// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1037TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1038 TestDelegate d;
davidben151423e2015-03-23 18:48:361039 scoped_ptr<URLRequest> req(
1040 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191041 req->Start();
[email protected]255620da2013-08-19 13:14:291042 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441043
1044 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191045 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441046}
[email protected]5ecf7cb282014-05-11 01:49:551047#endif // defined(OS_WIN)
1048
1049#endif // !defined(DISABLE_FILE_SUPPORT)
1050
1051TEST_F(URLRequestTest, InvalidUrlTest) {
1052 TestDelegate d;
1053 {
[email protected]f7022f32014-08-21 16:32:191054 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361055 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551056
[email protected]f7022f32014-08-21 16:32:191057 r->Start();
1058 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551059
1060 base::RunLoop().Run();
1061 EXPECT_TRUE(d.request_failed());
1062 }
1063}
1064
jochen0e3b3a62014-09-16 18:31:231065TEST_F(URLRequestTest, InvalidReferrerTest) {
1066 TestURLRequestContext context;
1067 TestNetworkDelegate network_delegate;
1068 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1069 context.set_network_delegate(&network_delegate);
1070 TestDelegate d;
davidben151423e2015-03-23 18:48:361071 scoped_ptr<URLRequest> req(
1072 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231073 req->SetReferrer("https://somewhere.com/");
1074
1075 req->Start();
1076 base::RunLoop().Run();
1077 EXPECT_TRUE(d.request_failed());
1078}
1079
[email protected]5ecf7cb282014-05-11 01:49:551080#if defined(OS_WIN)
1081TEST_F(URLRequestTest, ResolveShortcutTest) {
1082 base::FilePath app_path;
1083 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471084 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551085 app_path = app_path.AppendASCII("with-headers.html");
1086
1087 std::wstring lnk_path = app_path.value() + L".lnk";
1088
1089 base::win::ScopedCOMInitializer com_initializer;
1090
1091 // Temporarily create a shortcut for test
1092 {
1093 base::win::ScopedComPtr<IShellLink> shell;
1094 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1095 CLSCTX_INPROC_SERVER)));
1096 base::win::ScopedComPtr<IPersistFile> persist;
1097 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1098 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1099 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1100 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1101 }
1102
1103 TestDelegate d;
1104 {
[email protected]f7022f32014-08-21 16:32:191105 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361106 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551107
[email protected]f7022f32014-08-21 16:32:191108 r->Start();
1109 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551110
1111 base::RunLoop().Run();
1112
1113 WIN32_FILE_ATTRIBUTE_DATA data;
1114 GetFileAttributesEx(app_path.value().c_str(),
1115 GetFileExInfoStandard, &data);
1116 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1117 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1118 FILE_ATTRIBUTE_NORMAL, NULL);
1119 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1120 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1121 DWORD read_size;
1122 BOOL result;
1123 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1124 &read_size, NULL);
1125 std::string content(buffer.get(), read_size);
1126 CloseHandle(file);
1127
[email protected]f7022f32014-08-21 16:32:191128 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551129 EXPECT_EQ(1, d.received_redirect_count());
1130 EXPECT_EQ(content, d.data_received());
1131 }
1132
1133 // Clean the shortcut
1134 DeleteFile(lnk_path.c_str());
1135}
1136#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441137
1138// Custom URLRequestJobs for use with interceptor tests
1139class RestartTestJob : public URLRequestTestJob {
1140 public:
1141 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1142 : URLRequestTestJob(request, network_delegate, true) {}
1143 protected:
dchengb03027d2014-10-21 12:00:201144 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441145 private:
dchengb03027d2014-10-21 12:00:201146 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441147};
1148
1149class CancelTestJob : public URLRequestTestJob {
1150 public:
1151 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1152 : URLRequestTestJob(request, network_delegate, true) {}
1153 protected:
dchengb03027d2014-10-21 12:00:201154 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441155 private:
dchengb03027d2014-10-21 12:00:201156 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441157};
1158
1159class CancelThenRestartTestJob : public URLRequestTestJob {
1160 public:
1161 explicit CancelThenRestartTestJob(URLRequest* request,
1162 NetworkDelegate* network_delegate)
1163 : URLRequestTestJob(request, network_delegate, true) {
1164 }
1165 protected:
dchengb03027d2014-10-21 12:00:201166 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441167 request_->Cancel();
1168 this->NotifyRestartRequired();
1169 }
1170 private:
dchengb03027d2014-10-21 12:00:201171 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441172};
1173
bengr1bf8e942014-11-07 01:36:501174// An Interceptor for use with interceptor tests.
1175class MockURLRequestInterceptor : public URLRequestInterceptor {
1176 public:
1177 // Static getters for canned response header and data strings.
1178 static std::string ok_data() {
1179 return URLRequestTestJob::test_data_1();
1180 }
1181
1182 static std::string ok_headers() {
1183 return URLRequestTestJob::test_headers();
1184 }
1185
1186 static std::string redirect_data() {
1187 return std::string();
1188 }
1189
1190 static std::string redirect_headers() {
1191 return URLRequestTestJob::test_redirect_headers();
1192 }
1193
1194 static std::string error_data() {
1195 return std::string("ohhh nooooo mr. bill!");
1196 }
1197
1198 static std::string error_headers() {
1199 return URLRequestTestJob::test_error_headers();
1200 }
1201
1202 MockURLRequestInterceptor()
1203 : intercept_main_request_(false), restart_main_request_(false),
1204 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1205 simulate_main_network_error_(false),
1206 intercept_redirect_(false), cancel_redirect_request_(false),
1207 intercept_final_response_(false), cancel_final_request_(false),
1208 use_url_request_http_job_(false),
1209 did_intercept_main_(false), did_restart_main_(false),
1210 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1211 did_simulate_error_main_(false),
1212 did_intercept_redirect_(false), did_cancel_redirect_(false),
1213 did_intercept_final_(false), did_cancel_final_(false) {
1214 }
1215
1216 ~MockURLRequestInterceptor() override {
1217 }
1218
1219 // URLRequestInterceptor implementation:
1220 URLRequestJob* MaybeInterceptRequest(
1221 URLRequest* request,
1222 NetworkDelegate* network_delegate) const override {
1223 if (restart_main_request_) {
1224 restart_main_request_ = false;
1225 did_restart_main_ = true;
1226 return new RestartTestJob(request, network_delegate);
1227 }
1228 if (cancel_main_request_) {
1229 cancel_main_request_ = false;
1230 did_cancel_main_ = true;
1231 return new CancelTestJob(request, network_delegate);
1232 }
1233 if (cancel_then_restart_main_request_) {
1234 cancel_then_restart_main_request_ = false;
1235 did_cancel_then_restart_main_ = true;
1236 return new CancelThenRestartTestJob(request, network_delegate);
1237 }
1238 if (simulate_main_network_error_) {
1239 simulate_main_network_error_ = false;
1240 did_simulate_error_main_ = true;
1241 if (use_url_request_http_job_) {
1242 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1243 }
1244 // This job will result in error since the requested URL is not one of the
1245 // URLs supported by these tests.
1246 return new URLRequestTestJob(request, network_delegate, true);
1247 }
1248 if (!intercept_main_request_)
1249 return nullptr;
1250 intercept_main_request_ = false;
1251 did_intercept_main_ = true;
1252 URLRequestTestJob* job = new URLRequestTestJob(request,
1253 network_delegate,
1254 main_headers_,
1255 main_data_,
1256 true);
1257 job->set_load_timing_info(main_request_load_timing_info_);
1258 return job;
1259 }
1260
1261 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1262 NetworkDelegate* network_delegate,
1263 const GURL& location) const override {
1264 if (cancel_redirect_request_) {
1265 cancel_redirect_request_ = false;
1266 did_cancel_redirect_ = true;
1267 return new CancelTestJob(request, network_delegate);
1268 }
1269 if (!intercept_redirect_)
1270 return nullptr;
1271 intercept_redirect_ = false;
1272 did_intercept_redirect_ = true;
1273 if (use_url_request_http_job_) {
1274 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1275 }
1276 return new URLRequestTestJob(request,
1277 network_delegate,
1278 redirect_headers_,
1279 redirect_data_,
1280 true);
1281 }
1282
1283 URLRequestJob* MaybeInterceptResponse(
1284 URLRequest* request,
1285 NetworkDelegate* network_delegate) const override {
1286 if (cancel_final_request_) {
1287 cancel_final_request_ = false;
1288 did_cancel_final_ = true;
1289 return new CancelTestJob(request, network_delegate);
1290 }
1291 if (!intercept_final_response_)
1292 return nullptr;
1293 intercept_final_response_ = false;
1294 did_intercept_final_ = true;
1295 if (use_url_request_http_job_) {
1296 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1297 }
1298 return new URLRequestTestJob(request,
1299 network_delegate,
1300 final_headers_,
1301 final_data_,
1302 true);
1303 }
1304
1305 void set_intercept_main_request(bool intercept_main_request) {
1306 intercept_main_request_ = intercept_main_request;
1307 }
1308
1309 void set_main_headers(const std::string& main_headers) {
1310 main_headers_ = main_headers;
1311 }
1312
1313 void set_main_data(const std::string& main_data) {
1314 main_data_ = main_data;
1315 }
1316
1317 void set_main_request_load_timing_info(
1318 const LoadTimingInfo& main_request_load_timing_info) {
1319 main_request_load_timing_info_ = main_request_load_timing_info;
1320 }
1321
1322 void set_restart_main_request(bool restart_main_request) {
1323 restart_main_request_ = restart_main_request;
1324 }
1325
1326 void set_cancel_main_request(bool cancel_main_request) {
1327 cancel_main_request_ = cancel_main_request;
1328 }
1329
1330 void set_cancel_then_restart_main_request(
1331 bool cancel_then_restart_main_request) {
1332 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1333 }
1334
1335 void set_simulate_main_network_error(bool simulate_main_network_error) {
1336 simulate_main_network_error_ = simulate_main_network_error;
1337 }
1338
1339 void set_intercept_redirect(bool intercept_redirect) {
1340 intercept_redirect_ = intercept_redirect;
1341 }
1342
1343 void set_redirect_headers(const std::string& redirect_headers) {
1344 redirect_headers_ = redirect_headers;
1345 }
1346
1347 void set_redirect_data(const std::string& redirect_data) {
1348 redirect_data_ = redirect_data;
1349 }
1350
1351 void set_cancel_redirect_request(bool cancel_redirect_request) {
1352 cancel_redirect_request_ = cancel_redirect_request;
1353 }
1354
1355 void set_intercept_final_response(bool intercept_final_response) {
1356 intercept_final_response_ = intercept_final_response;
1357 }
1358
1359 void set_final_headers(const std::string& final_headers) {
1360 final_headers_ = final_headers;
1361 }
1362
1363 void set_final_data(const std::string& final_data) {
1364 final_data_ = final_data;
1365 }
1366
1367 void set_cancel_final_request(bool cancel_final_request) {
1368 cancel_final_request_ = cancel_final_request;
1369 }
1370
1371 void set_use_url_request_http_job(bool use_url_request_http_job) {
1372 use_url_request_http_job_ = use_url_request_http_job;
1373 }
1374
1375 bool did_intercept_main() const {
1376 return did_intercept_main_;
1377 }
1378
1379 bool did_restart_main() const {
1380 return did_restart_main_;
1381 }
1382
1383 bool did_cancel_main() const {
1384 return did_cancel_main_;
1385 }
1386
1387 bool did_cancel_then_restart_main() const {
1388 return did_cancel_then_restart_main_;
1389 }
1390
1391 bool did_simulate_error_main() const {
1392 return did_simulate_error_main_;
1393 }
1394
1395 bool did_intercept_redirect() const {
1396 return did_intercept_redirect_;
1397 }
1398
1399 bool did_cancel_redirect() const {
1400 return did_cancel_redirect_;
1401 }
1402
1403 bool did_intercept_final() const {
1404 return did_intercept_final_;
1405 }
1406
1407 bool did_cancel_final() const {
1408 return did_cancel_final_;
1409 }
1410
1411 private:
1412 // Indicate whether to intercept the main request, and if so specify the
1413 // response to return and the LoadTimingInfo to use.
1414 mutable bool intercept_main_request_;
1415 mutable std::string main_headers_;
1416 mutable std::string main_data_;
1417 mutable LoadTimingInfo main_request_load_timing_info_;
1418
1419 // These indicate actions that can be taken within MaybeInterceptRequest.
1420 mutable bool restart_main_request_;
1421 mutable bool cancel_main_request_;
1422 mutable bool cancel_then_restart_main_request_;
1423 mutable bool simulate_main_network_error_;
1424
1425 // Indicate whether to intercept redirects, and if so specify the response to
1426 // return.
1427 mutable bool intercept_redirect_;
1428 mutable std::string redirect_headers_;
1429 mutable std::string redirect_data_;
1430
1431 // Cancel the request within MaybeInterceptRedirect.
1432 mutable bool cancel_redirect_request_;
1433
1434 // Indicate whether to intercept the final response, and if so specify the
1435 // response to return.
1436 mutable bool intercept_final_response_;
1437 mutable std::string final_headers_;
1438 mutable std::string final_data_;
1439
1440 // Cancel the final request within MaybeInterceptResponse.
1441 mutable bool cancel_final_request_;
1442
1443 // Instruct the interceptor to use a real URLRequestHTTPJob.
1444 mutable bool use_url_request_http_job_;
1445
1446 // These indicate if the interceptor did something or not.
1447 mutable bool did_intercept_main_;
1448 mutable bool did_restart_main_;
1449 mutable bool did_cancel_main_;
1450 mutable bool did_cancel_then_restart_main_;
1451 mutable bool did_simulate_error_main_;
1452 mutable bool did_intercept_redirect_;
1453 mutable bool did_cancel_redirect_;
1454 mutable bool did_intercept_final_;
1455 mutable bool did_cancel_final_;
1456};
1457
1458// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1459class URLRequestInterceptorTest : public URLRequestTest {
1460 public:
1461 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1462 }
1463
1464 ~URLRequestInterceptorTest() override {
1465 // URLRequestJobs may post clean-up tasks on destruction.
1466 base::RunLoop().RunUntilIdle();
1467 }
1468
1469 void SetUpFactory() override {
1470 interceptor_ = new MockURLRequestInterceptor();
1471 job_factory_.reset(new URLRequestInterceptingJobFactory(
1472 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1473 }
1474
1475 MockURLRequestInterceptor* interceptor() const {
1476 return interceptor_;
1477 }
1478
1479 private:
1480 MockURLRequestInterceptor* interceptor_;
1481};
1482
1483TEST_F(URLRequestInterceptorTest, Intercept) {
1484 // Intercept the main request and respond with a simple response.
1485 interceptor()->set_intercept_main_request(true);
1486 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1487 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591488 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501489 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361490 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501491 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1492 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1493 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1494 req->SetUserData(nullptr, user_data0);
1495 req->SetUserData(&user_data1, user_data1);
1496 req->SetUserData(&user_data2, user_data2);
1497 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191498 req->Start();
[email protected]255620da2013-08-19 13:14:291499 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591500
bengr1bf8e942014-11-07 01:36:501501 // Make sure we can retrieve our specific user data.
1502 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1503 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1504 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591505
bengr1bf8e942014-11-07 01:36:501506 // Check that we got one good response.
1507 EXPECT_TRUE(req->status().is_success());
1508 EXPECT_EQ(200, req->response_headers()->response_code());
1509 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1510 EXPECT_EQ(1, d.response_started_count());
1511 EXPECT_EQ(0, d.received_redirect_count());
1512}
[email protected]2bba3252013-04-08 19:50:591513
bengr1bf8e942014-11-07 01:36:501514TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1515 // Intercept the main request and respond with a redirect.
1516 interceptor()->set_intercept_main_request(true);
1517 interceptor()->set_main_headers(
1518 MockURLRequestInterceptor::redirect_headers());
1519 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1520
1521 // Intercept that redirect and respond with a final OK response.
1522 interceptor()->set_intercept_redirect(true);
1523 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1524 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1525
1526 TestDelegate d;
1527 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361528 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501529 req->set_method("GET");
1530 req->Start();
1531 base::RunLoop().Run();
1532
1533 // Check that the interceptor got called as expected.
1534 EXPECT_TRUE(interceptor()->did_intercept_main());
1535 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1536
1537 // Check that we got one good response.
1538 EXPECT_TRUE(req->status().is_success());
1539 if (req->status().is_success())
1540 EXPECT_EQ(200, req->response_headers()->response_code());
1541
1542 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1543 EXPECT_EQ(1, d.response_started_count());
1544 EXPECT_EQ(0, d.received_redirect_count());
1545}
1546
1547TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1548 // Intercept the main request to generate a server error response.
1549 interceptor()->set_intercept_main_request(true);
1550 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1551 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1552
1553 // Intercept that error and respond with an OK response.
1554 interceptor()->set_intercept_final_response(true);
1555 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1556 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1557
1558 TestDelegate d;
1559 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361560 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501561 req->set_method("GET");
1562 req->Start();
1563 base::RunLoop().Run();
1564
1565 // Check that the interceptor got called as expected.
1566 EXPECT_TRUE(interceptor()->did_intercept_main());
1567 EXPECT_TRUE(interceptor()->did_intercept_final());
1568
1569 // Check that we got one good response.
1570 EXPECT_TRUE(req->status().is_success());
1571 EXPECT_EQ(200, req->response_headers()->response_code());
1572 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1573 EXPECT_EQ(1, d.response_started_count());
1574 EXPECT_EQ(0, d.received_redirect_count());
1575}
1576
1577TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1578 // Intercept the main request to simulate a network error.
1579 interceptor()->set_simulate_main_network_error(true);
1580
1581 // Intercept that error and respond with an OK response.
1582 interceptor()->set_intercept_final_response(true);
1583 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1584 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1585
1586 TestDelegate d;
1587 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361588 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501589 req->set_method("GET");
1590 req->Start();
1591 base::RunLoop().Run();
1592
1593 // Check that the interceptor got called as expected.
1594 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1595 EXPECT_TRUE(interceptor()->did_intercept_final());
1596
1597 // Check that we received one good response.
1598 EXPECT_TRUE(req->status().is_success());
1599 EXPECT_EQ(200, req->response_headers()->response_code());
1600 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1601 EXPECT_EQ(1, d.response_started_count());
1602 EXPECT_EQ(0, d.received_redirect_count());
1603}
1604
1605TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1606 // Restart the main request.
1607 interceptor()->set_restart_main_request(true);
1608
1609 // then intercept the new main request and respond with an OK response
1610 interceptor()->set_intercept_main_request(true);
1611 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1612 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1613
1614 TestDelegate d;
1615 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361616 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501617 req->set_method("GET");
1618 req->Start();
1619 base::RunLoop().Run();
1620
1621 // Check that the interceptor got called as expected.
1622 EXPECT_TRUE(interceptor()->did_restart_main());
1623 EXPECT_TRUE(interceptor()->did_intercept_main());
1624
1625 // Check that we received one good response.
1626 EXPECT_TRUE(req->status().is_success());
1627 if (req->status().is_success())
1628 EXPECT_EQ(200, req->response_headers()->response_code());
1629
1630 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1631 EXPECT_EQ(1, d.response_started_count());
1632 EXPECT_EQ(0, d.received_redirect_count());
1633}
1634
1635TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1636 // Intercept the main request and cancel from within the restarted job.
1637 interceptor()->set_cancel_main_request(true);
1638
1639 // Set up to intercept the final response and override it with an OK response.
1640 interceptor()->set_intercept_final_response(true);
1641 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1642 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1643
1644 TestDelegate d;
1645 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361646 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501647 req->set_method("GET");
1648 req->Start();
1649 base::RunLoop().Run();
1650
1651 // Check that the interceptor got called as expected.
1652 EXPECT_TRUE(interceptor()->did_cancel_main());
1653 EXPECT_FALSE(interceptor()->did_intercept_final());
1654
1655 // Check that we see a canceled request.
1656 EXPECT_FALSE(req->status().is_success());
1657 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1658}
1659
1660TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1661 // Intercept the main request and respond with a redirect.
1662 interceptor()->set_intercept_main_request(true);
1663 interceptor()->set_main_headers(
1664 MockURLRequestInterceptor::redirect_headers());
1665 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1666
1667 // Intercept the redirect and cancel from within that job.
1668 interceptor()->set_cancel_redirect_request(true);
1669
1670 // Set up to intercept the final response and override it with an OK response.
1671 interceptor()->set_intercept_final_response(true);
1672 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1673 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1674
1675 TestDelegate d;
1676 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361677 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501678 req->set_method("GET");
1679 req->Start();
1680 base::RunLoop().Run();
1681
1682 // Check that the interceptor got called as expected.
1683 EXPECT_TRUE(interceptor()->did_intercept_main());
1684 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1685 EXPECT_FALSE(interceptor()->did_intercept_final());
1686
1687 // Check that we see a canceled request.
1688 EXPECT_FALSE(req->status().is_success());
1689 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1690}
1691
1692TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1693 // Intercept the main request to simulate a network error.
1694 interceptor()->set_simulate_main_network_error(true);
1695
1696 // Set up to intercept final the response and cancel from within that job.
1697 interceptor()->set_cancel_final_request(true);
1698
1699 TestDelegate d;
1700 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361701 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501702 req->set_method("GET");
1703 req->Start();
1704 base::RunLoop().Run();
1705
1706 // Check that the interceptor got called as expected.
1707 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1708 EXPECT_TRUE(interceptor()->did_cancel_final());
1709
1710 // Check that we see a canceled request.
1711 EXPECT_FALSE(req->status().is_success());
1712 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1713}
1714
1715TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1716 // Intercept the main request and cancel then restart from within that job.
1717 interceptor()->set_cancel_then_restart_main_request(true);
1718
1719 // Set up to intercept the final response and override it with an OK response.
1720 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501721 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1722 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501723
1724 TestDelegate d;
1725 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361726 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501727 req->set_method("GET");
1728 req->Start();
1729 base::RunLoop().Run();
1730
1731 // Check that the interceptor got called as expected.
1732 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1733 EXPECT_FALSE(interceptor()->did_intercept_final());
1734
1735 // Check that we see a canceled request.
1736 EXPECT_FALSE(req->status().is_success());
1737 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591738}
1739
1740// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1741// reused. |connect_time_flags| is used to indicate if there should be dns
1742// or SSL times, and |used_proxy| is used for proxy times.
1743LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1744 int connect_time_flags,
1745 bool used_proxy) {
1746 LoadTimingInfo load_timing;
1747 load_timing.socket_log_id = 1;
1748
1749 if (used_proxy) {
1750 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1751 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1752 }
1753
1754 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1755 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1756 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1757 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1758 }
1759 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1760 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1761 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1762 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1763 }
1764 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1765
1766 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1767 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1768 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1769 return load_timing;
1770}
1771
1772// Same as above, but in the case of a reused socket.
1773LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1774 bool used_proxy) {
1775 LoadTimingInfo load_timing;
1776 load_timing.socket_log_id = 1;
1777 load_timing.socket_reused = true;
1778
1779 if (used_proxy) {
1780 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1781 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1782 }
1783
1784 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1785 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1786 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1787 return load_timing;
1788}
1789
bengr1bf8e942014-11-07 01:36:501790LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1791 const LoadTimingInfo& job_load_timing,
1792 const URLRequestContext& context,
1793 MockURLRequestInterceptor* interceptor) {
1794 interceptor->set_intercept_main_request(true);
1795 interceptor->set_main_request_load_timing_info(job_load_timing);
1796 TestDelegate d;
1797 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361798 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501799 req->Start();
1800 base::RunLoop().Run();
1801
1802 LoadTimingInfo resulting_load_timing;
1803 req->GetLoadTimingInfo(&resulting_load_timing);
1804
1805 // None of these should be modified by the URLRequest.
1806 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1807 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1808 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1809 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1810 EXPECT_EQ(job_load_timing.receive_headers_end,
1811 resulting_load_timing.receive_headers_end);
1812
1813 return resulting_load_timing;
1814}
1815
[email protected]2bba3252013-04-08 19:50:591816// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501817TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591818 base::TimeTicks now = base::TimeTicks::Now();
1819 LoadTimingInfo job_load_timing =
1820 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1821
[email protected]2ca01e52013-10-31 22:05:191822 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501823 RunURLRequestInterceptorLoadTimingTest(
1824 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591825
1826 // Nothing should have been changed by the URLRequest.
1827 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1828 load_timing_result.proxy_resolve_start);
1829 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1830 load_timing_result.proxy_resolve_end);
1831 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1832 load_timing_result.connect_timing.dns_start);
1833 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1834 load_timing_result.connect_timing.dns_end);
1835 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1836 load_timing_result.connect_timing.connect_start);
1837 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1838 load_timing_result.connect_timing.connect_end);
1839 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1840 load_timing_result.connect_timing.ssl_start);
1841 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1842 load_timing_result.connect_timing.ssl_end);
1843
1844 // Redundant sanity check.
1845 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1846}
1847
1848// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501849TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591850 base::TimeTicks now = base::TimeTicks::Now();
1851 LoadTimingInfo job_load_timing =
1852 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1853
[email protected]2ca01e52013-10-31 22:05:191854 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501855 RunURLRequestInterceptorLoadTimingTest(
1856 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591857
1858 // Nothing should have been changed by the URLRequest.
1859 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1860 load_timing_result.proxy_resolve_start);
1861 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1862 load_timing_result.proxy_resolve_end);
1863 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1864 load_timing_result.connect_timing.dns_start);
1865 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1866 load_timing_result.connect_timing.dns_end);
1867 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1868 load_timing_result.connect_timing.connect_start);
1869 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1870 load_timing_result.connect_timing.connect_end);
1871 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1872 load_timing_result.connect_timing.ssl_start);
1873 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1874 load_timing_result.connect_timing.ssl_end);
1875
1876 // Redundant sanity check.
1877 TestLoadTimingNotReusedWithProxy(load_timing_result,
1878 CONNECT_TIMING_HAS_SSL_TIMES);
1879}
1880
1881// Make sure that URLRequest correctly adjusts proxy times when they're before
1882// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101883// the case of reusing a SPDY session. The connected socket is not considered
1884// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591885//
1886// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501887TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591888 base::TimeTicks now = base::TimeTicks::Now();
1889 LoadTimingInfo job_load_timing =
1890 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1891 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1892 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1893 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1894 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1895 job_load_timing.connect_timing.connect_start =
1896 now - base::TimeDelta::FromDays(2);
1897 job_load_timing.connect_timing.connect_end =
1898 now - base::TimeDelta::FromDays(1);
1899
[email protected]2ca01e52013-10-31 22:05:191900 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501901 RunURLRequestInterceptorLoadTimingTest(
1902 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591903
1904 // Proxy times, connect times, and DNS times should all be replaced with
1905 // request_start.
1906 EXPECT_EQ(load_timing_result.request_start,
1907 load_timing_result.proxy_resolve_start);
1908 EXPECT_EQ(load_timing_result.request_start,
1909 load_timing_result.proxy_resolve_end);
1910 EXPECT_EQ(load_timing_result.request_start,
1911 load_timing_result.connect_timing.dns_start);
1912 EXPECT_EQ(load_timing_result.request_start,
1913 load_timing_result.connect_timing.dns_end);
1914 EXPECT_EQ(load_timing_result.request_start,
1915 load_timing_result.connect_timing.connect_start);
1916 EXPECT_EQ(load_timing_result.request_start,
1917 load_timing_result.connect_timing.connect_end);
1918
1919 // Other times should have been left null.
1920 TestLoadTimingNotReusedWithProxy(load_timing_result,
1921 CONNECT_TIMING_HAS_DNS_TIMES);
1922}
1923
1924// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501925TEST_F(URLRequestInterceptorTest,
1926 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591927 base::TimeTicks now = base::TimeTicks::Now();
1928 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1929 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1930 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1931
[email protected]2ca01e52013-10-31 22:05:191932 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501933 RunURLRequestInterceptorLoadTimingTest(
1934 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591935
1936 // Proxy times and connect times should all be replaced with request_start.
1937 EXPECT_EQ(load_timing_result.request_start,
1938 load_timing_result.proxy_resolve_start);
1939 EXPECT_EQ(load_timing_result.request_start,
1940 load_timing_result.proxy_resolve_end);
1941
1942 // Other times should have been left null.
1943 TestLoadTimingReusedWithProxy(load_timing_result);
1944}
1945
1946// Make sure that URLRequest correctly adjusts connect times when they're before
1947// |request_start|, due to reusing a connected socket. The connected socket is
1948// not considered reused in this test (May be a preconnect).
1949//
1950// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501951TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:591952 base::TimeTicks now = base::TimeTicks::Now();
1953 LoadTimingInfo job_load_timing =
1954 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1955 job_load_timing.connect_timing.connect_start =
1956 now - base::TimeDelta::FromDays(1);
1957 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1958 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1959 job_load_timing.connect_timing.connect_end =
1960 now - base::TimeDelta::FromDays(4);
1961
[email protected]2ca01e52013-10-31 22:05:191962 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501963 RunURLRequestInterceptorLoadTimingTest(
1964 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591965
1966 // Connect times, and SSL times should be replaced with request_start.
1967 EXPECT_EQ(load_timing_result.request_start,
1968 load_timing_result.connect_timing.connect_start);
1969 EXPECT_EQ(load_timing_result.request_start,
1970 load_timing_result.connect_timing.ssl_start);
1971 EXPECT_EQ(load_timing_result.request_start,
1972 load_timing_result.connect_timing.ssl_end);
1973 EXPECT_EQ(load_timing_result.request_start,
1974 load_timing_result.connect_timing.connect_end);
1975
1976 // Other times should have been left null.
1977 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1978}
1979
1980// Make sure that URLRequest correctly adjusts connect times when they're before
1981// |request_start|, due to reusing a connected socket in the case that there
1982// are also proxy times. The connected socket is not considered reused in this
1983// test (May be a preconnect).
1984//
1985// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:501986TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:591987 base::TimeTicks now = base::TimeTicks::Now();
1988 LoadTimingInfo job_load_timing =
1989 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1990 job_load_timing.connect_timing.connect_start =
1991 now - base::TimeDelta::FromDays(1);
1992 job_load_timing.connect_timing.connect_end =
1993 now - base::TimeDelta::FromDays(2);
1994
[email protected]2ca01e52013-10-31 22:05:191995 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501996 RunURLRequestInterceptorLoadTimingTest(
1997 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591998
1999 // Connect times should be replaced with proxy_resolve_end.
2000 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2001 load_timing_result.connect_timing.connect_start);
2002 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2003 load_timing_result.connect_timing.connect_end);
2004
2005 // Other times should have been left null.
2006 TestLoadTimingNotReusedWithProxy(load_timing_result,
2007 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2008}
2009
[email protected]316c1e5e2012-09-12 15:17:442010// Check that two different URL requests have different identifiers.
2011TEST_F(URLRequestTest, Identifiers) {
2012 TestDelegate d;
2013 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362014 scoped_ptr<URLRequest> req(
2015 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2016 scoped_ptr<URLRequest> other_req(
2017 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442018
mmenke19378d22014-09-09 04:12:592019 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442020}
2021
2022// Check that a failure to connect to the proxy is reported to the network
2023// delegate.
2024TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2025 MockHostResolver host_resolver;
2026 host_resolver.rules()->AddSimulatedFailure("*");
2027
[email protected]ceefd7fd2012-11-29 00:36:242028 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442029 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2030
2031 TestDelegate d;
davidben151423e2015-03-23 18:48:362032 scoped_ptr<URLRequest> req(
2033 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192034 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442035
[email protected]f7022f32014-08-21 16:32:192036 req->Start();
[email protected]255620da2013-08-19 13:14:292037 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442038
2039 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192040 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152041 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192042 EXPECT_TRUE(req->proxy_server().IsEmpty());
2043 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2044 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442045
2046 EXPECT_EQ(1, network_delegate.error_count());
2047 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2048 EXPECT_EQ(1, network_delegate.completed_requests());
2049}
2050
[email protected]cba24642014-08-15 20:49:592051// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442052// content is empty.
2053TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2054 TestDelegate d;
davidben151423e2015-03-23 18:48:362055 scoped_ptr<URLRequest> req(
2056 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192057 req->Start();
[email protected]255620da2013-08-19 13:14:292058 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442059 EXPECT_EQ("", d.data_received());
2060 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2061}
2062
[email protected]5033ab82013-03-22 20:17:462063// Make sure that SetPriority actually sets the URLRequest's priority
2064// correctly, both before and after start.
2065TEST_F(URLRequestTest, SetPriorityBasic) {
2066 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192067 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362068 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192069 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462070
[email protected]f7022f32014-08-21 16:32:192071 req->SetPriority(LOW);
2072 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462073
[email protected]f7022f32014-08-21 16:32:192074 req->Start();
2075 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462076
[email protected]f7022f32014-08-21 16:32:192077 req->SetPriority(MEDIUM);
2078 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462079}
2080
2081// Make sure that URLRequest calls SetPriority on a job before calling
2082// Start on it.
2083TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2084 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192085 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362086 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192087 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462088
2089 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192090 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502091 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462092 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2093
[email protected]f7022f32014-08-21 16:32:192094 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462095
[email protected]f7022f32014-08-21 16:32:192096 req->Start();
[email protected]5033ab82013-03-22 20:17:462097 EXPECT_EQ(LOW, job->priority());
2098}
2099
2100// Make sure that URLRequest passes on its priority updates to its
2101// job.
2102TEST_F(URLRequestTest, SetJobPriority) {
2103 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192104 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362105 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462106
2107 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192108 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502109 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462110
[email protected]f7022f32014-08-21 16:32:192111 req->SetPriority(LOW);
2112 req->Start();
[email protected]5033ab82013-03-22 20:17:462113 EXPECT_EQ(LOW, job->priority());
2114
[email protected]f7022f32014-08-21 16:32:192115 req->SetPriority(MEDIUM);
2116 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462117 EXPECT_EQ(MEDIUM, job->priority());
2118}
2119
[email protected]bb1c4662013-11-14 00:00:072120// Setting the IGNORE_LIMITS load flag should be okay if the priority
2121// is MAXIMUM_PRIORITY.
2122TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2123 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192124 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362125 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192126 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072127
2128 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192129 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072130 AddTestInterceptor()->set_main_intercept_job(job.get());
2131
[email protected]f7022f32014-08-21 16:32:192132 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2133 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072134
[email protected]f7022f32014-08-21 16:32:192135 req->SetPriority(MAXIMUM_PRIORITY);
2136 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072137
[email protected]f7022f32014-08-21 16:32:192138 req->Start();
2139 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072140 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2141}
2142
[email protected]ce7d0cbc2013-05-03 18:57:222143// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442144#if !defined(OS_IOS)
nick5d570de92015-05-04 20:16:162145namespace {
2146
2147// Less verbose way of running a simple testserver for the tests below.
[email protected]ce7d0cbc2013-05-03 18:57:222148class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442149 public:
[email protected]6cdfd7f2013-02-08 20:40:152150 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222151 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162152 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222153 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442154 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222155 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162156 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222157 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442158};
2159
nick5d570de92015-05-04 20:16:162160} // namespace
2161
[email protected]f2f31b32013-01-16 23:24:092162TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442163 LocalHttpTestServer test_server;
2164 ASSERT_TRUE(test_server.Start());
2165
2166 TestURLRequestContext context;
2167 scoped_refptr<DelayedCookieMonster> delayed_cm =
2168 new DelayedCookieMonster();
2169 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502170 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442171
2172 // Set up a cookie.
2173 {
2174 TestNetworkDelegate network_delegate;
2175 context.set_network_delegate(&network_delegate);
2176 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192177 scoped_ptr<URLRequest> req(context.CreateRequest(
2178 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362179 &d));
[email protected]f7022f32014-08-21 16:32:192180 req->Start();
[email protected]255620da2013-08-19 13:14:292181 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442182 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2183 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2184 EXPECT_EQ(1, network_delegate.set_cookie_count());
2185 }
2186
2187 // Verify that the cookie is set.
2188 {
2189 TestNetworkDelegate network_delegate;
2190 context.set_network_delegate(&network_delegate);
2191 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192192 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:362193 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192194 req->Start();
[email protected]255620da2013-08-19 13:14:292195 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442196
2197 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2198 != std::string::npos);
2199 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2200 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2201 }
2202}
2203
[email protected]f2f31b32013-01-16 23:24:092204TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442205 LocalHttpTestServer test_server;
2206 ASSERT_TRUE(test_server.Start());
2207
2208 // Set up a cookie.
2209 {
2210 TestNetworkDelegate network_delegate;
2211 default_context_.set_network_delegate(&network_delegate);
2212 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192213 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2214 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362215 &d));
[email protected]f7022f32014-08-21 16:32:192216 req->Start();
[email protected]255620da2013-08-19 13:14:292217 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442218 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2219 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2220 }
2221
2222 // Verify that the cookie is set.
2223 {
2224 TestNetworkDelegate network_delegate;
2225 default_context_.set_network_delegate(&network_delegate);
2226 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192227 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362228 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192229 req->Start();
[email protected]255620da2013-08-19 13:14:292230 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442231
2232 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2233 != std::string::npos);
2234 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2235 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2236 }
2237
2238 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2239 {
2240 TestNetworkDelegate network_delegate;
2241 default_context_.set_network_delegate(&network_delegate);
2242 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192243 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362244 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192245 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2246 req->Start();
[email protected]255620da2013-08-19 13:14:292247 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442248
2249 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2250 == std::string::npos);
2251
2252 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2253 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2254 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2255 }
2256}
2257
2258TEST_F(URLRequestTest, DoNotSaveCookies) {
2259 LocalHttpTestServer test_server;
2260 ASSERT_TRUE(test_server.Start());
2261
2262 // Set up a cookie.
2263 {
2264 TestNetworkDelegate network_delegate;
2265 default_context_.set_network_delegate(&network_delegate);
2266 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192267 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2268 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362269 &d));
[email protected]f7022f32014-08-21 16:32:192270 req->Start();
[email protected]255620da2013-08-19 13:14:292271 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442272
2273 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2274 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2275 EXPECT_EQ(1, network_delegate.set_cookie_count());
2276 }
2277
2278 // Try to set-up another cookie and update the previous cookie.
2279 {
2280 TestNetworkDelegate network_delegate;
2281 default_context_.set_network_delegate(&network_delegate);
2282 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192283 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442284 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362285 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192286 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2287 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442288
[email protected]255620da2013-08-19 13:14:292289 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442290
2291 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2292 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2293 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2294 EXPECT_EQ(0, network_delegate.set_cookie_count());
2295 }
2296
2297 // Verify the cookies weren't saved or updated.
2298 {
2299 TestNetworkDelegate network_delegate;
2300 default_context_.set_network_delegate(&network_delegate);
2301 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192302 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362303 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192304 req->Start();
[email protected]255620da2013-08-19 13:14:292305 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442306
2307 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2308 == std::string::npos);
2309 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2310 != std::string::npos);
2311
2312 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2313 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2314 EXPECT_EQ(0, network_delegate.set_cookie_count());
2315 }
2316}
2317
2318TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2319 LocalHttpTestServer test_server;
2320 ASSERT_TRUE(test_server.Start());
2321
2322 // Set up a cookie.
2323 {
2324 TestNetworkDelegate network_delegate;
2325 default_context_.set_network_delegate(&network_delegate);
2326 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192327 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2328 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362329 &d));
[email protected]f7022f32014-08-21 16:32:192330 req->Start();
[email protected]255620da2013-08-19 13:14:292331 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442332
2333 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2334 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2335 }
2336
2337 // Verify that the cookie is set.
2338 {
2339 TestNetworkDelegate network_delegate;
2340 default_context_.set_network_delegate(&network_delegate);
2341 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192342 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362343 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192344 req->Start();
[email protected]255620da2013-08-19 13:14:292345 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442346
2347 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2348 != std::string::npos);
2349
2350 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2351 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2352 }
2353
2354 // Verify that the cookie isn't sent.
2355 {
2356 TestNetworkDelegate network_delegate;
2357 default_context_.set_network_delegate(&network_delegate);
2358 TestDelegate d;
2359 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192360 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362361 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192362 req->Start();
[email protected]255620da2013-08-19 13:14:292363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442364
2365 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2366 == std::string::npos);
2367
[email protected]22e045f2013-09-20 03:54:032368 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442369 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2370 }
2371}
2372
2373TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2374 LocalHttpTestServer test_server;
2375 ASSERT_TRUE(test_server.Start());
2376
2377 // Set up a cookie.
2378 {
2379 TestNetworkDelegate network_delegate;
2380 default_context_.set_network_delegate(&network_delegate);
2381 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192382 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2383 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362384 &d));
[email protected]f7022f32014-08-21 16:32:192385 req->Start();
[email protected]255620da2013-08-19 13:14:292386 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442387
2388 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2389 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2390 }
2391
2392 // Try to set-up another cookie and update the previous cookie.
2393 {
2394 TestNetworkDelegate network_delegate;
2395 default_context_.set_network_delegate(&network_delegate);
2396 TestDelegate d;
2397 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192398 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442399 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362400 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192401 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442402
[email protected]255620da2013-08-19 13:14:292403 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442404
2405 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2406 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2407 }
2408
2409 // Verify the cookies weren't saved or updated.
2410 {
2411 TestNetworkDelegate network_delegate;
2412 default_context_.set_network_delegate(&network_delegate);
2413 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192414 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362415 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192416 req->Start();
[email protected]255620da2013-08-19 13:14:292417 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442418
2419 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2420 == std::string::npos);
2421 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2422 != std::string::npos);
2423
2424 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2425 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2426 }
2427}
2428
2429TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2430 LocalHttpTestServer test_server;
2431 ASSERT_TRUE(test_server.Start());
2432
2433 // Set up an empty cookie.
2434 {
2435 TestNetworkDelegate network_delegate;
2436 default_context_.set_network_delegate(&network_delegate);
2437 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192438 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362439 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192440 req->Start();
[email protected]255620da2013-08-19 13:14:292441 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442442
2443 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2444 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2445 EXPECT_EQ(0, network_delegate.set_cookie_count());
2446 }
2447}
2448
2449TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2450 LocalHttpTestServer test_server;
2451 ASSERT_TRUE(test_server.Start());
2452
2453 // Set up a cookie.
2454 {
2455 TestNetworkDelegate network_delegate;
2456 default_context_.set_network_delegate(&network_delegate);
2457 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192458 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2459 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362460 &d));
[email protected]f7022f32014-08-21 16:32:192461 req->Start();
[email protected]255620da2013-08-19 13:14:292462 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442463
2464 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2465 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2466 }
2467
2468 // Verify that the cookie is set.
2469 {
2470 TestNetworkDelegate network_delegate;
2471 default_context_.set_network_delegate(&network_delegate);
2472 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192473 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362474 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192475 req->Start();
[email protected]255620da2013-08-19 13:14:292476 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442477
2478 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2479 != std::string::npos);
2480
2481 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2482 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2483 }
2484
2485 // Verify that the cookie isn't sent.
2486 {
2487 TestNetworkDelegate network_delegate;
2488 default_context_.set_network_delegate(&network_delegate);
2489 TestDelegate d;
2490 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192491 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362492 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192493 req->Start();
[email protected]255620da2013-08-19 13:14:292494 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442495
2496 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2497 == std::string::npos);
2498
[email protected]22e045f2013-09-20 03:54:032499 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442500 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2501 }
2502}
2503
2504TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2505 LocalHttpTestServer test_server;
2506 ASSERT_TRUE(test_server.Start());
2507
2508 // Set up a cookie.
2509 {
2510 TestNetworkDelegate network_delegate;
2511 default_context_.set_network_delegate(&network_delegate);
2512 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192513 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2514 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362515 &d));
[email protected]f7022f32014-08-21 16:32:192516 req->Start();
[email protected]255620da2013-08-19 13:14:292517 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442518
2519 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2520 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2521 }
2522
2523 // Try to set-up another cookie and update the previous cookie.
2524 {
2525 TestNetworkDelegate network_delegate;
2526 default_context_.set_network_delegate(&network_delegate);
2527 TestDelegate d;
2528 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192529 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442530 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362531 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192532 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442533
[email protected]255620da2013-08-19 13:14:292534 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442535
2536 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2537 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2538 }
2539
2540 // Verify the cookies weren't saved or updated.
2541 {
2542 TestNetworkDelegate network_delegate;
2543 default_context_.set_network_delegate(&network_delegate);
2544 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192545 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362546 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192547 req->Start();
[email protected]255620da2013-08-19 13:14:292548 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442549
2550 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2551 == std::string::npos);
2552 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2553 != std::string::npos);
2554
2555 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2556 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2557 }
2558}
2559
mkwst3f3daac2015-02-26 20:15:262560TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2561 LocalHttpTestServer test_server;
2562 ASSERT_TRUE(test_server.Start());
2563
2564 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2565 // LocalHttpTestServer points).
2566 {
2567 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152568 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262569 default_context_.set_network_delegate(&network_delegate);
2570
2571 TestDelegate d;
2572 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2573 test_server.GetURL(
2574 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362575 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262576 req->Start();
2577 base::RunLoop().Run();
2578 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2579 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2580 EXPECT_EQ(1, network_delegate.set_cookie_count());
2581 }
2582
2583 // Verify that the cookie is sent for first-party requests.
2584 {
2585 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152586 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262587 default_context_.set_network_delegate(&network_delegate);
2588 TestDelegate d;
2589 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362590 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472591 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst3f3daac2015-02-26 20:15:262592 req->Start();
2593 base::RunLoop().Run();
2594
2595 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2596 std::string::npos);
2597 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2598 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2599 }
2600
2601 // Verify that the cookie is not-sent for non-first-party requests.
2602 {
2603 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152604 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262605 default_context_.set_network_delegate(&network_delegate);
2606 TestDelegate d;
2607 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362608 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262609 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2610 req->Start();
2611 base::RunLoop().Run();
2612
2613 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2614 std::string::npos);
2615 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2616 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2617 }
2618}
2619
mkwst0513c9d2015-04-01 05:53:152620TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2621 LocalHttpTestServer test_server;
2622 ASSERT_TRUE(test_server.Start());
2623
2624 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2625 // LocalHttpTestServer points).
2626 {
2627 TestNetworkDelegate network_delegate;
2628 network_delegate.set_first_party_only_cookies_enabled(false);
2629 default_context_.set_network_delegate(&network_delegate);
2630
2631 TestDelegate d;
2632 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2633 test_server.GetURL(
2634 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2635 DEFAULT_PRIORITY, &d));
2636 req->Start();
2637 base::RunLoop().Run();
2638 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2639 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2640 EXPECT_EQ(1, network_delegate.set_cookie_count());
2641 }
2642
2643 // Verify that the cookie is sent for first-party requests.
2644 {
2645 TestNetworkDelegate network_delegate;
2646 network_delegate.set_first_party_only_cookies_enabled(false);
2647 default_context_.set_network_delegate(&network_delegate);
2648 TestDelegate d;
2649 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2650 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472651 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst0513c9d2015-04-01 05:53:152652 req->Start();
2653 base::RunLoop().Run();
2654
2655 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2656 std::string::npos);
2657 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2658 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2659 }
2660
2661 // Verify that the cookie is also sent for non-first-party requests.
2662 {
2663 TestNetworkDelegate network_delegate;
2664 network_delegate.set_first_party_only_cookies_enabled(false);
2665 default_context_.set_network_delegate(&network_delegate);
2666 TestDelegate d;
2667 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2668 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2669 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2670 req->Start();
2671 base::RunLoop().Run();
2672
2673 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2674 std::string::npos);
2675 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2676 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2677 }
2678}
2679
[email protected]5095cd72012-11-01 10:29:162680// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2681// value for the |fixed_date| argument given to the constructor.
2682class FixedDateNetworkDelegate : public TestNetworkDelegate {
2683 public:
2684 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2685 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202686 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162687
[email protected]cba24642014-08-15 20:49:592688 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202689 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592690 URLRequest* request,
2691 const CompletionCallback& callback,
2692 const HttpResponseHeaders* original_response_headers,
2693 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132694 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162695
2696 private:
2697 std::string fixed_date_;
2698
2699 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2700};
2701
2702int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592703 URLRequest* request,
2704 const CompletionCallback& callback,
2705 const HttpResponseHeaders* original_response_headers,
2706 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162707 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592708 HttpResponseHeaders* new_response_headers =
2709 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162710
2711 new_response_headers->RemoveHeader("Date");
2712 new_response_headers->AddHeader("Date: " + fixed_date_);
2713
2714 *override_response_headers = new_response_headers;
2715 return TestNetworkDelegate::OnHeadersReceived(request,
2716 callback,
2717 original_response_headers,
[email protected]5f714132014-03-26 10:41:162718 override_response_headers,
2719 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162720}
2721
2722// Test that cookie expiration times are adjusted for server/client clock
2723// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2724// headers by defaulting to GMT. (crbug.com/135131)
2725TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2726 LocalHttpTestServer test_server;
2727 ASSERT_TRUE(test_server.Start());
2728
2729 // Set up an expired cookie.
2730 {
2731 TestNetworkDelegate network_delegate;
2732 default_context_.set_network_delegate(&network_delegate);
2733 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192734 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192735 test_server.GetURL(
2736 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362737 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192738 req->Start();
[email protected]255620da2013-08-19 13:14:292739 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162740 }
2741 // Verify that the cookie is not set.
2742 {
2743 TestNetworkDelegate network_delegate;
2744 default_context_.set_network_delegate(&network_delegate);
2745 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192746 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362747 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192748 req->Start();
[email protected]255620da2013-08-19 13:14:292749 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162750
2751 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2752 }
2753 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2754 {
2755 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2756 default_context_.set_network_delegate(&network_delegate);
2757 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192758 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192759 test_server.GetURL(
2760 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362761 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192762 req->Start();
[email protected]255620da2013-08-19 13:14:292763 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162764 }
2765 // Verify that the cookie is set.
2766 {
2767 TestNetworkDelegate network_delegate;
2768 default_context_.set_network_delegate(&network_delegate);
2769 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192770 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362771 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192772 req->Start();
[email protected]255620da2013-08-19 13:14:292773 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162774
2775 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2776 }
2777}
2778
2779
[email protected]316c1e5e2012-09-12 15:17:442780// Check that it is impossible to change the referrer in the extra headers of
2781// an URLRequest.
2782TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2783 LocalHttpTestServer test_server;
2784 ASSERT_TRUE(test_server.Start());
2785
2786 // If extra headers contain referer and the request contains a referer,
2787 // only the latter shall be respected.
2788 {
2789 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192790 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362791 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192792 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442793
2794 HttpRequestHeaders headers;
2795 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192796 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:442797
[email protected]f7022f32014-08-21 16:32:192798 req->Start();
[email protected]255620da2013-08-19 13:14:292799 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442800
2801 EXPECT_EQ("http://foo.com/", d.data_received());
2802 }
2803
2804 // If extra headers contain a referer but the request does not, no referer
2805 // shall be sent in the header.
2806 {
2807 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192808 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362809 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442810
2811 HttpRequestHeaders headers;
2812 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192813 req->SetExtraRequestHeaders(headers);
2814 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442815
[email protected]f7022f32014-08-21 16:32:192816 req->Start();
[email protected]255620da2013-08-19 13:14:292817 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442818
2819 EXPECT_EQ("None", d.data_received());
2820 }
2821}
2822
[email protected]b89290212009-08-14 22:37:352823class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112824 public:
mmenke9f2ec60c2015-06-01 20:59:472825 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:112826
[email protected]b89290212009-08-14 22:37:352827 protected:
[email protected]21184962011-10-26 00:50:302828 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2829 // |request_method| is the method to use for the initial request.
2830 // |redirect_method| is the method that is expected to be used for the second
2831 // request, after redirection.
2832 // If |include_data| is true, data is uploaded with the request. The
2833 // response body is expected to match it exactly, if and only if
2834 // |request_method| == |redirect_method|.
2835 void HTTPRedirectMethodTest(const GURL& redirect_url,
2836 const std::string& request_method,
2837 const std::string& redirect_method,
2838 bool include_data) {
2839 static const char kData[] = "hello world";
2840 TestDelegate d;
davidben151423e2015-03-23 18:48:362841 scoped_ptr<URLRequest> req(
2842 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192843 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:302844 if (include_data) {
mmenkecbc2b712014-10-09 20:29:072845 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:302846 HttpRequestHeaders headers;
2847 headers.SetHeader(HttpRequestHeaders::kContentLength,
2848 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:192849 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:302850 }
[email protected]f7022f32014-08-21 16:32:192851 req->Start();
[email protected]255620da2013-08-19 13:14:292852 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:192853 EXPECT_EQ(redirect_method, req->method());
2854 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2855 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:302856 if (include_data) {
2857 if (request_method == redirect_method) {
2858 EXPECT_EQ(kData, d.data_received());
2859 } else {
2860 EXPECT_NE(kData, d.data_received());
2861 }
2862 }
2863 if (HasFailure())
2864 LOG(WARNING) << "Request method was: " << request_method;
2865 }
2866
jww5fe460ff2015-03-28 00:22:512867 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2868 // |request_method| is the method to use for the initial request.
2869 // |redirect_method| is the method that is expected to be used for the second
2870 // request, after redirection.
2871 // |origin_value| is the expected value for the Origin header after
2872 // redirection. If empty, expects that there will be no Origin header.
2873 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
2874 const std::string& request_method,
2875 const std::string& redirect_method,
2876 const std::string& origin_value) {
2877 TestDelegate d;
2878 scoped_ptr<URLRequest> req(
2879 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
2880 req->set_method(request_method);
2881 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
2882 redirect_url.GetOrigin().spec(), false);
2883 req->Start();
2884
2885 base::RunLoop().Run();
2886
2887 EXPECT_EQ(redirect_method, req->method());
2888 // Note that there is no check for request success here because, for
2889 // purposes of testing, the request very well may fail. For example, if the
2890 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
2891 // origin, there is not an HTTPS server in this unit test framework, so the
2892 // request would fail. However, that's fine, as long as the request headers
2893 // are in order and pass the checks below.
2894 if (origin_value.empty()) {
2895 EXPECT_FALSE(
2896 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
2897 } else {
2898 std::string origin_header;
2899 EXPECT_TRUE(req->extra_request_headers().GetHeader(
2900 HttpRequestHeaders::kOrigin, &origin_header));
2901 EXPECT_EQ(origin_value, origin_header);
2902 }
2903 }
2904
[email protected]762d2db2010-01-11 19:03:012905 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012906 const int kMsgSize = 20000; // multiple of 10
2907 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482908 char* uploadBytes = new char[kMsgSize+1];
2909 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012910 char marker = 'a';
2911 for (int idx = 0; idx < kMsgSize/10; idx++) {
2912 memcpy(ptr, "----------", 10);
2913 ptr += 10;
2914 if (idx % 100 == 0) {
2915 ptr--;
2916 *ptr++ = marker;
2917 if (++marker > 'z')
2918 marker = 'a';
2919 }
2920 }
2921 uploadBytes[kMsgSize] = '\0';
2922
[email protected]762d2db2010-01-11 19:03:012923 for (int i = 0; i < kIterations; ++i) {
2924 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192925 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362926 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192927 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:012928
mmenkecbc2b712014-10-09 20:29:072929 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:012930
[email protected]f7022f32014-08-21 16:32:192931 r->Start();
2932 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:012933
[email protected]255620da2013-08-19 13:14:292934 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012935
[email protected]329b68b2012-11-14 17:54:272936 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:192937 << "request failed: " << r->status().status()
2938 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:012939
2940 EXPECT_FALSE(d.received_data_before_response());
2941 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012942 }
2943 delete[] uploadBytes;
2944 }
2945
[email protected]ef2bf422012-05-11 03:27:092946 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222947 r->AppendChunkToUpload("a", 1, false);
2948 r->AppendChunkToUpload("bcd", 3, false);
2949 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2950 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2951 r->AppendChunkToUpload("0", 1, false);
2952 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112953 }
2954
[email protected]ef2bf422012-05-11 03:27:092955 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112956 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272957 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112958 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2959
[email protected]329b68b2012-11-14 17:54:272960 ASSERT_EQ(1, d->response_started_count())
2961 << "request failed: " << r->status().status()
2962 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112963
2964 EXPECT_FALSE(d->received_data_before_response());
2965
[email protected]329b68b2012-11-14 17:54:272966 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2967 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112968 }
2969
[email protected]ede03212012-09-07 12:52:262970 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342971 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192972 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2973 test_server_.GetURL("set-many-cookies?" +
davidben151423e2015-03-23 18:48:362974 base::IntToString(num_cookies)),
2975 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:342976
[email protected]f7022f32014-08-21 16:32:192977 r->Start();
2978 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:342979
[email protected]255620da2013-08-19 13:14:292980 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342981
[email protected]f7022f32014-08-21 16:32:192982 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:342983
[email protected]ede03212012-09-07 12:52:262984 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:192985 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:342986 // The test server appears to be unable to handle subsequent requests
2987 // after this error is triggered. Force it to restart.
2988 EXPECT_TRUE(test_server_.Stop());
2989 EXPECT_TRUE(test_server_.Start());
2990 }
2991
2992 return is_success;
2993 }
2994
bengr1bf8e942014-11-07 01:36:502995 LocalHttpTestServer* test_server() {
2996 return &test_server_;
2997 }
2998
2999 protected:
[email protected]1700c6a2012-02-22 18:07:073000 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353001};
3002
[email protected]95409e12010-08-17 20:07:113003// In this unit test, we're using the HTTPTestServer as a proxy server and
3004// issuing a CONNECT request with the magic host name "www.redirect.com".
3005// The HTTPTestServer will return a 302 response, which we should not
3006// follow.
[email protected]f2f31b32013-01-16 23:24:093007TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:113008 ASSERT_TRUE(test_server_.Start());
3009
[email protected]ceefd7fd2012-11-29 00:36:243010 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043011 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193012 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503013
[email protected]d1ec59082009-02-11 02:48:153014 TestDelegate d;
3015 {
[email protected]f7022f32014-08-21 16:32:193016 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363017 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193018 r->Start();
3019 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153020
[email protected]255620da2013-08-19 13:14:293021 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153022
[email protected]f7022f32014-08-21 16:32:193023 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153024 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193025 EXPECT_TRUE(r->proxy_server().IsEmpty());
3026 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083027 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153028 // We should not have followed the redirect.
3029 EXPECT_EQ(0, d.received_redirect_count());
3030 }
3031}
3032
[email protected]8202d0c2011-02-23 08:31:143033// This is the same as the previous test, but checks that the network delegate
3034// registers the error.
[email protected]c044616e2013-02-20 02:01:263035TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:143036 ASSERT_TRUE(test_server_.Start());
3037
[email protected]ceefd7fd2012-11-29 00:36:243038 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043039 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193040 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503041
[email protected]8202d0c2011-02-23 08:31:143042 TestDelegate d;
3043 {
[email protected]f7022f32014-08-21 16:32:193044 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363045 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193046 r->Start();
3047 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143048
[email protected]255620da2013-08-19 13:14:293049 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143050
[email protected]f7022f32014-08-21 16:32:193051 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153052 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193053 EXPECT_TRUE(r->proxy_server().IsEmpty());
3054 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143055 EXPECT_EQ(1, d.response_started_count());
3056 // We should not have followed the redirect.
3057 EXPECT_EQ(0, d.received_redirect_count());
3058
3059 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053060 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143061 }
3062}
3063
[email protected]dc5a5cf2012-09-26 02:49:303064// Tests that we can block and asynchronously return OK in various stages.
3065TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3066 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3067 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3068 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3069 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3070 };
3071 static const size_t blocking_stages_length = arraysize(blocking_stages);
3072
3073 ASSERT_TRUE(test_server_.Start());
3074
3075 TestDelegate d;
3076 BlockingNetworkDelegate network_delegate(
3077 BlockingNetworkDelegate::USER_CALLBACK);
3078 network_delegate.set_block_on(
3079 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3080 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3081 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3082
3083 TestURLRequestContext context(true);
3084 context.set_network_delegate(&network_delegate);
3085 context.Init();
3086
3087 {
[email protected]f7022f32014-08-21 16:32:193088 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363089 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303090
[email protected]f7022f32014-08-21 16:32:193091 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303092 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293093 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303094 EXPECT_EQ(blocking_stages[i],
3095 network_delegate.stage_blocked_for_callback());
3096 network_delegate.DoCallback(OK);
3097 }
[email protected]255620da2013-08-19 13:14:293098 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193099 EXPECT_EQ(200, r->GetResponseCode());
3100 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303101 EXPECT_EQ(1, network_delegate.created_requests());
3102 EXPECT_EQ(0, network_delegate.destroyed_requests());
3103 }
3104 EXPECT_EQ(1, network_delegate.destroyed_requests());
3105}
3106
[email protected]4c76d7c2011-04-15 19:14:123107// Tests that the network delegate can block and cancel a request.
3108TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3109 ASSERT_TRUE(test_server_.Start());
3110
3111 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303112 BlockingNetworkDelegate network_delegate(
3113 BlockingNetworkDelegate::AUTO_CALLBACK);
3114 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3115 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123116
[email protected]d5a4dd62012-05-23 01:41:043117 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193118 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503119
[email protected]4c76d7c2011-04-15 19:14:123120 {
[email protected]f7022f32014-08-21 16:32:193121 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363122 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123123
[email protected]f7022f32014-08-21 16:32:193124 r->Start();
[email protected]255620da2013-08-19 13:14:293125 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123126
[email protected]f7022f32014-08-21 16:32:193127 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153128 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193129 EXPECT_TRUE(r->proxy_server().IsEmpty());
3130 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123131 EXPECT_EQ(1, network_delegate.created_requests());
3132 EXPECT_EQ(0, network_delegate.destroyed_requests());
3133 }
3134 EXPECT_EQ(1, network_delegate.destroyed_requests());
3135}
3136
[email protected]b4438d32012-09-27 06:15:303137// Helper function for NetworkDelegateCancelRequestAsynchronously and
3138// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3139// delegate operating in |block_mode| and a request for |url|. It blocks the
3140// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3141void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3142 BlockingNetworkDelegate::Stage stage,
3143 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363144 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303145 BlockingNetworkDelegate network_delegate(block_mode);
3146 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3147 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363148
[email protected]b4438d32012-09-27 06:15:303149 TestURLRequestContext context(true);
3150 context.set_network_delegate(&network_delegate);
3151 context.Init();
[email protected]3cd384c602011-08-31 16:12:363152
3153 {
davidben151423e2015-03-23 18:48:363154 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363155
[email protected]f7022f32014-08-21 16:32:193156 r->Start();
[email protected]255620da2013-08-19 13:14:293157 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363158
[email protected]f7022f32014-08-21 16:32:193159 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153160 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193161 EXPECT_TRUE(r->proxy_server().IsEmpty());
3162 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363163 EXPECT_EQ(1, network_delegate.created_requests());
3164 EXPECT_EQ(0, network_delegate.destroyed_requests());
3165 }
3166 EXPECT_EQ(1, network_delegate.destroyed_requests());
3167}
3168
[email protected]b4438d32012-09-27 06:15:303169// The following 3 tests check that the network delegate can cancel a request
3170// synchronously in various stages of the request.
3171TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3172 ASSERT_TRUE(test_server_.Start());
3173 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3174 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453175 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303176}
3177
3178TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3179 ASSERT_TRUE(test_server_.Start());
3180 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3181 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453182 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303183}
3184
3185TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3186 ASSERT_TRUE(test_server_.Start());
3187 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3188 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453189 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303190}
3191
3192// The following 3 tests check that the network delegate can cancel a request
3193// asynchronously in various stages of the request.
3194TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3195 ASSERT_TRUE(test_server_.Start());
3196 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3197 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453198 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303199}
3200
3201TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3202 ASSERT_TRUE(test_server_.Start());
3203 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3204 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453205 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303206}
3207
3208TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3209 ASSERT_TRUE(test_server_.Start());
3210 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3211 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453212 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303213}
3214
[email protected]4c76d7c2011-04-15 19:14:123215// Tests that the network delegate can block and redirect a request to a new
3216// URL.
3217TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3218 ASSERT_TRUE(test_server_.Start());
3219
3220 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303221 BlockingNetworkDelegate network_delegate(
3222 BlockingNetworkDelegate::AUTO_CALLBACK);
3223 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123224 GURL redirect_url(test_server_.GetURL("simple.html"));
3225 network_delegate.set_redirect_url(redirect_url);
3226
[email protected]d5a4dd62012-05-23 01:41:043227 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193228 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503229
[email protected]4c76d7c2011-04-15 19:14:123230 {
[email protected]8f1ac082011-04-19 21:14:133231 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363232 scoped_ptr<URLRequest> r(
3233 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123234
[email protected]6be6fa92014-08-06 23:44:563235 // Quit after hitting the redirect, so can check the headers.
3236 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193237 r->Start();
[email protected]255620da2013-08-19 13:14:293238 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123239
[email protected]6be6fa92014-08-06 23:44:563240 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193241 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3242 EXPECT_EQ(307, r->GetResponseCode());
3243 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563244 std::string location;
[email protected]f7022f32014-08-21 16:32:193245 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3246 &location));
[email protected]6be6fa92014-08-06 23:44:563247 EXPECT_EQ(redirect_url, GURL(location));
3248
3249 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193250 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563251 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193252 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3253 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273254 EXPECT_EQ(
3255 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3256 EXPECT_TRUE(
3257 network_delegate.last_observed_proxy().Equals(
3258 test_server_.host_port_pair()));
3259
[email protected]f7022f32014-08-21 16:32:193260 EXPECT_EQ(0, r->status().error());
3261 EXPECT_EQ(redirect_url, r->url());
3262 EXPECT_EQ(original_url, r->original_url());
3263 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123264 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
[email protected]b813ed72012-04-05 08:21:363270// Tests that the network delegate can block and redirect a request to a new
3271// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3272TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3273 ASSERT_TRUE(test_server_.Start());
3274
3275 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303276 BlockingNetworkDelegate network_delegate(
3277 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363278 GURL redirect_url(test_server_.GetURL("simple.html"));
3279 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363280
[email protected]d5a4dd62012-05-23 01:41:043281 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193282 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363283
3284 {
3285 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363286 scoped_ptr<URLRequest> r(
3287 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363288
[email protected]6be6fa92014-08-06 23:44:563289 // Quit after hitting the redirect, so can check the headers.
3290 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193291 r->Start();
[email protected]255620da2013-08-19 13:14:293292 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363293
[email protected]6be6fa92014-08-06 23:44:563294 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193295 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3296 EXPECT_EQ(307, r->GetResponseCode());
3297 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563298 std::string location;
[email protected]f7022f32014-08-21 16:32:193299 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3300 &location));
[email protected]6be6fa92014-08-06 23:44:563301 EXPECT_EQ(redirect_url, GURL(location));
3302
3303 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193304 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563305 base::RunLoop().Run();
3306
[email protected]f7022f32014-08-21 16:32:193307 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3308 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273309 EXPECT_EQ(
3310 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3311 EXPECT_TRUE(
3312 network_delegate.last_observed_proxy().Equals(
3313 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193314 EXPECT_EQ(0, r->status().error());
3315 EXPECT_EQ(redirect_url, r->url());
3316 EXPECT_EQ(original_url, r->original_url());
3317 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363318 EXPECT_EQ(1, network_delegate.created_requests());
3319 EXPECT_EQ(0, network_delegate.destroyed_requests());
3320 }
3321 EXPECT_EQ(1, network_delegate.destroyed_requests());
3322}
3323
[email protected]3c5ca8c2011-09-29 01:14:513324// Tests that redirects caused by the network delegate preserve POST data.
3325TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3326 ASSERT_TRUE(test_server_.Start());
3327
3328 const char kData[] = "hello world";
3329
3330 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303331 BlockingNetworkDelegate network_delegate(
3332 BlockingNetworkDelegate::AUTO_CALLBACK);
3333 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513334 GURL redirect_url(test_server_.GetURL("echo"));
3335 network_delegate.set_redirect_url(redirect_url);
3336
[email protected]ef2bf422012-05-11 03:27:093337 TestURLRequestContext context(true);
3338 context.set_network_delegate(&network_delegate);
3339 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513340
3341 {
3342 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363343 scoped_ptr<URLRequest> r(
3344 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193345 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073346 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513347 HttpRequestHeaders headers;
3348 headers.SetHeader(HttpRequestHeaders::kContentLength,
3349 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193350 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563351
3352 // Quit after hitting the redirect, so can check the headers.
3353 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193354 r->Start();
[email protected]255620da2013-08-19 13:14:293355 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513356
[email protected]6be6fa92014-08-06 23:44:563357 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193358 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3359 EXPECT_EQ(307, r->GetResponseCode());
3360 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563361 std::string location;
[email protected]f7022f32014-08-21 16:32:193362 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3363 &location));
[email protected]6be6fa92014-08-06 23:44:563364 EXPECT_EQ(redirect_url, GURL(location));
3365
3366 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193367 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563368 base::RunLoop().Run();
3369
[email protected]f7022f32014-08-21 16:32:193370 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3371 EXPECT_EQ(0, r->status().error());
3372 EXPECT_EQ(redirect_url, r->url());
3373 EXPECT_EQ(original_url, r->original_url());
3374 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513375 EXPECT_EQ(1, network_delegate.created_requests());
3376 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193377 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513378 EXPECT_EQ(kData, d.data_received());
3379 }
3380 EXPECT_EQ(1, network_delegate.destroyed_requests());
3381}
3382
[email protected]5f714132014-03-26 10:41:163383// Tests that the network delegate can block and redirect a request to a new
3384// URL during OnHeadersReceived.
3385TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3386 ASSERT_TRUE(test_server_.Start());
3387
3388 TestDelegate d;
3389 BlockingNetworkDelegate network_delegate(
3390 BlockingNetworkDelegate::AUTO_CALLBACK);
3391 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3392 GURL redirect_url(test_server_.GetURL("simple.html"));
3393 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3394
3395 TestURLRequestContextWithProxy context(
3396 test_server_.host_port_pair().ToString(), &network_delegate);
3397
3398 {
3399 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363400 scoped_ptr<URLRequest> r(
3401 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163402
[email protected]f7022f32014-08-21 16:32:193403 r->Start();
[email protected]5f714132014-03-26 10:41:163404 base::RunLoop().Run();
3405
[email protected]f7022f32014-08-21 16:32:193406 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3407 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273408 EXPECT_EQ(
3409 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3410 EXPECT_TRUE(
3411 network_delegate.last_observed_proxy().Equals(
3412 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193413
3414 EXPECT_EQ(OK, r->status().error());
3415 EXPECT_EQ(redirect_url, r->url());
3416 EXPECT_EQ(original_url, r->original_url());
3417 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163418 EXPECT_EQ(2, network_delegate.created_requests());
3419 EXPECT_EQ(0, network_delegate.destroyed_requests());
3420 }
3421 EXPECT_EQ(1, network_delegate.destroyed_requests());
3422}
3423
[email protected]c2911d72011-10-03 22:16:363424// Tests that the network delegate can synchronously complete OnAuthRequired
3425// by taking no action. This indicates that the NetworkDelegate does not want to
3426// handle the challenge, and is passing the buck along to the
3427// URLRequest::Delegate.
3428TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3429 ASSERT_TRUE(test_server_.Start());
3430
3431 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303432 BlockingNetworkDelegate network_delegate(
3433 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363434
[email protected]ef2bf422012-05-11 03:27:093435 TestURLRequestContext context(true);
3436 context.set_network_delegate(&network_delegate);
3437 context.Init();
[email protected]c2911d72011-10-03 22:16:363438
[email protected]f3cf9802011-10-28 18:44:583439 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363440
3441 {
3442 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363443 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193444 r->Start();
[email protected]79e1fd62013-06-20 06:50:043445
[email protected]255620da2013-08-19 13:14:293446 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043447
[email protected]f7022f32014-08-21 16:32:193448 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3449 EXPECT_EQ(0, r->status().error());
3450 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043451 EXPECT_TRUE(d.auth_required_called());
3452 EXPECT_EQ(1, network_delegate.created_requests());
3453 EXPECT_EQ(0, network_delegate.destroyed_requests());
3454 }
3455 EXPECT_EQ(1, network_delegate.destroyed_requests());
3456}
3457
3458TEST_F(URLRequestTestHTTP,
3459 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3460 ASSERT_TRUE(test_server_.Start());
3461
3462 TestDelegate d;
3463 BlockingNetworkDelegate network_delegate(
3464 BlockingNetworkDelegate::SYNCHRONOUS);
3465
3466 TestURLRequestContext context(true);
3467 context.set_network_delegate(&network_delegate);
3468 context.Init();
3469
3470 d.set_credentials(AuthCredentials(kUser, kSecret));
3471
3472 {
3473 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363474 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193475 r->Start();
[email protected]79e1fd62013-06-20 06:50:043476
3477 {
3478 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193479 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043480 EXPECT_FALSE(headers.HasHeader("Authorization"));
3481 }
3482
[email protected]255620da2013-08-19 13:14:293483 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363484
[email protected]f7022f32014-08-21 16:32:193485 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3486 EXPECT_EQ(0, r->status().error());
3487 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363488 EXPECT_TRUE(d.auth_required_called());
3489 EXPECT_EQ(1, network_delegate.created_requests());
3490 EXPECT_EQ(0, network_delegate.destroyed_requests());
3491 }
3492 EXPECT_EQ(1, network_delegate.destroyed_requests());
3493}
3494
3495// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403496// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363497TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3498 ASSERT_TRUE(test_server_.Start());
3499
3500 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303501 BlockingNetworkDelegate network_delegate(
3502 BlockingNetworkDelegate::SYNCHRONOUS);
3503 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363504 network_delegate.set_auth_retval(
3505 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3506
[email protected]f3cf9802011-10-28 18:44:583507 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363508
[email protected]ef2bf422012-05-11 03:27:093509 TestURLRequestContext context(true);
3510 context.set_network_delegate(&network_delegate);
3511 context.Init();
[email protected]c2911d72011-10-03 22:16:363512
3513 {
3514 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363515 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193516 r->Start();
[email protected]255620da2013-08-19 13:14:293517 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363518
[email protected]f7022f32014-08-21 16:32:193519 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3520 EXPECT_EQ(0, r->status().error());
3521 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363522 EXPECT_FALSE(d.auth_required_called());
3523 EXPECT_EQ(1, network_delegate.created_requests());
3524 EXPECT_EQ(0, network_delegate.destroyed_requests());
3525 }
3526 EXPECT_EQ(1, network_delegate.destroyed_requests());
3527}
3528
[email protected]79e1fd62013-06-20 06:50:043529// Same as above, but also tests that GetFullRequestHeaders returns the proper
3530// headers (for the first or second request) when called at the proper times.
3531TEST_F(URLRequestTestHTTP,
3532 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3533 ASSERT_TRUE(test_server_.Start());
3534
3535 TestDelegate d;
3536 BlockingNetworkDelegate network_delegate(
3537 BlockingNetworkDelegate::SYNCHRONOUS);
3538 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3539 network_delegate.set_auth_retval(
3540 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3541
3542 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3543
3544 TestURLRequestContext context(true);
3545 context.set_network_delegate(&network_delegate);
3546 context.Init();
3547
3548 {
3549 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363550 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193551 r->Start();
[email protected]255620da2013-08-19 13:14:293552 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043553
[email protected]f7022f32014-08-21 16:32:193554 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3555 EXPECT_EQ(0, r->status().error());
3556 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043557 EXPECT_FALSE(d.auth_required_called());
3558 EXPECT_EQ(1, network_delegate.created_requests());
3559 EXPECT_EQ(0, network_delegate.destroyed_requests());
3560
3561 {
3562 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193563 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043564 EXPECT_TRUE(headers.HasHeader("Authorization"));
3565 }
3566 }
3567 EXPECT_EQ(1, network_delegate.destroyed_requests());
3568}
3569
[email protected]c2911d72011-10-03 22:16:363570// Tests that the network delegate can synchronously complete OnAuthRequired
3571// by cancelling authentication.
3572TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3573 ASSERT_TRUE(test_server_.Start());
3574
3575 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303576 BlockingNetworkDelegate network_delegate(
3577 BlockingNetworkDelegate::SYNCHRONOUS);
3578 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363579 network_delegate.set_auth_retval(
3580 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3581
[email protected]ef2bf422012-05-11 03:27:093582 TestURLRequestContext context(true);
3583 context.set_network_delegate(&network_delegate);
3584 context.Init();
[email protected]c2911d72011-10-03 22:16:363585
3586 {
3587 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363588 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193589 r->Start();
[email protected]255620da2013-08-19 13:14:293590 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363591
[email protected]f7022f32014-08-21 16:32:193592 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3593 EXPECT_EQ(OK, r->status().error());
3594 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363595 EXPECT_FALSE(d.auth_required_called());
3596 EXPECT_EQ(1, network_delegate.created_requests());
3597 EXPECT_EQ(0, network_delegate.destroyed_requests());
3598 }
3599 EXPECT_EQ(1, network_delegate.destroyed_requests());
3600}
3601
3602// Tests that the network delegate can asynchronously complete OnAuthRequired
3603// by taking no action. This indicates that the NetworkDelegate does not want
3604// to handle the challenge, and is passing the buck along to the
3605// URLRequest::Delegate.
3606TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3607 ASSERT_TRUE(test_server_.Start());
3608
3609 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303610 BlockingNetworkDelegate network_delegate(
3611 BlockingNetworkDelegate::AUTO_CALLBACK);
3612 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363613
[email protected]ef2bf422012-05-11 03:27:093614 TestURLRequestContext context(true);
3615 context.set_network_delegate(&network_delegate);
3616 context.Init();
[email protected]c2911d72011-10-03 22:16:363617
[email protected]f3cf9802011-10-28 18:44:583618 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363619
3620 {
3621 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363622 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193623 r->Start();
[email protected]255620da2013-08-19 13:14:293624 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363625
[email protected]f7022f32014-08-21 16:32:193626 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3627 EXPECT_EQ(0, r->status().error());
3628 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363629 EXPECT_TRUE(d.auth_required_called());
3630 EXPECT_EQ(1, network_delegate.created_requests());
3631 EXPECT_EQ(0, network_delegate.destroyed_requests());
3632 }
3633 EXPECT_EQ(1, network_delegate.destroyed_requests());
3634}
3635
3636// Tests that the network delegate can asynchronously complete OnAuthRequired
3637// by setting credentials.
3638TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3639 ASSERT_TRUE(test_server_.Start());
3640
3641 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303642 BlockingNetworkDelegate network_delegate(
3643 BlockingNetworkDelegate::AUTO_CALLBACK);
3644 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363645 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363646 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3647
[email protected]f3cf9802011-10-28 18:44:583648 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363649 network_delegate.set_auth_credentials(auth_credentials);
3650
[email protected]ef2bf422012-05-11 03:27:093651 TestURLRequestContext context(true);
3652 context.set_network_delegate(&network_delegate);
3653 context.Init();
[email protected]c2911d72011-10-03 22:16:363654
3655 {
3656 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363657 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193658 r->Start();
[email protected]255620da2013-08-19 13:14:293659 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363660
[email protected]f7022f32014-08-21 16:32:193661 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3662 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363663
[email protected]f7022f32014-08-21 16:32:193664 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363665 EXPECT_FALSE(d.auth_required_called());
3666 EXPECT_EQ(1, network_delegate.created_requests());
3667 EXPECT_EQ(0, network_delegate.destroyed_requests());
3668 }
3669 EXPECT_EQ(1, network_delegate.destroyed_requests());
3670}
3671
3672// Tests that the network delegate can asynchronously complete OnAuthRequired
3673// by cancelling authentication.
3674TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3675 ASSERT_TRUE(test_server_.Start());
3676
3677 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303678 BlockingNetworkDelegate network_delegate(
3679 BlockingNetworkDelegate::AUTO_CALLBACK);
3680 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363681 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363682 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3683
[email protected]ef2bf422012-05-11 03:27:093684 TestURLRequestContext context(true);
3685 context.set_network_delegate(&network_delegate);
3686 context.Init();
[email protected]c2911d72011-10-03 22:16:363687
3688 {
3689 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363690 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193691 r->Start();
[email protected]255620da2013-08-19 13:14:293692 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363693
[email protected]f7022f32014-08-21 16:32:193694 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3695 EXPECT_EQ(OK, r->status().error());
3696 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363697 EXPECT_FALSE(d.auth_required_called());
3698 EXPECT_EQ(1, network_delegate.created_requests());
3699 EXPECT_EQ(0, network_delegate.destroyed_requests());
3700 }
3701 EXPECT_EQ(1, network_delegate.destroyed_requests());
3702}
3703
[email protected]9045b8822012-01-13 20:35:353704// Tests that we can handle when a network request was canceled while we were
3705// waiting for the network delegate.
3706// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3707TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3708 ASSERT_TRUE(test_server_.Start());
3709
3710 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303711 BlockingNetworkDelegate network_delegate(
3712 BlockingNetworkDelegate::USER_CALLBACK);
3713 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353714
[email protected]ef2bf422012-05-11 03:27:093715 TestURLRequestContext context(true);
3716 context.set_network_delegate(&network_delegate);
3717 context.Init();
[email protected]9045b8822012-01-13 20:35:353718
3719 {
[email protected]f7022f32014-08-21 16:32:193720 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363721 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353722
[email protected]f7022f32014-08-21 16:32:193723 r->Start();
[email protected]255620da2013-08-19 13:14:293724 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303725 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3726 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353727 EXPECT_EQ(0, network_delegate.completed_requests());
3728 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193729 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353730 // Ensure that network delegate is notified.
3731 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193732 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3733 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353734 EXPECT_EQ(1, network_delegate.created_requests());
3735 EXPECT_EQ(0, network_delegate.destroyed_requests());
3736 }
3737 EXPECT_EQ(1, network_delegate.destroyed_requests());
3738}
3739
3740// Tests that we can handle when a network request was canceled while we were
3741// waiting for the network delegate.
3742// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3743TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3744 ASSERT_TRUE(test_server_.Start());
3745
3746 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303747 BlockingNetworkDelegate network_delegate(
3748 BlockingNetworkDelegate::USER_CALLBACK);
3749 network_delegate.set_block_on(
3750 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353751
[email protected]ef2bf422012-05-11 03:27:093752 TestURLRequestContext context(true);
3753 context.set_network_delegate(&network_delegate);
3754 context.Init();
[email protected]9045b8822012-01-13 20:35:353755
3756 {
[email protected]f7022f32014-08-21 16:32:193757 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363758 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353759
[email protected]f7022f32014-08-21 16:32:193760 r->Start();
[email protected]255620da2013-08-19 13:14:293761 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303762 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3763 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353764 EXPECT_EQ(0, network_delegate.completed_requests());
3765 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193766 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353767 // Ensure that network delegate is notified.
3768 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193769 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3770 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353771 EXPECT_EQ(1, network_delegate.created_requests());
3772 EXPECT_EQ(0, network_delegate.destroyed_requests());
3773 }
3774 EXPECT_EQ(1, network_delegate.destroyed_requests());
3775}
3776
3777// Tests that we can handle when a network request was canceled while we were
3778// waiting for the network delegate.
3779// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3780TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3781 ASSERT_TRUE(test_server_.Start());
3782
3783 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303784 BlockingNetworkDelegate network_delegate(
3785 BlockingNetworkDelegate::USER_CALLBACK);
3786 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353787
[email protected]ef2bf422012-05-11 03:27:093788 TestURLRequestContext context(true);
3789 context.set_network_delegate(&network_delegate);
3790 context.Init();
[email protected]9045b8822012-01-13 20:35:353791
3792 {
[email protected]f7022f32014-08-21 16:32:193793 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363794 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353795
[email protected]f7022f32014-08-21 16:32:193796 r->Start();
[email protected]255620da2013-08-19 13:14:293797 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303798 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3799 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353800 EXPECT_EQ(0, network_delegate.completed_requests());
3801 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193802 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353803 // Ensure that network delegate is notified.
3804 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193805 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3806 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353807 EXPECT_EQ(1, network_delegate.created_requests());
3808 EXPECT_EQ(0, network_delegate.destroyed_requests());
3809 }
3810 EXPECT_EQ(1, network_delegate.destroyed_requests());
3811}
3812
3813// Tests that we can handle when a network request was canceled while we were
3814// waiting for the network delegate.
3815// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023816TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353817 ASSERT_TRUE(test_server_.Start());
3818
3819 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303820 BlockingNetworkDelegate network_delegate(
3821 BlockingNetworkDelegate::USER_CALLBACK);
3822 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353823
[email protected]ef2bf422012-05-11 03:27:093824 TestURLRequestContext context(true);
3825 context.set_network_delegate(&network_delegate);
3826 context.Init();
[email protected]9045b8822012-01-13 20:35:353827
3828 {
[email protected]f7022f32014-08-21 16:32:193829 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363830 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353831
[email protected]f7022f32014-08-21 16:32:193832 r->Start();
[email protected]255620da2013-08-19 13:14:293833 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303834 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3835 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353836 EXPECT_EQ(0, network_delegate.completed_requests());
3837 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193838 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353839 // Ensure that network delegate is notified.
3840 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193841 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3842 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353843 EXPECT_EQ(1, network_delegate.created_requests());
3844 EXPECT_EQ(0, network_delegate.destroyed_requests());
3845 }
3846 EXPECT_EQ(1, network_delegate.destroyed_requests());
3847}
3848
[email protected]95409e12010-08-17 20:07:113849// In this unit test, we're using the HTTPTestServer as a proxy server and
3850// issuing a CONNECT request with the magic host name "www.server-auth.com".
3851// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353852TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113853 ASSERT_TRUE(test_server_.Start());
3854
[email protected]ceefd7fd2012-11-29 00:36:243855 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043856 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193857 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503858
[email protected]dc651782009-02-14 01:45:083859 TestDelegate d;
3860 {
[email protected]f7022f32014-08-21 16:32:193861 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363862 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:083863
[email protected]f7022f32014-08-21 16:32:193864 r->Start();
3865 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:083866
[email protected]255620da2013-08-19 13:14:293867 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083868
[email protected]f7022f32014-08-21 16:32:193869 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153870 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193871 EXPECT_TRUE(r->proxy_server().IsEmpty());
3872 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083873 }
3874}
3875
[email protected]b89290212009-08-14 22:37:353876TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113877 ASSERT_TRUE(test_server_.Start());
3878
initial.commit586acc5fe2008-07-26 22:42:523879 TestDelegate d;
3880 {
[email protected]f7022f32014-08-21 16:32:193881 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363882 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523883
[email protected]f7022f32014-08-21 16:32:193884 r->Start();
3885 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523886
[email protected]255620da2013-08-19 13:14:293887 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523888
3889 EXPECT_EQ(1, d.response_started_count());
3890 EXPECT_FALSE(d.received_data_before_response());
3891 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193892 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193893 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193894 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193895 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163896
[email protected]9e743cd2010-03-16 07:03:533897 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523898 }
initial.commit586acc5fe2008-07-26 22:42:523899}
3900
[email protected]263163f2012-06-14 22:40:343901// This test has the server send a large number of cookies to the client.
3902// To ensure that no number of cookies causes a crash, a galloping binary
3903// search is used to estimate that maximum number of cookies that are accepted
3904// by the browser. Beyond the maximum number, the request will fail with
3905// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303906#if defined(OS_WIN)
3907// http://crbug.com/177916
3908#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3909#else
3910#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3911#endif // defined(OS_WIN)
3912TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343913 ASSERT_TRUE(test_server_.Start());
3914
3915 int lower_bound = 0;
3916 int upper_bound = 1;
3917
3918 // Double the number of cookies until the response header limits are
3919 // exceeded.
3920 while (DoManyCookiesRequest(upper_bound)) {
3921 lower_bound = upper_bound;
3922 upper_bound *= 2;
3923 ASSERT_LT(upper_bound, 1000000);
3924 }
3925
pkasting6b68a162014-12-01 22:10:293926 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:343927 if (tolerance < 2)
3928 tolerance = 2;
3929
3930 // Perform a binary search to find the highest possible number of cookies,
3931 // within the desired tolerance.
3932 while (upper_bound - lower_bound >= tolerance) {
3933 int num_cookies = (lower_bound + upper_bound) / 2;
3934
3935 if (DoManyCookiesRequest(num_cookies))
3936 lower_bound = num_cookies;
3937 else
3938 upper_bound = num_cookies;
3939 }
3940 // Success: the test did not crash.
3941}
3942
[email protected]b89290212009-08-14 22:37:353943TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113944 ASSERT_TRUE(test_server_.Start());
3945
initial.commit586acc5fe2008-07-26 22:42:523946 TestDelegate d;
3947 {
[email protected]f7022f32014-08-21 16:32:193948 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363949 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523950
[email protected]f7022f32014-08-21 16:32:193951 r->Start();
3952 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523953
[email protected]255620da2013-08-19 13:14:293954 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523955
3956 EXPECT_EQ(1, d.response_started_count());
3957 EXPECT_FALSE(d.received_data_before_response());
3958 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193959 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193960 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193961 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193962 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523963 }
[email protected]5d7b373e2009-09-02 07:19:033964}
3965
[email protected]79e1fd62013-06-20 06:50:043966TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3967 ASSERT_TRUE(test_server_.Start());
3968
3969 TestDelegate d;
3970 {
3971 GURL test_url(test_server_.GetURL(std::string()));
davidben151423e2015-03-23 18:48:363972 scoped_ptr<URLRequest> r(
3973 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:043974
3975 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193976 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043977
[email protected]f7022f32014-08-21 16:32:193978 r->Start();
3979 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:043980
[email protected]255620da2013-08-19 13:14:293981 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043982
3983 EXPECT_EQ(1, d.response_started_count());
3984 EXPECT_FALSE(d.received_data_before_response());
3985 EXPECT_NE(0, d.bytes_received());
3986 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193987 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:043988 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193989 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:043990
3991 EXPECT_TRUE(d.have_full_request_headers());
3992 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3993 }
3994}
3995
[email protected]58e32bb2013-01-21 18:23:253996TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3997 ASSERT_TRUE(test_server_.Start());
3998
3999 TestDelegate d;
4000 {
[email protected]f7022f32014-08-21 16:32:194001 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364002 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254003
[email protected]f7022f32014-08-21 16:32:194004 r->Start();
4005 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254006
[email protected]255620da2013-08-19 13:14:294007 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254008
4009 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194010 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254011 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4012
4013 EXPECT_EQ(1, d.response_started_count());
4014 EXPECT_FALSE(d.received_data_before_response());
4015 EXPECT_NE(0, d.bytes_received());
4016 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194017 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:254018 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194019 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254020 }
4021}
4022
[email protected]aad63572011-05-24 20:14:394023TEST_F(URLRequestTestHTTP, GetZippedTest) {
4024 ASSERT_TRUE(test_server_.Start());
4025
4026 // Parameter that specifies the Content-Length field in the response:
4027 // C - Compressed length.
4028 // U - Uncompressed length.
4029 // L - Large length (larger than both C & U).
4030 // M - Medium length (between C & U).
4031 // S - Small length (smaller than both C & U).
4032 const char test_parameters[] = "CULMS";
4033 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4034 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444035 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394036 // S has too little data, but we seem to accept it.
4037 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374038 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394039
4040 for (int i = 0; i < num_tests ; i++) {
4041 TestDelegate d;
4042 {
4043 std::string test_file =
4044 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4045 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394046
[email protected]ceefd7fd2012-11-29 00:36:244047 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094048 TestURLRequestContext context(true);
4049 context.set_network_delegate(&network_delegate);
4050 context.Init();
[email protected]87a09a92011-07-14 15:50:504051
[email protected]f7022f32014-08-21 16:32:194052 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364053 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194054 r->Start();
4055 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394056
[email protected]255620da2013-08-19 13:14:294057 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394058
4059 EXPECT_EQ(1, d.response_started_count());
4060 EXPECT_FALSE(d.received_data_before_response());
4061 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194062 << " status = " << r->status().status()
4063 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394064 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194065 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394066 << " Parameter = \"" << test_file << "\"";
4067 } else {
[email protected]f7022f32014-08-21 16:32:194068 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4069 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394070 << " Parameter = \"" << test_file << "\"";
4071 }
4072 }
4073 }
4074}
4075
tbansala1caf9612015-06-01 20:24:184076TEST_F(URLRequestTestHTTP, NetworkQualityEstimator) {
tbansalea2fb8c2015-05-22 22:23:004077 ASSERT_TRUE(test_server_.Start());
4078 // Enable requests to local host to be used for network quality estimation.
4079 NetworkQualityEstimator estimator(true);
4080
4081 TestDelegate d;
4082 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
4083 TestURLRequestContext context(true);
4084 context.set_network_quality_estimator(&estimator);
4085 context.set_network_delegate(&network_delegate);
4086 context.Init();
4087
4088 uint64_t min_transfer_size_in_bytes =
4089 NetworkQualityEstimator::kMinTransferSizeInBytes;
4090 // Create a long enough URL such that response size exceeds network quality
4091 // estimator's minimum transfer size.
4092 std::string url = "echo.html?";
4093 url.append(min_transfer_size_in_bytes, 'x');
4094
4095 scoped_ptr<URLRequest> r(
4096 context.CreateRequest(test_server_.GetURL(url), DEFAULT_PRIORITY, &d));
4097 int sleep_duration_milliseconds = 1;
4098 base::PlatformThread::Sleep(
4099 base::TimeDelta::FromMilliseconds(sleep_duration_milliseconds));
4100 r->Start();
4101
4102 base::RunLoop().Run();
4103
4104 NetworkQuality network_quality =
4105 context.network_quality_estimator()->GetEstimate();
4106 EXPECT_GE(network_quality.fastest_rtt,
4107 base::TimeDelta::FromMilliseconds(sleep_duration_milliseconds));
4108 EXPECT_GT(network_quality.fastest_rtt_confidence, 0);
4109 EXPECT_GT(network_quality.peak_throughput_kbps, uint64_t(0));
4110 EXPECT_GT(network_quality.peak_throughput_kbps_confidence, 0);
4111
4112 // Verify that histograms are not populated. They should populate only when
4113 // there is a change in ConnectionType.
4114 base::HistogramTester histogram_tester;
4115 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 0);
4116 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 0);
4117
4118 NetworkChangeNotifier::NotifyObserversOfConnectionTypeChangeForTests(
4119 NetworkChangeNotifier::ConnectionType::CONNECTION_WIFI);
4120 base::MessageLoop::current()->RunUntilIdle();
4121 histogram_tester.ExpectTotalCount("NQE.PeakKbps.Unknown", 1);
4122 histogram_tester.ExpectTotalCount("NQE.FastestRTT.Unknown", 1);
4123}
4124
[email protected]58e32bb2013-01-21 18:23:254125TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4126 ASSERT_TRUE(test_server_.Start());
4127
[email protected]007b3f82013-04-09 08:46:454128 GURL destination_url = test_server_.GetURL(std::string());
4129 GURL original_url =
4130 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254131 TestDelegate d;
davidben151423e2015-03-23 18:48:364132 scoped_ptr<URLRequest> req(
4133 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194134 req->Start();
[email protected]255620da2013-08-19 13:14:294135 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254136
4137 EXPECT_EQ(1, d.response_started_count());
4138 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194139 EXPECT_EQ(destination_url, req->url());
4140 EXPECT_EQ(original_url, req->original_url());
4141 ASSERT_EQ(2U, req->url_chain().size());
4142 EXPECT_EQ(original_url, req->url_chain()[0]);
4143 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254144
4145 LoadTimingInfo load_timing_info_before_redirect;
4146 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4147 &load_timing_info_before_redirect));
4148 TestLoadTimingNotReused(load_timing_info_before_redirect,
4149 CONNECT_TIMING_HAS_DNS_TIMES);
4150
4151 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194152 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254153 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4154
4155 // Check that a new socket was used on redirect, since the server does not
4156 // supposed keep-alive sockets, and that the times before the redirect are
4157 // before the ones recorded for the second request.
4158 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4159 load_timing_info.socket_log_id);
4160 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4161 load_timing_info.connect_timing.connect_start);
4162}
4163
[email protected]8f1ac082011-04-19 21:14:134164TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4165 ASSERT_TRUE(test_server_.Start());
4166
[email protected]007b3f82013-04-09 08:46:454167 GURL destination_url = test_server_.GetURL(std::string());
4168 GURL middle_redirect_url =
4169 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134170 GURL original_url = test_server_.GetURL(
4171 "server-redirect?" + middle_redirect_url.spec());
4172 TestDelegate d;
davidben151423e2015-03-23 18:48:364173 scoped_ptr<URLRequest> req(
4174 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194175 req->Start();
[email protected]255620da2013-08-19 13:14:294176 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134177
4178 EXPECT_EQ(1, d.response_started_count());
4179 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194180 EXPECT_EQ(destination_url, req->url());
4181 EXPECT_EQ(original_url, req->original_url());
4182 ASSERT_EQ(3U, req->url_chain().size());
4183 EXPECT_EQ(original_url, req->url_chain()[0]);
4184 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4185 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134186}
4187
[email protected]abe1c4a2013-10-25 19:28:514188// First and second pieces of information logged by delegates to URLRequests.
4189const char kFirstDelegateInfo[] = "Wonderful delegate";
4190const char kSecondDelegateInfo[] = "Exciting delegate";
4191
4192// Logs delegate information to a URLRequest. The first string is logged
4193// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4194// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4195// another asynchronous call is used to clear the delegate information
4196// before calling a callback. The object then deletes itself.
4197class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4198 public:
4199 typedef base::Callback<void()> Callback;
4200
4201 // Each time delegate information is added to the URLRequest, the resulting
4202 // load state is checked. The expected load state after each request is
4203 // passed in as an argument.
4204 static void Run(URLRequest* url_request,
4205 LoadState expected_first_load_state,
4206 LoadState expected_second_load_state,
4207 LoadState expected_third_load_state,
4208 const Callback& callback) {
4209 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4210 url_request,
4211 expected_first_load_state,
4212 expected_second_load_state,
4213 expected_third_load_state,
4214 callback);
4215 logger->Start();
4216 }
4217
4218 // Checks that the log entries, starting with log_position, contain the
4219 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4220 // recorded. Returns the index of entry after the expected number of
4221 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464222 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514223 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514224 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4225 if (log_position + 3 >= entries.size()) {
4226 ADD_FAILURE() << "Not enough log entries";
4227 return entries.size();
4228 }
4229 std::string delegate_info;
4230 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4231 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4232 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4233 &delegate_info));
4234 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4235
4236 ++log_position;
4237 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4238 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4239
4240 ++log_position;
4241 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4242 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4243 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4244 &delegate_info));
4245 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4246
4247 ++log_position;
4248 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4249 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4250
4251 return log_position + 1;
4252 }
4253
[email protected]1826a402014-01-08 15:40:484254 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4255 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464256 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4257 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484258 log_position =
4259 ExpectLogContainsSomewhereAfter(entries,
4260 log_position,
4261 NetLog::TYPE_URL_REQUEST_DELEGATE,
4262 NetLog::PHASE_BEGIN);
4263 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4264 entries[log_position + 1].type);
4265 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4266 return log_position + 1;
4267 }
4268
[email protected]abe1c4a2013-10-25 19:28:514269 private:
4270 friend class base::RefCounted<AsyncDelegateLogger>;
4271
4272 AsyncDelegateLogger(URLRequest* url_request,
4273 LoadState expected_first_load_state,
4274 LoadState expected_second_load_state,
4275 LoadState expected_third_load_state,
4276 const Callback& callback)
4277 : url_request_(url_request),
4278 expected_first_load_state_(expected_first_load_state),
4279 expected_second_load_state_(expected_second_load_state),
4280 expected_third_load_state_(expected_third_load_state),
4281 callback_(callback) {
4282 }
4283
4284 ~AsyncDelegateLogger() {}
4285
4286 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534287 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514288 LoadStateWithParam load_state = url_request_->GetLoadState();
4289 EXPECT_EQ(expected_first_load_state_, load_state.state);
4290 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4291 base::MessageLoop::current()->PostTask(
4292 FROM_HERE,
4293 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4294 }
4295
4296 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534297 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514298 LoadStateWithParam load_state = url_request_->GetLoadState();
4299 EXPECT_EQ(expected_second_load_state_, load_state.state);
4300 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4301 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4302 } else {
4303 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4304 }
4305 base::MessageLoop::current()->PostTask(
4306 FROM_HERE,
4307 base::Bind(&AsyncDelegateLogger::LogComplete, this));
4308 }
4309
4310 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534311 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514312 LoadStateWithParam load_state = url_request_->GetLoadState();
4313 EXPECT_EQ(expected_third_load_state_, load_state.state);
4314 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084315 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514316 callback_.Run();
4317 }
4318
4319 URLRequest* url_request_;
4320 const int expected_first_load_state_;
4321 const int expected_second_load_state_;
4322 const int expected_third_load_state_;
4323 const Callback callback_;
4324
4325 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4326};
4327
4328// NetworkDelegate that logs delegate information before a request is started,
4329// before headers are sent, when headers are read, and when auth information
4330// is requested. Uses AsyncDelegateLogger.
4331class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4332 public:
4333 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204334 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514335
4336 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204337 int OnBeforeURLRequest(URLRequest* request,
4338 const CompletionCallback& callback,
4339 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514340 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4341 return RunCallbackAsynchronously(request, callback);
4342 }
4343
dchengb03027d2014-10-21 12:00:204344 int OnBeforeSendHeaders(URLRequest* request,
4345 const CompletionCallback& callback,
4346 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514347 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4348 return RunCallbackAsynchronously(request, callback);
4349 }
4350
dchengb03027d2014-10-21 12:00:204351 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514352 URLRequest* request,
4353 const CompletionCallback& callback,
4354 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164355 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134356 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164357 TestNetworkDelegate::OnHeadersReceived(request,
4358 callback,
[email protected]abe1c4a2013-10-25 19:28:514359 original_response_headers,
[email protected]5f714132014-03-26 10:41:164360 override_response_headers,
4361 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514362 return RunCallbackAsynchronously(request, callback);
4363 }
4364
dchengb03027d2014-10-21 12:00:204365 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514366 URLRequest* request,
4367 const AuthChallengeInfo& auth_info,
4368 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134369 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514370 AsyncDelegateLogger::Run(
4371 request,
4372 LOAD_STATE_WAITING_FOR_DELEGATE,
4373 LOAD_STATE_WAITING_FOR_DELEGATE,
4374 LOAD_STATE_WAITING_FOR_DELEGATE,
4375 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4376 callback, credentials));
4377 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4378 }
4379
4380 private:
4381 static int RunCallbackAsynchronously(
4382 URLRequest* request,
4383 const CompletionCallback& callback) {
4384 AsyncDelegateLogger::Run(
4385 request,
4386 LOAD_STATE_WAITING_FOR_DELEGATE,
4387 LOAD_STATE_WAITING_FOR_DELEGATE,
4388 LOAD_STATE_WAITING_FOR_DELEGATE,
4389 base::Bind(callback, OK));
4390 return ERR_IO_PENDING;
4391 }
4392
4393 static void SetAuthAndResume(const AuthCallback& callback,
4394 AuthCredentials* credentials) {
4395 *credentials = AuthCredentials(kUser, kSecret);
4396 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4397 }
4398
4399 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4400};
4401
4402// URLRequest::Delegate that logs delegate information when the headers
4403// are received, when each read completes, and during redirects. Uses
4404// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4405//
4406// Inherits from TestDelegate to reuse the TestDelegate code to handle
4407// advancing to the next step in most cases, as well as cancellation.
4408class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4409 public:
4410 enum CancelStage {
4411 NO_CANCEL = 0,
4412 CANCEL_ON_RECEIVED_REDIRECT,
4413 CANCEL_ON_RESPONSE_STARTED,
4414 CANCEL_ON_READ_COMPLETED
4415 };
4416
4417 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4418 : cancel_stage_(cancel_stage) {
4419 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4420 set_cancel_in_received_redirect(true);
4421 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4422 set_cancel_in_response_started(true);
4423 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4424 set_cancel_in_received_data(true);
4425 }
dchengb03027d2014-10-21 12:00:204426 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514427
4428 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204429 void OnReceivedRedirect(URLRequest* request,
4430 const RedirectInfo& redirect_info,
4431 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514432 *defer_redirect = true;
4433 AsyncDelegateLogger::Run(
4434 request,
4435 LOAD_STATE_WAITING_FOR_DELEGATE,
4436 LOAD_STATE_WAITING_FOR_DELEGATE,
4437 LOAD_STATE_WAITING_FOR_DELEGATE,
4438 base::Bind(
4439 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594440 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514441 }
4442
dchengb03027d2014-10-21 12:00:204443 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514444 AsyncDelegateLogger::Run(
4445 request,
4446 LOAD_STATE_WAITING_FOR_DELEGATE,
4447 LOAD_STATE_WAITING_FOR_DELEGATE,
4448 LOAD_STATE_WAITING_FOR_DELEGATE,
4449 base::Bind(
4450 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4451 base::Unretained(this), request));
4452 }
4453
dchengb03027d2014-10-21 12:00:204454 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514455 AsyncDelegateLogger::Run(
4456 request,
4457 LOAD_STATE_IDLE,
4458 LOAD_STATE_IDLE,
4459 LOAD_STATE_IDLE,
4460 base::Bind(
4461 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4462 base::Unretained(this), request, bytes_read));
4463 }
4464
4465 private:
4466 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594467 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514468 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594469 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514470 // FollowDeferredRedirect should not be called after cancellation.
4471 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4472 return;
4473 if (!defer_redirect)
4474 request->FollowDeferredRedirect();
4475 }
4476
4477 void OnResponseStartedLoggingComplete(URLRequest* request) {
4478 // The parent class continues the request.
4479 TestDelegate::OnResponseStarted(request);
4480 }
4481
4482 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4483 // The parent class continues the request.
4484 TestDelegate::OnReadCompleted(request, bytes_read);
4485 }
4486
4487 const CancelStage cancel_stage_;
4488
4489 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4490};
4491
4492// Tests handling of delegate info before a request starts.
4493TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4494 ASSERT_TRUE(test_server_.Start());
4495
4496 TestDelegate request_delegate;
4497 TestURLRequestContext context(true);
4498 context.set_network_delegate(NULL);
4499 context.set_net_log(&net_log_);
4500 context.Init();
4501
4502 {
davidben151423e2015-03-23 18:48:364503 scoped_ptr<URLRequest> r(
4504 context.CreateRequest(test_server_.GetURL("empty.html"),
4505 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194506 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514507 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084508 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514509
4510 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194511 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514512 LOAD_STATE_WAITING_FOR_DELEGATE,
4513 LOAD_STATE_WAITING_FOR_DELEGATE,
4514 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194515 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514516
4517 base::RunLoop().Run();
4518
[email protected]f7022f32014-08-21 16:32:194519 EXPECT_EQ(200, r->GetResponseCode());
4520 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514521 }
4522
mmenke43758e62015-05-04 21:09:464523 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514524 net_log_.GetEntries(&entries);
4525 size_t log_position = ExpectLogContainsSomewhereAfter(
4526 entries,
4527 0,
4528 NetLog::TYPE_DELEGATE_INFO,
4529 NetLog::PHASE_BEGIN);
4530
4531 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4532
4533 // Nothing else should add any delegate info to the request.
4534 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4535 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4536}
4537
4538// Tests handling of delegate info from a network delegate.
4539TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4540 ASSERT_TRUE(test_server_.Start());
4541
4542 TestDelegate request_delegate;
4543 AsyncLoggingNetworkDelegate network_delegate;
4544 TestURLRequestContext context(true);
4545 context.set_network_delegate(&network_delegate);
4546 context.set_net_log(&net_log_);
4547 context.Init();
4548
4549 {
davidben151423e2015-03-23 18:48:364550 scoped_ptr<URLRequest> r(
4551 context.CreateRequest(test_server_.GetURL("simple.html"),
4552 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194553 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514554 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084555 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514556
[email protected]f7022f32014-08-21 16:32:194557 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514558 base::RunLoop().Run();
4559
[email protected]f7022f32014-08-21 16:32:194560 EXPECT_EQ(200, r->GetResponseCode());
4561 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514562 EXPECT_EQ(1, network_delegate.created_requests());
4563 EXPECT_EQ(0, network_delegate.destroyed_requests());
4564 }
4565 EXPECT_EQ(1, network_delegate.destroyed_requests());
4566
4567 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464568 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514569 net_log_.GetEntries(&entries);
4570 for (size_t i = 0; i < 3; ++i) {
4571 log_position = ExpectLogContainsSomewhereAfter(
4572 entries,
4573 log_position + 1,
4574 NetLog::TYPE_URL_REQUEST_DELEGATE,
4575 NetLog::PHASE_BEGIN);
4576
4577 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4578 log_position + 1);
4579
4580 ASSERT_LT(log_position, entries.size());
4581 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4582 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484583
4584 if (i == 1) {
4585 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4586 entries, log_position + 1);
4587 }
[email protected]abe1c4a2013-10-25 19:28:514588 }
4589
4590 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4591 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4592}
4593
4594// Tests handling of delegate info from a network delegate in the case of an
4595// HTTP redirect.
4596TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4597 ASSERT_TRUE(test_server_.Start());
4598
4599 TestDelegate request_delegate;
4600 AsyncLoggingNetworkDelegate network_delegate;
4601 TestURLRequestContext context(true);
4602 context.set_network_delegate(&network_delegate);
4603 context.set_net_log(&net_log_);
4604 context.Init();
4605
4606 {
[email protected]f7022f32014-08-21 16:32:194607 scoped_ptr<URLRequest> r(context.CreateRequest(
4608 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364609 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194610 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514611 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084612 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514613
[email protected]f7022f32014-08-21 16:32:194614 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514615 base::RunLoop().Run();
4616
[email protected]f7022f32014-08-21 16:32:194617 EXPECT_EQ(200, r->GetResponseCode());
4618 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514619 EXPECT_EQ(2, network_delegate.created_requests());
4620 EXPECT_EQ(0, network_delegate.destroyed_requests());
4621 }
4622 EXPECT_EQ(1, network_delegate.destroyed_requests());
4623
4624 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464625 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514626 net_log_.GetEntries(&entries);
4627 // The NetworkDelegate logged information in OnBeforeURLRequest,
4628 // OnBeforeSendHeaders, and OnHeadersReceived.
4629 for (size_t i = 0; i < 3; ++i) {
4630 log_position = ExpectLogContainsSomewhereAfter(
4631 entries,
4632 log_position + 1,
4633 NetLog::TYPE_URL_REQUEST_DELEGATE,
4634 NetLog::PHASE_BEGIN);
4635
4636 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4637 log_position + 1);
4638
4639 ASSERT_LT(log_position, entries.size());
4640 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4641 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484642
4643 if (i == 1) {
4644 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4645 entries, log_position + 1);
4646 }
[email protected]abe1c4a2013-10-25 19:28:514647 }
4648
4649 // The URLRequest::Delegate then gets informed about the redirect.
4650 log_position = ExpectLogContainsSomewhereAfter(
4651 entries,
4652 log_position + 1,
4653 NetLog::TYPE_URL_REQUEST_DELEGATE,
4654 NetLog::PHASE_BEGIN);
4655
4656 // The NetworkDelegate logged information in the same three events as before.
4657 for (size_t i = 0; i < 3; ++i) {
4658 log_position = ExpectLogContainsSomewhereAfter(
4659 entries,
4660 log_position + 1,
4661 NetLog::TYPE_URL_REQUEST_DELEGATE,
4662 NetLog::PHASE_BEGIN);
4663
4664 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4665 log_position + 1);
4666
4667 ASSERT_LT(log_position, entries.size());
4668 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4669 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4670 }
4671
4672 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4673 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4674}
4675
4676// Tests handling of delegate info from a network delegate in the case of HTTP
4677// AUTH.
4678TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4679 ASSERT_TRUE(test_server_.Start());
4680
4681 TestDelegate request_delegate;
4682 AsyncLoggingNetworkDelegate network_delegate;
4683 TestURLRequestContext context(true);
4684 context.set_network_delegate(&network_delegate);
4685 context.set_net_log(&net_log_);
4686 context.Init();
4687
4688 {
davidben151423e2015-03-23 18:48:364689 scoped_ptr<URLRequest> r(
4690 context.CreateRequest(test_server_.GetURL("auth-basic"),
4691 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194692 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514693 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084694 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514695
[email protected]f7022f32014-08-21 16:32:194696 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514697 base::RunLoop().Run();
4698
[email protected]f7022f32014-08-21 16:32:194699 EXPECT_EQ(200, r->GetResponseCode());
4700 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514701 EXPECT_EQ(1, network_delegate.created_requests());
4702 EXPECT_EQ(0, network_delegate.destroyed_requests());
4703 }
4704 EXPECT_EQ(1, network_delegate.destroyed_requests());
4705
4706 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:464707 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514708 net_log_.GetEntries(&entries);
4709 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4710 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4711 // OnBeforeURLRequest and OnBeforeSendHeaders.
4712 for (size_t i = 0; i < 6; ++i) {
4713 log_position = ExpectLogContainsSomewhereAfter(
4714 entries,
4715 log_position + 1,
4716 NetLog::TYPE_URL_REQUEST_DELEGATE,
4717 NetLog::PHASE_BEGIN);
4718
4719 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4720 log_position + 1);
4721
4722 ASSERT_LT(log_position, entries.size());
4723 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4724 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484725
4726 if (i == 1) {
4727 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4728 entries, log_position + 1);
4729 }
[email protected]abe1c4a2013-10-25 19:28:514730 }
4731
4732 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4733 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4734}
4735
4736// Tests handling of delegate info from a URLRequest::Delegate.
4737TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4738 ASSERT_TRUE(test_server_.Start());
4739
4740 AsyncLoggingUrlRequestDelegate request_delegate(
4741 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4742 TestURLRequestContext context(true);
4743 context.set_network_delegate(NULL);
4744 context.set_net_log(&net_log_);
4745 context.Init();
4746
4747 {
4748 // A chunked response with delays between chunks is used to make sure that
4749 // attempts by the URLRequest delegate to log information while reading the
4750 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484751 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514752 // that it occurs.
[email protected]f7022f32014-08-21 16:32:194753 scoped_ptr<URLRequest> r(context.CreateRequest(
4754 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364755 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194756 LoadStateWithParam load_state = r->GetLoadState();
4757 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514758 base::RunLoop().Run();
4759
[email protected]f7022f32014-08-21 16:32:194760 EXPECT_EQ(200, r->GetResponseCode());
4761 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514762 }
4763
mmenke43758e62015-05-04 21:09:464764 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514765 net_log_.GetEntries(&entries);
4766
[email protected]1826a402014-01-08 15:40:484767 size_t log_position = 0;
4768
4769 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4770 entries, log_position);
4771
[email protected]abe1c4a2013-10-25 19:28:514772 // The delegate info should only have been logged on header complete. Other
4773 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484774 log_position =
4775 ExpectLogContainsSomewhereAfter(entries,
4776 log_position + 1,
4777 NetLog::TYPE_URL_REQUEST_DELEGATE,
4778 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514779
4780 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4781 log_position + 1);
4782
4783 ASSERT_LT(log_position, entries.size());
4784 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4785 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4786
4787 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4788 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4789 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4790 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4791}
4792
4793// Tests handling of delegate info from a URLRequest::Delegate in the case of
4794// an HTTP redirect.
4795TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4796 ASSERT_TRUE(test_server_.Start());
4797
4798 AsyncLoggingUrlRequestDelegate request_delegate(
4799 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4800 TestURLRequestContext context(true);
4801 context.set_network_delegate(NULL);
4802 context.set_net_log(&net_log_);
4803 context.Init();
4804
4805 {
[email protected]f7022f32014-08-21 16:32:194806 scoped_ptr<URLRequest> r(context.CreateRequest(
4807 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364808 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194809 LoadStateWithParam load_state = r->GetLoadState();
4810 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514811 base::RunLoop().Run();
4812
[email protected]f7022f32014-08-21 16:32:194813 EXPECT_EQ(200, r->GetResponseCode());
4814 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514815 }
4816
mmenke43758e62015-05-04 21:09:464817 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514818 net_log_.GetEntries(&entries);
4819
4820 // Delegate info should only have been logged in OnReceivedRedirect and
4821 // OnResponseStarted.
4822 size_t log_position = 0;
4823 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484824 if (i == 0) {
4825 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4826 entries, log_position) + 1;
4827 }
4828
[email protected]abe1c4a2013-10-25 19:28:514829 log_position = ExpectLogContainsSomewhereAfter(
4830 entries,
4831 log_position,
4832 NetLog::TYPE_URL_REQUEST_DELEGATE,
4833 NetLog::PHASE_BEGIN);
4834
4835 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4836 log_position + 1);
4837
4838 ASSERT_LT(log_position, entries.size());
4839 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4840 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4841 }
4842
4843 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4844 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4845 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4846 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4847}
4848
4849// Tests handling of delegate info from a URLRequest::Delegate in the case of
4850// an HTTP redirect, with cancellation at various points.
4851TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4852 ASSERT_TRUE(test_server_.Start());
4853
4854 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4855 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4856 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4857 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4858 };
4859
4860 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4861 ++test_case) {
4862 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4863 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:514864 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:514865 context.set_network_delegate(NULL);
4866 context.set_net_log(&net_log);
4867 context.Init();
4868
4869 {
[email protected]f7022f32014-08-21 16:32:194870 scoped_ptr<URLRequest> r(context.CreateRequest(
4871 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364872 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194873 LoadStateWithParam load_state = r->GetLoadState();
4874 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514875 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194876 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514877 }
4878
mmenke43758e62015-05-04 21:09:464879 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:514880 net_log.GetEntries(&entries);
4881
4882 // Delegate info is always logged in both OnReceivedRedirect and
4883 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4884 // OnResponseStarted delegate call is after cancellation, but logging is
4885 // still currently supported in that call.
4886 size_t log_position = 0;
4887 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484888 if (i == 0) {
4889 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4890 entries, log_position) + 1;
4891 }
4892
[email protected]abe1c4a2013-10-25 19:28:514893 log_position = ExpectLogContainsSomewhereAfter(
4894 entries,
4895 log_position,
4896 NetLog::TYPE_URL_REQUEST_DELEGATE,
4897 NetLog::PHASE_BEGIN);
4898
4899 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4900 log_position + 1);
4901
4902 ASSERT_LT(log_position, entries.size());
4903 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4904 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4905 }
4906
4907 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4908 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4909 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4910 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4911 }
4912}
4913
[email protected]847c0fa92012-11-06 16:37:424914namespace {
4915
4916const char kExtraHeader[] = "Allow-Snafu";
4917const char kExtraValue[] = "fubar";
4918
4919class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204920 void OnReceivedRedirect(URLRequest* request,
4921 const RedirectInfo& redirect_info,
4922 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594923 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:424924 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4925 }
4926};
4927
4928} // namespace
4929
4930TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4931 ASSERT_TRUE(test_server_.Start());
4932
4933 GURL destination_url = test_server_.GetURL(
4934 "echoheader?" + std::string(kExtraHeader));
4935 GURL original_url = test_server_.GetURL(
4936 "server-redirect?" + destination_url.spec());
4937 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:364938 scoped_ptr<URLRequest> req(
4939 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194940 req->Start();
[email protected]255620da2013-08-19 13:14:294941 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424942
4943 std::string value;
[email protected]f7022f32014-08-21 16:32:194944 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:424945 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4946 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:194947 EXPECT_FALSE(req->is_pending());
4948 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:424949 EXPECT_EQ(kExtraValue, d.data_received());
4950}
4951
[email protected]251a1b92012-11-13 11:01:094952namespace {
4953
4954const char kExtraHeaderToRemove[] = "To-Be-Removed";
4955
4956class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204957 void OnReceivedRedirect(URLRequest* request,
4958 const RedirectInfo& redirect_info,
4959 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594960 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:094961 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4962 }
4963};
4964
4965} // namespace
4966
4967TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4968 ASSERT_TRUE(test_server_.Start());
4969
4970 GURL destination_url = test_server_.GetURL(
4971 "echoheader?" + std::string(kExtraHeaderToRemove));
4972 GURL original_url = test_server_.GetURL(
4973 "server-redirect?" + destination_url.spec());
4974 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:364975 scoped_ptr<URLRequest> req(
4976 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194977 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4978 req->Start();
[email protected]255620da2013-08-19 13:14:294979 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094980
4981 std::string value;
[email protected]f7022f32014-08-21 16:32:194982 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:094983 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:194984 EXPECT_FALSE(req->is_pending());
4985 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:094986 EXPECT_EQ("None", d.data_received());
4987}
4988
[email protected]316c1e5e2012-09-12 15:17:444989TEST_F(URLRequestTestHTTP, CancelTest) {
4990 TestDelegate d;
4991 {
[email protected]f7022f32014-08-21 16:32:194992 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364993 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444994
[email protected]f7022f32014-08-21 16:32:194995 r->Start();
4996 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444997
[email protected]f7022f32014-08-21 16:32:194998 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:444999
[email protected]255620da2013-08-19 13:14:295000 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445001
5002 // We expect to receive OnResponseStarted even though the request has been
5003 // cancelled.
5004 EXPECT_EQ(1, d.response_started_count());
5005 EXPECT_EQ(0, d.bytes_received());
5006 EXPECT_FALSE(d.received_data_before_response());
5007 }
5008}
5009
5010TEST_F(URLRequestTestHTTP, CancelTest2) {
5011 ASSERT_TRUE(test_server_.Start());
5012
5013 TestDelegate d;
5014 {
[email protected]f7022f32014-08-21 16:32:195015 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365016 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445017
5018 d.set_cancel_in_response_started(true);
5019
[email protected]f7022f32014-08-21 16:32:195020 r->Start();
5021 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445022
[email protected]255620da2013-08-19 13:14:295023 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445024
5025 EXPECT_EQ(1, d.response_started_count());
5026 EXPECT_EQ(0, d.bytes_received());
5027 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195028 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445029 }
5030}
5031
5032TEST_F(URLRequestTestHTTP, CancelTest3) {
5033 ASSERT_TRUE(test_server_.Start());
5034
5035 TestDelegate d;
5036 {
[email protected]f7022f32014-08-21 16:32:195037 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365038 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445039
5040 d.set_cancel_in_received_data(true);
5041
[email protected]f7022f32014-08-21 16:32:195042 r->Start();
5043 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445044
[email protected]255620da2013-08-19 13:14:295045 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445046
5047 EXPECT_EQ(1, d.response_started_count());
5048 // There is no guarantee about how much data was received
5049 // before the cancel was issued. It could have been 0 bytes,
5050 // or it could have been all the bytes.
5051 // EXPECT_EQ(0, d.bytes_received());
5052 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195053 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445054 }
5055}
5056
5057TEST_F(URLRequestTestHTTP, CancelTest4) {
5058 ASSERT_TRUE(test_server_.Start());
5059
5060 TestDelegate d;
5061 {
[email protected]f7022f32014-08-21 16:32:195062 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365063 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445064
[email protected]f7022f32014-08-21 16:32:195065 r->Start();
5066 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445067
5068 // The request will be implicitly canceled when it is destroyed. The
5069 // test delegate must not post a quit message when this happens because
5070 // this test doesn't actually have a message loop. The quit message would
5071 // get put on this thread's message queue and the next test would exit
5072 // early, causing problems.
5073 d.set_quit_on_complete(false);
5074 }
5075 // expect things to just cleanup properly.
5076
5077 // we won't actually get a received reponse here because we've never run the
5078 // message loop
5079 EXPECT_FALSE(d.received_data_before_response());
5080 EXPECT_EQ(0, d.bytes_received());
5081}
5082
5083TEST_F(URLRequestTestHTTP, CancelTest5) {
5084 ASSERT_TRUE(test_server_.Start());
5085
5086 // populate cache
5087 {
5088 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195089 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365090 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195091 r->Start();
[email protected]255620da2013-08-19 13:14:295092 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195093 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445094 }
5095
5096 // cancel read from cache (see bug 990242)
5097 {
5098 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195099 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365100 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195101 r->Start();
5102 r->Cancel();
[email protected]255620da2013-08-19 13:14:295103 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445104
[email protected]f7022f32014-08-21 16:32:195105 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445106 EXPECT_EQ(1, d.response_started_count());
5107 EXPECT_EQ(0, d.bytes_received());
5108 EXPECT_FALSE(d.received_data_before_response());
5109 }
5110}
5111
5112TEST_F(URLRequestTestHTTP, PostTest) {
5113 ASSERT_TRUE(test_server_.Start());
5114 HTTPUploadDataOperationTest("POST");
5115}
5116
5117TEST_F(URLRequestTestHTTP, PutTest) {
5118 ASSERT_TRUE(test_server_.Start());
5119 HTTPUploadDataOperationTest("PUT");
5120}
5121
5122TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5123 ASSERT_TRUE(test_server_.Start());
5124
5125 TestDelegate d;
5126 {
[email protected]f7022f32014-08-21 16:32:195127 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365128 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195129 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445130
[email protected]f7022f32014-08-21 16:32:195131 r->Start();
5132 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445133
[email protected]255620da2013-08-19 13:14:295134 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445135
[email protected]329b68b2012-11-14 17:54:275136 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195137 << "request failed: " << r->status().status()
5138 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445139
5140 EXPECT_FALSE(d.received_data_before_response());
5141 EXPECT_TRUE(d.data_received().empty());
5142 }
5143}
5144
5145TEST_F(URLRequestTestHTTP, PostFileTest) {
5146 ASSERT_TRUE(test_server_.Start());
5147
5148 TestDelegate d;
5149 {
[email protected]f7022f32014-08-21 16:32:195150 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365151 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195152 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445153
[email protected]6cdfd7f2013-02-08 20:40:155154 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445155 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025156 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445157
[email protected]f288ef02012-12-15 20:28:285158 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445159
[email protected]6cdfd7f2013-02-08 20:40:155160 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445161 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475162 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445163 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365164 element_readers.push_back(
5165 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5166 path,
5167 0,
5168 kuint64max,
5169 base::Time()));
mmenkecbc2b712014-10-09 20:29:075170 r->set_upload(make_scoped_ptr<UploadDataStream>(
5171 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445172
[email protected]f7022f32014-08-21 16:32:195173 r->Start();
5174 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445175
[email protected]255620da2013-08-19 13:14:295176 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445177
pkasting6b68a162014-12-01 22:10:295178 int64 size64 = 0;
5179 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5180 ASSERT_LE(size64, std::numeric_limits<int>::max());
5181 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175182 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445183
[email protected]7600d0b2013-12-08 21:43:305184 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445185
[email protected]329b68b2012-11-14 17:54:275186 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195187 << "request failed: " << r->status().status()
5188 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445189
5190 EXPECT_FALSE(d.received_data_before_response());
5191
[email protected]329b68b2012-11-14 17:54:275192 EXPECT_EQ(size, d.bytes_received());
5193 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445194 }
5195}
5196
[email protected]999dd8c2013-11-12 06:45:545197TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5198 ASSERT_TRUE(test_server_.Start());
5199
5200 TestDelegate d;
5201 {
[email protected]f7022f32014-08-21 16:32:195202 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365203 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195204 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545205
5206 ScopedVector<UploadElementReader> element_readers;
5207
5208 element_readers.push_back(new UploadFileElementReader(
5209 base::MessageLoopProxy::current().get(),
5210 base::FilePath(FILE_PATH_LITERAL(
5211 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5212 0,
5213 kuint64max,
5214 base::Time()));
mmenkecbc2b712014-10-09 20:29:075215 r->set_upload(make_scoped_ptr<UploadDataStream>(
5216 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545217
[email protected]f7022f32014-08-21 16:32:195218 r->Start();
5219 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545220
5221 base::RunLoop().Run();
5222
[email protected]999dd8c2013-11-12 06:45:545223 EXPECT_TRUE(d.request_failed());
5224 EXPECT_FALSE(d.received_data_before_response());
5225 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195226 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5227 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545228 }
5229}
5230
[email protected]316c1e5e2012-09-12 15:17:445231TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5232 ASSERT_TRUE(test_server_.Start());
5233
5234 TestDelegate d;
5235 {
[email protected]f7022f32014-08-21 16:32:195236 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365237 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195238 r->EnableChunkedUpload();
5239 r->set_method("POST");
5240 AddChunksToUpload(r.get());
5241 r->Start();
5242 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445243
[email protected]255620da2013-08-19 13:14:295244 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445245
[email protected]f7022f32014-08-21 16:32:195246 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445247 }
5248}
5249
[email protected]329b68b2012-11-14 17:54:275250TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5251 ASSERT_TRUE(test_server_.Start());
5252
5253 TestDelegate d;
5254 {
[email protected]f7022f32014-08-21 16:32:195255 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365256 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195257 r->EnableChunkedUpload();
5258 r->set_method("POST");
5259 r->Start();
5260 EXPECT_TRUE(r->is_pending());
5261 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295262 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275263
[email protected]f7022f32014-08-21 16:32:195264 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275265 }
5266}
5267
[email protected]316c1e5e2012-09-12 15:17:445268TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5269 ASSERT_TRUE(test_server_.Start());
5270
5271 TestDelegate d;
5272 {
[email protected]f7022f32014-08-21 16:32:195273 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365274 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195275 r->EnableChunkedUpload();
5276 r->set_method("POST");
5277 r->Start();
5278 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445279
[email protected]255620da2013-08-19 13:14:295280 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195281 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295282 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445283
[email protected]f7022f32014-08-21 16:32:195284 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445285 }
5286}
5287
5288TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5289 ASSERT_TRUE(test_server_.Start());
5290
5291 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195292 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365293 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195294 req->Start();
[email protected]255620da2013-08-19 13:14:295295 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445296
[email protected]f7022f32014-08-21 16:32:195297 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445298
5299 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195300 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445301
5302 std::string header;
5303 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5304 EXPECT_EQ("private", header);
5305
5306 header.clear();
5307 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5308 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5309
5310 // The response has two "X-Multiple-Entries" headers.
5311 // This verfies our output has them concatenated together.
5312 header.clear();
5313 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5314 EXPECT_EQ("a, b", header);
5315}
5316
[email protected]242d8562012-10-30 21:20:465317TEST_F(URLRequestTestHTTP, ProcessSTS) {
estarka5da76702015-04-09 04:00:165318 SpawnedTestServer::SSLOptions ssl_options(
5319 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475320 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5321 ssl_options,
5322 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465323 ASSERT_TRUE(https_test_server.Start());
5324
estarka5da76702015-04-09 04:00:165325 std::string test_server_hostname = https_test_server.GetURL("").host();
5326
[email protected]242d8562012-10-30 21:20:465327 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195328 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365329 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5330 &d));
[email protected]f7022f32014-08-21 16:32:195331 request->Start();
[email protected]255620da2013-08-19 13:14:295332 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465333
5334 TransportSecurityState* security_state =
5335 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465336 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165337 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5338 &domain_state));
[email protected]242d8562012-10-30 21:20:465339 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265340 domain_state.sts.upgrade_mode);
5341 EXPECT_TRUE(domain_state.sts.include_subdomains);
5342 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275343#if defined(OS_ANDROID)
5344 // Android's CertVerifyProc does not (yet) handle pins.
5345#else
5346 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5347#endif
5348}
5349
estarka5da76702015-04-09 04:00:165350TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475351 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5352 SpawnedTestServer::SSLOptions(),
5353 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165354 ASSERT_TRUE(https_test_server.Start());
5355 // Make sure this test fails if the test server is changed to not
5356 // listen on an IP by default.
5357 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5358 std::string test_server_hostname = https_test_server.GetURL("").host();
5359
5360 TestDelegate d;
5361 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5362 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5363 &d));
5364 request->Start();
5365 base::RunLoop().Run();
5366
5367 TransportSecurityState* security_state =
5368 default_context_.transport_security_state();
5369 TransportSecurityState::DomainState domain_state;
5370 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5371 &domain_state));
5372}
5373
[email protected]37fd55fb2013-06-29 13:13:275374// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5375// reject HPKP headers, and a test setting only HPKP headers will fail (no
5376// DomainState present because header rejected).
5377#if defined(OS_ANDROID)
5378#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5379#else
5380#define MAYBE_ProcessPKP ProcessPKP
5381#endif
5382
5383// Tests that enabling HPKP on a domain does not affect the HSTS
5384// validity/expiration.
5385TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estarka5da76702015-04-09 04:00:165386 SpawnedTestServer::SSLOptions ssl_options(
5387 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475388 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5389 ssl_options,
5390 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275391 ASSERT_TRUE(https_test_server.Start());
5392
estarka5da76702015-04-09 04:00:165393 std::string test_server_hostname = https_test_server.GetURL("").host();
5394
[email protected]37fd55fb2013-06-29 13:13:275395 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195396 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365397 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5398 &d));
[email protected]f7022f32014-08-21 16:32:195399 request->Start();
[email protected]255620da2013-08-19 13:14:295400 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275401
5402 TransportSecurityState* security_state =
5403 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275404 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165405 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5406 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275407 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265408 domain_state.sts.upgrade_mode);
5409 EXPECT_FALSE(domain_state.sts.include_subdomains);
5410 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275411 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265412 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465413}
5414
estarka5da76702015-04-09 04:00:165415TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
mmenke9f2ec60c2015-06-01 20:59:475416 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5417 SpawnedTestServer::SSLOptions(),
5418 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165419 ASSERT_TRUE(https_test_server.Start());
5420 // Make sure this test fails if the test server is changed to not
5421 // listen on an IP by default.
5422 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5423 std::string test_server_hostname = https_test_server.GetURL("").host();
5424
5425 TestDelegate d;
5426 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5427 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5428 &d));
5429 request->Start();
5430 base::RunLoop().Run();
5431
5432 TransportSecurityState* security_state =
5433 default_context_.transport_security_state();
5434 TransportSecurityState::DomainState domain_state;
5435 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5436 &domain_state));
5437}
5438
[email protected]242d8562012-10-30 21:20:465439TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
estarka5da76702015-04-09 04:00:165440 SpawnedTestServer::SSLOptions ssl_options(
5441 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475442 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5443 ssl_options,
5444 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465445 ASSERT_TRUE(https_test_server.Start());
5446
estarka5da76702015-04-09 04:00:165447 std::string test_server_hostname = https_test_server.GetURL("").host();
5448
[email protected]242d8562012-10-30 21:20:465449 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195450 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465451 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365452 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195453 request->Start();
[email protected]255620da2013-08-19 13:14:295454 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465455
5456 // We should have set parameters from the first header, not the second.
5457 TransportSecurityState* security_state =
5458 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465459 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165460 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5461 &domain_state));
[email protected]242d8562012-10-30 21:20:465462 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265463 domain_state.sts.upgrade_mode);
5464 EXPECT_FALSE(domain_state.sts.include_subdomains);
5465 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465466}
5467
[email protected]9f972ec2013-04-10 20:24:365468TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
estarka5da76702015-04-09 04:00:165469 SpawnedTestServer::SSLOptions ssl_options(
5470 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475471 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5472 ssl_options,
5473 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:365474 ASSERT_TRUE(https_test_server.Start());
5475
estarka5da76702015-04-09 04:00:165476 std::string test_server_hostname = https_test_server.GetURL("").host();
5477
[email protected]9f972ec2013-04-10 20:24:365478 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195479 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365480 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
davidben151423e2015-03-23 18:48:365481 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195482 request->Start();
[email protected]255620da2013-08-19 13:14:295483 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365484
5485 // We should have set parameters from the first header, not the second.
5486 TransportSecurityState* security_state =
5487 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365488 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165489 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5490 &domain_state));
[email protected]9f972ec2013-04-10 20:24:365491 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265492 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365493#if defined(OS_ANDROID)
5494 // Android's CertVerifyProc does not (yet) handle pins.
5495#else
5496 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5497#endif
[email protected]9e6968d2014-05-07 21:46:265498 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365499
[email protected]a165f092013-06-12 16:10:055500 // Even though there is an HSTS header asserting includeSubdomains, it is
5501 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265502 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055503 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265504 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365505}
5506
[email protected]37fd55fb2013-06-29 13:13:275507// Tests that when multiple HPKP headers are present, asserting different
5508// policies, that only the first such policy is processed.
5509TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
estarka5da76702015-04-09 04:00:165510 SpawnedTestServer::SSLOptions ssl_options(
5511 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
mmenke9f2ec60c2015-06-01 20:59:475512 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
5513 ssl_options,
5514 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275515 ASSERT_TRUE(https_test_server.Start());
5516
estarka5da76702015-04-09 04:00:165517 std::string test_server_hostname = https_test_server.GetURL("").host();
5518
[email protected]37fd55fb2013-06-29 13:13:275519 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195520 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275521 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:365522 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195523 request->Start();
[email protected]255620da2013-08-19 13:14:295524 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275525
5526 TransportSecurityState* security_state =
5527 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275528 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165529 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5530 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275531 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265532 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275533#if defined(OS_ANDROID)
5534 // Android's CertVerifyProc does not (yet) handle pins.
5535#else
5536 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5537#endif
[email protected]9e6968d2014-05-07 21:46:265538 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275539
[email protected]9e6968d2014-05-07 21:46:265540 EXPECT_TRUE(domain_state.sts.include_subdomains);
5541 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275542}
5543
[email protected]316c1e5e2012-09-12 15:17:445544TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5545 ASSERT_TRUE(test_server_.Start());
5546
5547 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195548 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5549 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:365550 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195551 req->Start();
[email protected]255620da2013-08-19 13:14:295552 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445553
5554 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195555 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445556 EXPECT_EQ("text/html", mime_type);
5557
5558 std::string charset;
[email protected]f7022f32014-08-21 16:32:195559 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445560 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195561 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445562}
5563
[email protected]02494ec2014-05-07 15:05:295564TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345565 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345566 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345567 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025568 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345569
5570 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505571 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345572}
5573
[email protected]02494ec2014-05-07 15:05:295574#if !defined(DISABLE_FILE_SUPPORT)
5575TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5576 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5577 GURL file_url("file:///foo.txt");
5578 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5579 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5580
5581 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505582 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295583}
5584
[email protected]588614c22013-08-16 00:09:025585TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445586 ASSERT_TRUE(test_server_.Start());
5587
5588 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195589 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365590 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5591 &d));
[email protected]f7022f32014-08-21 16:32:195592 req->Start();
[email protected]255620da2013-08-19 13:14:295593 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445594
[email protected]f7022f32014-08-21 16:32:195595 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5596 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445597}
[email protected]02494ec2014-05-07 15:05:295598#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445599
[email protected]588614c22013-08-16 00:09:025600TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5601 ASSERT_TRUE(test_server_.Start());
5602
5603 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195604 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365605 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5606 &d));
[email protected]f7022f32014-08-21 16:32:195607 req->Start();
[email protected]588614c22013-08-16 00:09:025608 base::MessageLoop::current()->Run();
5609
[email protected]f7022f32014-08-21 16:32:195610 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5611 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025612}
5613
[email protected]316c1e5e2012-09-12 15:17:445614TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5615 ASSERT_TRUE(test_server_.Start());
5616
5617 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195618 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5619 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:365620 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195621 req->Start();
[email protected]255620da2013-08-19 13:14:295622 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445623
[email protected]f7022f32014-08-21 16:32:195624 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5625 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445626}
5627
[email protected]e50efea2014-03-24 18:41:005628// Make sure redirects are cached, despite not reading their bodies.
5629TEST_F(URLRequestTestHTTP, CacheRedirect) {
5630 ASSERT_TRUE(test_server_.Start());
5631 GURL redirect_url =
5632 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5633
5634 {
5635 TestDelegate d;
davidben151423e2015-03-23 18:48:365636 scoped_ptr<URLRequest> req(
5637 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195638 req->Start();
[email protected]e50efea2014-03-24 18:41:005639 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195640 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005641 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195642 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005643 }
5644
5645 {
5646 TestDelegate d;
5647 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:365648 scoped_ptr<URLRequest> req(
5649 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195650 req->Start();
[email protected]e50efea2014-03-24 18:41:005651 base::RunLoop().Run();
5652
5653 EXPECT_EQ(1, d.received_redirect_count());
5654 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195655 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005656
[email protected]f7022f32014-08-21 16:32:195657 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005658 base::RunLoop().Run();
5659 EXPECT_EQ(1, d.received_redirect_count());
5660 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195661 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5662 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005663 }
5664}
5665
5666// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5667// when the headers are read, since the body won't have been read.
5668TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5669 ASSERT_TRUE(test_server_.Start());
5670 // URL that is normally cached.
5671 GURL initial_url = test_server_.GetURL("cachetime");
5672
5673 {
5674 // Set up the TestNetworkDelegate tp force a redirect.
5675 GURL redirect_to_url = test_server_.GetURL("echo");
5676 default_network_delegate_.set_redirect_on_headers_received_url(
5677 redirect_to_url);
5678
5679 TestDelegate d;
davidben151423e2015-03-23 18:48:365680 scoped_ptr<URLRequest> req(
5681 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195682 req->Start();
[email protected]e50efea2014-03-24 18:41:005683 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195684 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005685 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195686 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005687 }
5688
5689 {
5690 TestDelegate d;
davidben151423e2015-03-23 18:48:365691 scoped_ptr<URLRequest> req(
5692 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195693 req->Start();
[email protected]e50efea2014-03-24 18:41:005694 base::RunLoop().Run();
5695
[email protected]f7022f32014-08-21 16:32:195696 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5697 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005698 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195699 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005700 }
5701}
5702
[email protected]5f714132014-03-26 10:41:165703// Tests that redirection to an unsafe URL is allowed when it has been marked as
5704// safe.
5705TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5706 ASSERT_TRUE(test_server_.Start());
5707
5708 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5709 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5710 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5711
5712 TestDelegate d;
5713 {
[email protected]f7022f32014-08-21 16:32:195714 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365715 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165716
[email protected]f7022f32014-08-21 16:32:195717 r->Start();
[email protected]5f714132014-03-26 10:41:165718 base::RunLoop().Run();
5719
[email protected]f7022f32014-08-21 16:32:195720 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165721
[email protected]f7022f32014-08-21 16:32:195722 EXPECT_EQ(2U, r->url_chain().size());
5723 EXPECT_EQ(OK, r->status().error());
5724 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165725 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5726 }
5727}
5728
5729// Tests that a redirect to a different unsafe URL is blocked, even after adding
5730// some other URL to the whitelist.
5731TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5732 ASSERT_TRUE(test_server_.Start());
5733
5734 GURL unsafe_url("data:text/html,something");
5735 GURL different_unsafe_url("data:text/html,something-else");
5736 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5737 default_network_delegate_.set_allowed_unsafe_redirect_url(
5738 different_unsafe_url);
5739
5740 TestDelegate d;
5741 {
[email protected]f7022f32014-08-21 16:32:195742 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365743 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165744
[email protected]f7022f32014-08-21 16:32:195745 r->Start();
[email protected]5f714132014-03-26 10:41:165746 base::RunLoop().Run();
5747
[email protected]f7022f32014-08-21 16:32:195748 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5749 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165750 }
5751}
5752
[email protected]5f714132014-03-26 10:41:165753// Redirects from an URL with fragment to an unsafe URL with fragment should
5754// be allowed, and the reference fragment of the target URL should be preserved.
5755TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5756 ASSERT_TRUE(test_server_.Start());
5757
5758 GURL original_url(test_server_.GetURL("original#fragment1"));
5759 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5760 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5761
5762 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5763 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5764
5765 TestDelegate d;
5766 {
davidben151423e2015-03-23 18:48:365767 scoped_ptr<URLRequest> r(
5768 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165769
[email protected]f7022f32014-08-21 16:32:195770 r->Start();
[email protected]5f714132014-03-26 10:41:165771 base::RunLoop().Run();
5772
[email protected]f7022f32014-08-21 16:32:195773 EXPECT_EQ(2U, r->url_chain().size());
5774 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5775 EXPECT_EQ(OK, r->status().error());
5776 EXPECT_EQ(original_url, r->original_url());
5777 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165778 }
5779}
5780
5781// When a delegate has specified a safe redirect URL, but it does not match the
5782// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145783TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165784 ASSERT_TRUE(test_server_.Start());
5785
5786 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5787 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5788 GURL redirect_url(test_server_.GetURL("target"));
5789 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5790
5791 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5792 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5793
5794 TestDelegate d;
5795 {
davidben151423e2015-03-23 18:48:365796 scoped_ptr<URLRequest> r(
5797 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165798
[email protected]f7022f32014-08-21 16:32:195799 r->Start();
[email protected]5f714132014-03-26 10:41:165800 base::RunLoop().Run();
5801
[email protected]f7022f32014-08-21 16:32:195802 EXPECT_EQ(2U, r->url_chain().size());
5803 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5804 EXPECT_EQ(OK, r->status().error());
5805 EXPECT_EQ(original_url, r->original_url());
5806 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:165807 }
5808}
5809
[email protected]f878230e2014-04-03 15:36:145810// When a delegate has specified a safe redirect URL, assume that the redirect
5811// URL should not be changed. In particular, the reference fragment should not
5812// be modified.
5813TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5814 ASSERT_TRUE(test_server_.Start());
5815
5816 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5817 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5818
5819 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5820 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5821
5822 TestDelegate d;
5823 {
davidben151423e2015-03-23 18:48:365824 scoped_ptr<URLRequest> r(
5825 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145826
[email protected]f7022f32014-08-21 16:32:195827 r->Start();
[email protected]f878230e2014-04-03 15:36:145828 base::RunLoop().Run();
5829
[email protected]f7022f32014-08-21 16:32:195830 EXPECT_EQ(2U, r->url_chain().size());
5831 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5832 EXPECT_EQ(OK, r->status().error());
5833 EXPECT_EQ(original_url, r->original_url());
5834 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145835 }
5836}
5837
5838// When a URLRequestRedirectJob is created, the redirection must be followed and
5839// the reference fragment of the target URL must not be modified.
5840TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5841 ASSERT_TRUE(test_server_.Start());
5842
5843 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5844 GURL redirect_url(test_server_.GetURL("echo"));
5845
5846 TestDelegate d;
davidben151423e2015-03-23 18:48:365847 scoped_ptr<URLRequest> r(
5848 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145849
5850 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:195851 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:145852 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5853 AddTestInterceptor()->set_main_intercept_job(job);
5854
[email protected]f7022f32014-08-21 16:32:195855 r->Start();
[email protected]f878230e2014-04-03 15:36:145856 base::RunLoop().Run();
5857
[email protected]f7022f32014-08-21 16:32:195858 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5859 EXPECT_EQ(OK, r->status().error());
5860 EXPECT_EQ(original_url, r->original_url());
5861 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145862}
5863
[email protected]316c1e5e2012-09-12 15:17:445864TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5865 ASSERT_TRUE(test_server_.Start());
5866
5867 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195868 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365869 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195870 req->SetReferrer("http://user:[email protected]/");
5871 req->Start();
[email protected]255620da2013-08-19 13:14:295872 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445873
5874 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5875}
5876
[email protected]99ecf6e2013-04-10 22:46:135877TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5878 ASSERT_TRUE(test_server_.Start());
5879
5880 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195881 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365882 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195883 req->SetReferrer("http://foo.com/test#fragment");
5884 req->Start();
[email protected]255620da2013-08-19 13:14:295885 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135886
5887 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5888}
5889
5890TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5891 ASSERT_TRUE(test_server_.Start());
5892
5893 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195894 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365895 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195896 req->SetReferrer("http://foo.com/test#fragment");
5897 req->SetReferrer("");
5898 req->Start();
[email protected]255620da2013-08-19 13:14:295899 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135900
5901 EXPECT_EQ(std::string("None"), d.data_received());
5902}
5903
[email protected]1826a402014-01-08 15:40:485904// Defer network start and then resume, checking that the request was a success
5905// and bytes were received.
5906TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5907 ASSERT_TRUE(test_server_.Start());
5908
5909 TestDelegate d;
5910 {
5911 d.set_quit_on_network_start(true);
5912 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365913 scoped_ptr<URLRequest> req(
5914 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485915
[email protected]f7022f32014-08-21 16:32:195916 req->Start();
[email protected]1826a402014-01-08 15:40:485917 base::RunLoop().Run();
5918
5919 EXPECT_EQ(1, d.received_before_network_start_count());
5920 EXPECT_EQ(0, d.response_started_count());
5921
[email protected]f7022f32014-08-21 16:32:195922 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485923 base::RunLoop().Run();
5924
5925 EXPECT_EQ(1, d.response_started_count());
5926 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195927 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485928 }
5929}
5930
5931// Check that OnBeforeNetworkStart is only called once even if there is a
5932// redirect.
5933TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5934 ASSERT_TRUE(test_server_.Start());
5935
5936 TestDelegate d;
5937 {
5938 d.set_quit_on_redirect(true);
5939 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:195940 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365941 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485942
[email protected]f7022f32014-08-21 16:32:195943 req->Start();
[email protected]1826a402014-01-08 15:40:485944 base::RunLoop().Run();
5945
5946 EXPECT_EQ(1, d.received_before_network_start_count());
5947 EXPECT_EQ(0, d.response_started_count());
5948 EXPECT_EQ(0, d.received_redirect_count());
5949
[email protected]f7022f32014-08-21 16:32:195950 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485951 base::RunLoop().Run();
5952
5953 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195954 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:485955 base::RunLoop().Run();
5956
5957 // Check that the redirect's new network transaction does not get propagated
5958 // to a second OnBeforeNetworkStart() notification.
5959 EXPECT_EQ(1, d.received_before_network_start_count());
5960
5961 EXPECT_EQ(1, d.response_started_count());
5962 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195963 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485964 }
5965}
5966
5967// Cancel the request after learning that the request would use the network.
5968TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5969 ASSERT_TRUE(test_server_.Start());
5970
5971 TestDelegate d;
5972 {
5973 d.set_quit_on_network_start(true);
5974 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365975 scoped_ptr<URLRequest> req(
5976 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485977
[email protected]f7022f32014-08-21 16:32:195978 req->Start();
[email protected]1826a402014-01-08 15:40:485979 base::RunLoop().Run();
5980
5981 EXPECT_EQ(1, d.received_before_network_start_count());
5982 EXPECT_EQ(0, d.response_started_count());
5983
[email protected]f7022f32014-08-21 16:32:195984 req->Cancel();
[email protected]1826a402014-01-08 15:40:485985 base::RunLoop().Run();
5986
5987 EXPECT_EQ(1, d.response_started_count());
5988 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195989 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:485990 }
5991}
5992
[email protected]316c1e5e2012-09-12 15:17:445993TEST_F(URLRequestTestHTTP, CancelRedirect) {
5994 ASSERT_TRUE(test_server_.Start());
5995
5996 TestDelegate d;
5997 {
5998 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:195999 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366000 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196001 req->Start();
[email protected]255620da2013-08-19 13:14:296002 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446003
6004 EXPECT_EQ(1, d.response_started_count());
6005 EXPECT_EQ(0, d.bytes_received());
6006 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196007 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446008 }
6009}
6010
6011TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6012 ASSERT_TRUE(test_server_.Start());
6013
6014 TestDelegate d;
6015 {
6016 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:046017 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366018 scoped_ptr<URLRequest> req(
6019 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046020
[email protected]f7022f32014-08-21 16:32:196021 req->Start();
[email protected]255620da2013-08-19 13:14:296022 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446023
6024 EXPECT_EQ(1, d.received_redirect_count());
6025
[email protected]f7022f32014-08-21 16:32:196026 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296027 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446028
6029 EXPECT_EQ(1, d.response_started_count());
6030 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196031 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446032
[email protected]6cdfd7f2013-02-08 20:40:156033 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446034 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476035 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446036 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6037
6038 std::string contents;
[email protected]82f84b92013-08-30 18:23:506039 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446040 EXPECT_EQ(contents, d.data_received());
6041 }
6042}
6043
[email protected]79e1fd62013-06-20 06:50:046044TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6045 ASSERT_TRUE(test_server_.Start());
6046
6047 TestDelegate d;
6048 {
6049 d.set_quit_on_redirect(true);
6050 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366051 scoped_ptr<URLRequest> req(
6052 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046053
6054 EXPECT_FALSE(d.have_full_request_headers());
6055
[email protected]f7022f32014-08-21 16:32:196056 req->Start();
[email protected]255620da2013-08-19 13:14:296057 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046058
6059 EXPECT_EQ(1, d.received_redirect_count());
6060 EXPECT_TRUE(d.have_full_request_headers());
6061 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6062 d.ClearFullRequestHeaders();
6063
[email protected]f7022f32014-08-21 16:32:196064 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296065 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046066
6067 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6068 EXPECT_EQ(1, d.response_started_count());
6069 EXPECT_TRUE(d.have_full_request_headers());
6070 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6071 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196072 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046073
6074 base::FilePath path;
6075 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476076 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046077 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6078
6079 std::string contents;
[email protected]82f84b92013-08-30 18:23:506080 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046081 EXPECT_EQ(contents, d.data_received());
6082 }
6083}
6084
[email protected]316c1e5e2012-09-12 15:17:446085TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6086 ASSERT_TRUE(test_server_.Start());
6087
6088 TestDelegate d;
6089 {
6090 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196091 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366092 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196093 req->Start();
[email protected]255620da2013-08-19 13:14:296094 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446095
6096 EXPECT_EQ(1, d.received_redirect_count());
6097
[email protected]f7022f32014-08-21 16:32:196098 req->Cancel();
[email protected]255620da2013-08-19 13:14:296099 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446100
6101 EXPECT_EQ(1, d.response_started_count());
6102 EXPECT_EQ(0, d.bytes_received());
6103 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196104 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446105 }
6106}
6107
6108TEST_F(URLRequestTestHTTP, VaryHeader) {
6109 ASSERT_TRUE(test_server_.Start());
6110
[email protected]3b23a222013-05-15 21:33:256111 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446112 {
6113 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196114 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366115 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446116 HttpRequestHeaders headers;
6117 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196118 req->SetExtraRequestHeaders(headers);
6119 req->Start();
[email protected]255620da2013-08-19 13:14:296120 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256121
6122 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196123 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256124 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446125 }
6126
[email protected]3b23a222013-05-15 21:33:256127 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446128 {
6129 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196130 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366131 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446132 HttpRequestHeaders headers;
6133 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196134 req->SetExtraRequestHeaders(headers);
6135 req->Start();
[email protected]255620da2013-08-19 13:14:296136 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446137
[email protected]f7022f32014-08-21 16:32:196138 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256139
6140 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196141 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256142 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446143 }
6144
[email protected]3b23a222013-05-15 21:33:256145 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446146 {
6147 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196148 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366149 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446150 HttpRequestHeaders headers;
6151 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196152 req->SetExtraRequestHeaders(headers);
6153 req->Start();
[email protected]255620da2013-08-19 13:14:296154 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446155
[email protected]f7022f32014-08-21 16:32:196156 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256157
6158 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196159 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256160 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446161 }
6162}
6163
6164TEST_F(URLRequestTestHTTP, BasicAuth) {
6165 ASSERT_TRUE(test_server_.Start());
6166
6167 // populate the cache
6168 {
6169 TestDelegate d;
6170 d.set_credentials(AuthCredentials(kUser, kSecret));
6171
[email protected]f7022f32014-08-21 16:32:196172 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366173 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196174 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446175
[email protected]255620da2013-08-19 13:14:296176 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446177
6178 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6179 }
6180
6181 // repeat request with end-to-end validation. since auth-basic results in a
6182 // cachable page, we expect this test to result in a 304. in which case, the
6183 // response should be fetched from the cache.
6184 {
6185 TestDelegate d;
6186 d.set_credentials(AuthCredentials(kUser, kSecret));
6187
[email protected]f7022f32014-08-21 16:32:196188 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366189 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196190 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6191 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446192
[email protected]255620da2013-08-19 13:14:296193 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446194
6195 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6196
6197 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196198 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446199 }
6200}
6201
6202// Check that Set-Cookie headers in 401 responses are respected.
6203// http://crbug.com/6450
6204TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6205 ASSERT_TRUE(test_server_.Start());
6206
6207 GURL url_requiring_auth =
6208 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6209
6210 // Request a page that will give a 401 containing a Set-Cookie header.
6211 // Verify that when the transaction is restarted, it includes the new cookie.
6212 {
[email protected]ceefd7fd2012-11-29 00:36:246213 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446214 TestURLRequestContext context(true);
6215 context.set_network_delegate(&network_delegate);
6216 context.Init();
6217
6218 TestDelegate d;
6219 d.set_credentials(AuthCredentials(kUser, kSecret));
6220
davidben151423e2015-03-23 18:48:366221 scoped_ptr<URLRequest> r(
6222 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196223 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446224
[email protected]255620da2013-08-19 13:14:296225 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446226
6227 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6228
6229 // Make sure we sent the cookie in the restarted transaction.
6230 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6231 != std::string::npos);
6232 }
6233
6234 // Same test as above, except this time the restart is initiated earlier
6235 // (without user intervention since identity is embedded in the URL).
6236 {
[email protected]ceefd7fd2012-11-29 00:36:246237 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446238 TestURLRequestContext context(true);
6239 context.set_network_delegate(&network_delegate);
6240 context.Init();
6241
6242 TestDelegate d;
6243
6244 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186245 replacements.SetUsernameStr("user2");
6246 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446247 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6248
davidben151423e2015-03-23 18:48:366249 scoped_ptr<URLRequest> r(
6250 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196251 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446252
[email protected]255620da2013-08-19 13:14:296253 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446254
6255 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6256
6257 // Make sure we sent the cookie in the restarted transaction.
6258 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6259 != std::string::npos);
6260 }
6261}
6262
[email protected]58e32bb2013-01-21 18:23:256263// Tests that load timing works as expected with auth and the cache.
6264TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6265 ASSERT_TRUE(test_server_.Start());
6266
6267 // populate the cache
6268 {
6269 TestDelegate d;
6270 d.set_credentials(AuthCredentials(kUser, kSecret));
6271
[email protected]f7022f32014-08-21 16:32:196272 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366273 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196274 r->Start();
[email protected]58e32bb2013-01-21 18:23:256275
[email protected]255620da2013-08-19 13:14:296276 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256277
6278 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6279
6280 LoadTimingInfo load_timing_info_before_auth;
6281 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6282 &load_timing_info_before_auth));
6283 TestLoadTimingNotReused(load_timing_info_before_auth,
6284 CONNECT_TIMING_HAS_DNS_TIMES);
6285
6286 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196287 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256288 // The test server does not support keep alive sockets, so the second
6289 // request with auth should use a new socket.
6290 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6291 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6292 load_timing_info.socket_log_id);
6293 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6294 load_timing_info.connect_timing.connect_start);
6295 }
6296
[email protected]3b23a222013-05-15 21:33:256297 // Repeat request with end-to-end validation. Since auth-basic results in a
6298 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256299 // response should be fetched from the cache.
6300 {
6301 TestDelegate d;
6302 d.set_credentials(AuthCredentials(kUser, kSecret));
6303
[email protected]f7022f32014-08-21 16:32:196304 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366305 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196306 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6307 r->Start();
[email protected]58e32bb2013-01-21 18:23:256308
[email protected]255620da2013-08-19 13:14:296309 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256310
6311 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6312
6313 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196314 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256315
[email protected]3b23a222013-05-15 21:33:256316 // Since there was a request that went over the wire, the load timing
6317 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256318 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196319 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256320 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256321 }
6322}
6323
[email protected]316c1e5e2012-09-12 15:17:446324// In this test, we do a POST which the server will 302 redirect.
6325// The subsequent transaction should use GET, and should not send the
6326// Content-Type header.
6327// http://code.google.com/p/chromium/issues/detail?id=843
6328TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6329 ASSERT_TRUE(test_server_.Start());
6330
6331 const char kData[] = "hello world";
6332
6333 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196334 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366335 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196336 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076337 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446338
6339 // Set headers (some of which are specific to the POST).
6340 HttpRequestHeaders headers;
6341 headers.AddHeadersFromString(
6342 "Content-Type: multipart/form-data; "
6343 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6344 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6345 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6346 "Accept-Language: en-US,en\r\n"
6347 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6348 "Content-Length: 11\r\n"
6349 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196350 req->SetExtraRequestHeaders(headers);
6351 req->Start();
[email protected]255620da2013-08-19 13:14:296352 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446353
6354 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196355 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446356 EXPECT_EQ("text/html", mime_type);
6357
6358 const std::string& data = d.data_received();
6359
6360 // Check that the post-specific headers were stripped:
6361 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6362 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6363 EXPECT_FALSE(ContainsString(data, "Origin:"));
6364
6365 // These extra request headers should not have been stripped.
6366 EXPECT_TRUE(ContainsString(data, "Accept:"));
6367 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6368 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6369}
6370
jww5fe460ff2015-03-28 00:22:516371// The following tests check that we handle mutating the request for HTTP
6372// redirects as expected.
6373// See https://crbug.com/56373, https://crbug.com/102130, and
6374// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446375
6376TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6377 ASSERT_TRUE(test_server_.Start());
6378
6379 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516380 const GURL https_redirect_url =
6381 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446382
6383 HTTPRedirectMethodTest(url, "POST", "GET", true);
6384 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6385 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516386
6387 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6388 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6389 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6390 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6391 std::string());
[email protected]316c1e5e2012-09-12 15:17:446392}
6393
6394TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6395 ASSERT_TRUE(test_server_.Start());
6396
6397 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516398 const GURL https_redirect_url =
6399 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446400
6401 HTTPRedirectMethodTest(url, "POST", "GET", true);
6402 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6403 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516404
6405 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6406 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6407 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6408 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6409 std::string());
[email protected]316c1e5e2012-09-12 15:17:446410}
6411
6412TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6413 ASSERT_TRUE(test_server_.Start());
6414
6415 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516416 const GURL https_redirect_url =
6417 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446418
6419 HTTPRedirectMethodTest(url, "POST", "GET", true);
6420 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6421 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516422
6423 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6424 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6425 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6426 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6427 std::string());
[email protected]316c1e5e2012-09-12 15:17:446428}
6429
6430TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6431 ASSERT_TRUE(test_server_.Start());
6432
6433 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516434 const GURL https_redirect_url =
6435 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446436
6437 HTTPRedirectMethodTest(url, "POST", "POST", true);
6438 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6439 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516440
6441 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6442 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6443 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6444 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446445}
6446
[email protected]0a17aab32014-04-24 03:32:376447TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6448 ASSERT_TRUE(test_server_.Start());
6449
6450 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516451 const GURL https_redirect_url =
6452 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376453
6454 HTTPRedirectMethodTest(url, "POST", "POST", true);
6455 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6456 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516457
6458 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6459 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6460 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6461 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376462}
6463
6464// Make sure that 308 responses without bodies are not treated as redirects.
6465// Certain legacy apis that pre-date the response code expect this behavior
6466// (Like Google Drive).
6467TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6468 ASSERT_TRUE(test_server_.Start());
6469
6470 TestDelegate d;
6471 const GURL url = test_server_.GetURL("files/308-without-location-header");
6472
davidben151423e2015-03-23 18:48:366473 scoped_ptr<URLRequest> request(
6474 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376475
[email protected]f7022f32014-08-21 16:32:196476 request->Start();
[email protected]0a17aab32014-04-24 03:32:376477 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196478 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6479 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376480 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196481 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376482 EXPECT_EQ("This is not a redirect.", d.data_received());
6483}
6484
[email protected]f878230e2014-04-03 15:36:146485TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6486 ASSERT_TRUE(test_server_.Start());
6487
6488 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6489 GURL expected_url(test_server_.GetURL("echo#fragment"));
6490
6491 TestDelegate d;
6492 {
davidben151423e2015-03-23 18:48:366493 scoped_ptr<URLRequest> r(
6494 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146495
[email protected]f7022f32014-08-21 16:32:196496 r->Start();
[email protected]f878230e2014-04-03 15:36:146497 base::RunLoop().Run();
6498
[email protected]f7022f32014-08-21 16:32:196499 EXPECT_EQ(2U, r->url_chain().size());
6500 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6501 EXPECT_EQ(OK, r->status().error());
6502 EXPECT_EQ(original_url, r->original_url());
6503 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146504 }
6505}
6506
[email protected]cba24642014-08-15 20:49:596507TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6508 ASSERT_TRUE(test_server_.Start());
6509
6510 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6511 GURL first_party_url("http://example.com");
6512
6513 TestDelegate d;
6514 {
davidben151423e2015-03-23 18:48:366515 scoped_ptr<URLRequest> r(
6516 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196517 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596518
[email protected]f7022f32014-08-21 16:32:196519 r->Start();
[email protected]cba24642014-08-15 20:49:596520 base::RunLoop().Run();
6521
[email protected]f7022f32014-08-21 16:32:196522 EXPECT_EQ(2U, r->url_chain().size());
6523 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6524 EXPECT_EQ(OK, r->status().error());
6525 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596526 }
6527}
6528
6529TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6530 ASSERT_TRUE(test_server_.Start());
6531
6532 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6533 GURL original_first_party_url("http://example.com");
6534 GURL expected_first_party_url(test_server_.GetURL("echo"));
6535
6536 TestDelegate d;
6537 {
davidben151423e2015-03-23 18:48:366538 scoped_ptr<URLRequest> r(
6539 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196540 r->set_first_party_for_cookies(original_first_party_url);
6541 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596542 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6543
[email protected]f7022f32014-08-21 16:32:196544 r->Start();
[email protected]cba24642014-08-15 20:49:596545 base::RunLoop().Run();
6546
[email protected]f7022f32014-08-21 16:32:196547 EXPECT_EQ(2U, r->url_chain().size());
6548 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6549 EXPECT_EQ(OK, r->status().error());
6550 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596551 }
6552}
6553
[email protected]316c1e5e2012-09-12 15:17:446554TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6555 ASSERT_TRUE(test_server_.Start());
6556
6557 const char kData[] = "hello world";
6558
6559 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196560 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366561 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196562 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076563 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446564 HttpRequestHeaders headers;
6565 headers.SetHeader(HttpRequestHeaders::kContentLength,
6566 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196567 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446568
6569 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196570 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096571 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446572 AddTestInterceptor()->set_main_intercept_job(job);
6573
[email protected]f7022f32014-08-21 16:32:196574 req->Start();
[email protected]255620da2013-08-19 13:14:296575 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196576 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446577}
6578
6579TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6580 ASSERT_TRUE(test_server_.Start());
6581
6582 const char kData[] = "hello world";
6583
6584 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196585 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366586 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196587 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076588 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446589 HttpRequestHeaders headers;
6590 headers.SetHeader(HttpRequestHeaders::kContentLength,
6591 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196592 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446593
6594 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196595 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096596 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6597 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446598 AddTestInterceptor()->set_main_intercept_job(job);
6599
[email protected]f7022f32014-08-21 16:32:196600 req->Start();
[email protected]255620da2013-08-19 13:14:296601 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196602 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446603 EXPECT_EQ(kData, d.data_received());
6604}
6605
6606// Check that default A-L header is sent.
6607TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6608 ASSERT_TRUE(test_server_.Start());
6609
[email protected]8790210c2013-12-02 05:29:536610 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246611 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446612 TestURLRequestContext context(true);
6613 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436614 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446615 context.Init();
6616
6617 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196618 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366619 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196620 req->Start();
[email protected]255620da2013-08-19 13:14:296621 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446622 EXPECT_EQ("en", d.data_received());
6623}
6624
6625// Check that an empty A-L header is not sent. http://crbug.com/77365.
6626TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6627 ASSERT_TRUE(test_server_.Start());
6628
[email protected]8790210c2013-12-02 05:29:536629 std::string empty_string; // Avoid most vexing parse on line below.
6630 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246631 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446632 TestURLRequestContext context(true);
6633 context.set_network_delegate(&network_delegate);
6634 context.Init();
6635 // We override the language after initialization because empty entries
6636 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436637 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446638
6639 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196640 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366641 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196642 req->Start();
[email protected]255620da2013-08-19 13:14:296643 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446644 EXPECT_EQ("None", d.data_received());
6645}
6646
6647// Check that if request overrides the A-L header, the default is not appended.
6648// See http://crbug.com/20894
6649TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6650 ASSERT_TRUE(test_server_.Start());
6651
6652 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196653 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366654 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446655 HttpRequestHeaders headers;
6656 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196657 req->SetExtraRequestHeaders(headers);
6658 req->Start();
[email protected]255620da2013-08-19 13:14:296659 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446660 EXPECT_EQ(std::string("ru"), d.data_received());
6661}
6662
6663// Check that default A-E header is sent.
6664TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6665 ASSERT_TRUE(test_server_.Start());
6666
6667 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196668 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366669 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446670 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196671 req->SetExtraRequestHeaders(headers);
6672 req->Start();
[email protected]255620da2013-08-19 13:14:296673 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446674 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6675}
6676
6677// Check that if request overrides the A-E header, the default is not appended.
6678// See http://crbug.com/47381
6679TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6680 ASSERT_TRUE(test_server_.Start());
6681
6682 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196683 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366684 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446685 HttpRequestHeaders headers;
6686 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196687 req->SetExtraRequestHeaders(headers);
6688 req->Start();
[email protected]255620da2013-08-19 13:14:296689 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446690 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6691 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6692}
6693
[email protected]84f05432013-03-15 01:00:126694// Check that setting the A-C header sends the proper header.
6695TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446696 ASSERT_TRUE(test_server_.Start());
6697
6698 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196699 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366700 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446701 HttpRequestHeaders headers;
6702 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196703 req->SetExtraRequestHeaders(headers);
6704 req->Start();
[email protected]255620da2013-08-19 13:14:296705 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446706 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6707}
6708
6709// Check that default User-Agent header is sent.
6710TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6711 ASSERT_TRUE(test_server_.Start());
6712
6713 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196714 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366715 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196716 req->Start();
[email protected]255620da2013-08-19 13:14:296717 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196718 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376719 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446720}
6721
6722// Check that if request overrides the User-Agent header,
6723// the default is not appended.
6724TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6725 ASSERT_TRUE(test_server_.Start());
6726
6727 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196728 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366729 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446730 HttpRequestHeaders headers;
6731 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196732 req->SetExtraRequestHeaders(headers);
6733 req->Start();
[email protected]255620da2013-08-19 13:14:296734 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356735 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446736}
6737
[email protected]ee4c30d2012-11-07 15:08:436738// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6739// User-Agent header to be sent but does not send the Accept-Language and
6740// Accept-Charset headers.
6741TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6742 ASSERT_TRUE(test_server_.Start());
6743
[email protected]ceefd7fd2012-11-29 00:36:246744 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436745 TestURLRequestContext context(true);
6746 context.set_network_delegate(&network_delegate);
6747 context.Init();
6748 // We override the HttpUserAgentSettings after initialization because empty
6749 // entries get overridden by Init().
6750 context.set_http_user_agent_settings(NULL);
6751
6752 struct {
6753 const char* request;
6754 const char* expected_response;
6755 } tests[] = { { "echoheader?Accept-Language", "None" },
6756 { "echoheader?Accept-Charset", "None" },
6757 { "echoheader?User-Agent", "" } };
6758
viettrungluue4a8b882014-10-16 06:17:386759 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436760 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196761 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366762 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196763 req->Start();
[email protected]255620da2013-08-19 13:14:296764 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436765 EXPECT_EQ(tests[i].expected_response, d.data_received())
6766 << " Request = \"" << tests[i].request << "\"";
6767 }
6768}
6769
[email protected]5033ab82013-03-22 20:17:466770// Make sure that URLRequest passes on its priority updates to
6771// newly-created jobs after the first one.
6772TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6773 ASSERT_TRUE(test_server_.Start());
6774
6775 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196776 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366777 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196778 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466779
6780 scoped_refptr<URLRequestRedirectJob> redirect_job =
6781 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196782 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096783 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506784 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466785
[email protected]f7022f32014-08-21 16:32:196786 req->SetPriority(LOW);
6787 req->Start();
6788 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466789
6790 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196791 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506792 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466793
6794 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296795 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466796 EXPECT_EQ(LOW, job->priority());
6797}
6798
[email protected]80abdad2014-03-15 00:20:546799// Check that creating a network request while entering/exiting suspend mode
6800// fails as it should. This is the only case where an HttpTransactionFactory
6801// does not return an HttpTransaction.
6802TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6803 // Create a new HttpNetworkLayer that thinks it's suspended.
6804 HttpNetworkSession::Params params;
6805 params.host_resolver = default_context_.host_resolver();
6806 params.cert_verifier = default_context_.cert_verifier();
6807 params.transport_security_state = default_context_.transport_security_state();
6808 params.proxy_service = default_context_.proxy_service();
6809 params.ssl_config_service = default_context_.ssl_config_service();
6810 params.http_auth_handler_factory =
6811 default_context_.http_auth_handler_factory();
6812 params.network_delegate = &default_network_delegate_;
6813 params.http_server_properties = default_context_.http_server_properties();
6814 scoped_ptr<HttpNetworkLayer> network_layer(
6815 new HttpNetworkLayer(new HttpNetworkSession(params)));
6816 network_layer->OnSuspend();
6817
6818 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6819 HttpCache::DefaultBackend::InMemory(0));
6820
6821 TestURLRequestContext context(true);
6822 context.set_http_transaction_factory(&http_cache);
6823 context.Init();
6824
6825 TestDelegate d;
davidben151423e2015-03-23 18:48:366826 scoped_ptr<URLRequest> req(
6827 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196828 req->Start();
[email protected]80abdad2014-03-15 00:20:546829 base::RunLoop().Run();
6830
6831 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196832 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6833 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546834}
6835
6836// Check that creating a network request while entering/exiting suspend mode
6837// fails as it should in the case there is no cache. This is the only case
6838// where an HttpTransactionFactory does not return an HttpTransaction.
6839TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6840 // Create a new HttpNetworkLayer that thinks it's suspended.
6841 HttpNetworkSession::Params params;
6842 params.host_resolver = default_context_.host_resolver();
6843 params.cert_verifier = default_context_.cert_verifier();
6844 params.transport_security_state = default_context_.transport_security_state();
6845 params.proxy_service = default_context_.proxy_service();
6846 params.ssl_config_service = default_context_.ssl_config_service();
6847 params.http_auth_handler_factory =
6848 default_context_.http_auth_handler_factory();
6849 params.network_delegate = &default_network_delegate_;
6850 params.http_server_properties = default_context_.http_server_properties();
6851 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6852 network_layer.OnSuspend();
6853
6854 TestURLRequestContext context(true);
6855 context.set_http_transaction_factory(&network_layer);
6856 context.Init();
6857
6858 TestDelegate d;
davidben151423e2015-03-23 18:48:366859 scoped_ptr<URLRequest> req(
6860 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196861 req->Start();
[email protected]80abdad2014-03-15 00:20:546862 base::RunLoop().Run();
6863
6864 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196865 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6866 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546867}
6868
ttuttlec0c828492015-05-15 01:25:556869TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
6870 ASSERT_TRUE(test_server_.Start());
6871
6872 TestDelegate d;
6873 GURL test_url(test_server_.GetURL(std::string()));
6874 scoped_ptr<URLRequest> req(
6875 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6876
6877 req->Start();
6878 base::RunLoop().Run();
6879
6880 EXPECT_TRUE(req->response_info().network_accessed);
6881}
6882
6883TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
6884 ASSERT_TRUE(test_server_.Start());
6885
6886 // Populate the cache.
6887 TestDelegate d;
6888 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6889 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
6890 req->Start();
6891 base::RunLoop().Run();
6892
6893 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6894 EXPECT_TRUE(req->response_info().network_accessed);
6895 EXPECT_FALSE(req->response_info().was_cached);
6896
6897 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
6898 DEFAULT_PRIORITY, &d);
6899 req->Start();
6900 base::RunLoop().Run();
6901
6902 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6903 EXPECT_FALSE(req->response_info().network_accessed);
6904 EXPECT_TRUE(req->response_info().was_cached);
6905}
6906
6907TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
6908 ASSERT_TRUE(test_server_.Start());
6909
6910 TestDelegate d;
6911 GURL test_url(test_server_.GetURL(std::string()));
6912 scoped_ptr<URLRequest> req(
6913 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6914 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
6915
6916 req->Start();
6917 base::RunLoop().Run();
6918
6919 EXPECT_FALSE(req->response_info().network_accessed);
6920}
6921
bengr1bf8e942014-11-07 01:36:506922class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6923 public:
6924 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6925 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6926 // tests into the factory tests.
6927 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6928 }
6929
6930 void SetUpFactory() override {
6931 interceptor_ = new MockURLRequestInterceptor();
6932 job_factory_.reset(new URLRequestInterceptingJobFactory(
6933 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6934 }
6935
6936 MockURLRequestInterceptor* interceptor() const {
6937 return interceptor_;
6938 }
6939
6940 private:
6941 MockURLRequestInterceptor* interceptor_;
6942};
6943
6944TEST_F(URLRequestInterceptorTestHTTP,
6945 NetworkDelegateNotificationOnRedirectIntercept) {
6946 interceptor()->set_intercept_redirect(true);
6947 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6948 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6949
6950 ASSERT_TRUE(test_server()->Start());
6951
6952 TestDelegate d;
6953 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366954 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506955 req->Start();
6956 base::RunLoop().Run();
6957
6958 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6959 // Check we got one good response
6960 EXPECT_TRUE(req->status().is_success());
6961 if (req->status().is_success())
6962 EXPECT_EQ(200, req->response_headers()->response_code());
6963
6964 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6965 EXPECT_EQ(1, d.response_started_count());
6966 EXPECT_EQ(0, d.received_redirect_count());
6967
6968 EXPECT_EQ(1, default_network_delegate()->created_requests());
6969 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6970 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6971}
6972
6973TEST_F(URLRequestInterceptorTestHTTP,
6974 NetworkDelegateNotificationOnErrorIntercept) {
6975 // Intercept that error and respond with an OK response.
6976 interceptor()->set_intercept_final_response(true);
6977 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6978 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6979 default_network_delegate()->set_can_be_intercepted_on_error(true);
6980
6981 ASSERT_TRUE(test_server()->Start());
6982
6983 TestDelegate d;
6984 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6985 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366986 &d));
bengr1bf8e942014-11-07 01:36:506987 req->set_method("GET");
6988 req->Start();
6989 base::RunLoop().Run();
6990
6991 EXPECT_TRUE(interceptor()->did_intercept_final());
6992
6993 // Check we received one good response.
6994 EXPECT_TRUE(req->status().is_success());
6995 if (req->status().is_success())
6996 EXPECT_EQ(200, req->response_headers()->response_code());
6997 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6998 EXPECT_EQ(1, d.response_started_count());
6999 EXPECT_EQ(0, d.received_redirect_count());
7000
7001 EXPECT_EQ(1, default_network_delegate()->created_requests());
7002 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7003 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7004}
7005
7006TEST_F(URLRequestInterceptorTestHTTP,
7007 NetworkDelegateNotificationOnResponseIntercept) {
7008 // Intercept that error and respond with an OK response.
7009 interceptor()->set_intercept_final_response(true);
7010
7011 // Intercept with a real URLRequestHttpJob.
7012 interceptor()->set_use_url_request_http_job(true);
7013
7014 ASSERT_TRUE(test_server()->Start());
7015
7016 TestDelegate d;
7017 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367018 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507019 req->set_method("GET");
7020 req->Start();
7021 base::RunLoop().Run();
7022
7023 EXPECT_TRUE(interceptor()->did_intercept_final());
7024
7025 // Check we received one good response.
7026 EXPECT_TRUE(req->status().is_success());
7027 if (req->status().is_success())
7028 EXPECT_EQ(200, req->response_headers()->response_code());
7029 EXPECT_EQ("hello", d.data_received());
7030 EXPECT_EQ(1, d.response_started_count());
7031 EXPECT_EQ(0, d.received_redirect_count());
7032
7033 EXPECT_EQ(1, default_network_delegate()->created_requests());
7034 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7035 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7036}
7037
mkwst0c5eab872014-11-21 14:18:547038class URLRequestTestReferrerPolicy : public URLRequestTest {
7039 public:
7040 URLRequestTestReferrerPolicy() {}
7041
7042 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7043 origin_server_.reset(new SpawnedTestServer(
7044 origin_type, SpawnedTestServer::kLocalhost,
7045 origin_type == SpawnedTestServer::TYPE_HTTPS
7046 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477047 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547048 ASSERT_TRUE(origin_server_->Start());
7049 }
7050
7051 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7052 SpawnedTestServer::Type destination_type) {
7053 origin_server_.reset(new SpawnedTestServer(
7054 origin_type, SpawnedTestServer::kLocalhost,
7055 origin_type == SpawnedTestServer::TYPE_HTTPS
7056 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477057 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547058 ASSERT_TRUE(origin_server_->Start());
7059
7060 destination_server_.reset(new SpawnedTestServer(
7061 destination_type, SpawnedTestServer::kLocalhost,
7062 destination_type == SpawnedTestServer::TYPE_HTTPS
7063 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
mmenke9f2ec60c2015-06-01 20:59:477064 : base::FilePath(kTestFilePath)));
mkwst0c5eab872014-11-21 14:18:547065 ASSERT_TRUE(destination_server_->Start());
7066 }
7067
7068 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7069 const GURL& referrer,
7070 const GURL& expected) {
7071 // Create and execute the request: we'll only have a |destination_server_|
7072 // if the origins are meant to be distinct. Otherwise, we'll use the
7073 // |origin_server_| for both endpoints.
7074 GURL destination_url =
7075 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7076 : origin_server_->GetURL("echoheader?Referer");
7077 GURL origin_url =
7078 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7079
7080 TestDelegate d;
7081 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367082 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547083 req->set_referrer_policy(policy);
7084 req->SetReferrer(referrer.spec());
7085 req->Start();
7086 base::RunLoop().Run();
7087
7088 EXPECT_EQ(1, d.response_started_count());
7089 EXPECT_EQ(1, d.received_redirect_count());
7090 EXPECT_EQ(destination_url, req->url());
7091 EXPECT_TRUE(req->status().is_success());
7092 EXPECT_EQ(200, req->response_headers()->response_code());
7093
7094 EXPECT_EQ(expected.spec(), req->referrer());
7095 if (expected.is_empty())
7096 EXPECT_EQ("None", d.data_received());
7097 else
7098 EXPECT_EQ(expected.spec(), d.data_received());
7099 }
7100
7101 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7102
7103 private:
7104 scoped_ptr<SpawnedTestServer> origin_server_;
7105 scoped_ptr<SpawnedTestServer> destination_server_;
7106};
7107
7108TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7109 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7110
7111 VerifyReferrerAfterRedirect(
7112 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7113 origin_server()->GetURL("path/to/file.html"),
7114 origin_server()->GetURL("path/to/file.html"));
7115
7116 VerifyReferrerAfterRedirect(
7117 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7118 origin_server()->GetURL("path/to/file.html"),
7119 origin_server()->GetURL("path/to/file.html"));
7120
7121 VerifyReferrerAfterRedirect(
7122 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7123 origin_server()->GetURL("path/to/file.html"),
7124 origin_server()->GetURL("path/to/file.html"));
7125
7126 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7127 origin_server()->GetURL("path/to/file.html"),
7128 origin_server()->GetURL("path/to/file.html"));
7129}
7130
7131TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7132 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7133 SpawnedTestServer::TYPE_HTTP);
7134
7135 VerifyReferrerAfterRedirect(
7136 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7137 origin_server()->GetURL("path/to/file.html"),
7138 origin_server()->GetURL("path/to/file.html"));
7139
7140 VerifyReferrerAfterRedirect(
7141 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7142 origin_server()->GetURL("path/to/file.html"),
7143 origin_server()->GetURL(std::string()));
7144
7145 VerifyReferrerAfterRedirect(
7146 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7147 origin_server()->GetURL("path/to/file.html"),
7148 origin_server()->GetURL(std::string()));
7149
7150 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7151 origin_server()->GetURL("path/to/file.html"),
7152 origin_server()->GetURL("path/to/file.html"));
7153}
7154
7155TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7156 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7157
7158 VerifyReferrerAfterRedirect(
7159 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7160 origin_server()->GetURL("path/to/file.html"),
7161 origin_server()->GetURL("path/to/file.html"));
7162
7163 VerifyReferrerAfterRedirect(
7164 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7165 origin_server()->GetURL("path/to/file.html"),
7166 origin_server()->GetURL("path/to/file.html"));
7167
7168 VerifyReferrerAfterRedirect(
7169 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7170 origin_server()->GetURL("path/to/file.html"),
7171 origin_server()->GetURL("path/to/file.html"));
7172
7173 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7174 origin_server()->GetURL("path/to/file.html"),
7175 origin_server()->GetURL("path/to/file.html"));
7176}
7177
7178TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7179 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7180 SpawnedTestServer::TYPE_HTTPS);
7181
7182 VerifyReferrerAfterRedirect(
7183 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7184 origin_server()->GetURL("path/to/file.html"),
7185 origin_server()->GetURL("path/to/file.html"));
7186
7187 VerifyReferrerAfterRedirect(
7188 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7189 origin_server()->GetURL("path/to/file.html"),
7190 origin_server()->GetURL(std::string()));
7191
7192 VerifyReferrerAfterRedirect(
7193 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7194 origin_server()->GetURL("path/to/file.html"),
7195 origin_server()->GetURL(std::string()));
7196
7197 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7198 origin_server()->GetURL("path/to/file.html"),
7199 origin_server()->GetURL("path/to/file.html"));
7200}
7201
7202TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7203 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7204 SpawnedTestServer::TYPE_HTTPS);
7205
7206 VerifyReferrerAfterRedirect(
7207 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7208 origin_server()->GetURL("path/to/file.html"),
7209 origin_server()->GetURL("path/to/file.html"));
7210
7211 VerifyReferrerAfterRedirect(
7212 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7213 origin_server()->GetURL("path/to/file.html"),
7214 origin_server()->GetURL(std::string()));
7215
7216 VerifyReferrerAfterRedirect(
7217 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7218 origin_server()->GetURL("path/to/file.html"),
7219 origin_server()->GetURL(std::string()));
7220
7221 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7222 origin_server()->GetURL("path/to/file.html"),
7223 origin_server()->GetURL("path/to/file.html"));
7224}
7225
7226TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7227 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7228 SpawnedTestServer::TYPE_HTTP);
7229
7230 VerifyReferrerAfterRedirect(
7231 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7232 origin_server()->GetURL("path/to/file.html"), GURL());
7233
7234 VerifyReferrerAfterRedirect(
7235 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7236 origin_server()->GetURL("path/to/file.html"), GURL());
7237
7238 VerifyReferrerAfterRedirect(
7239 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7240 origin_server()->GetURL("path/to/file.html"),
7241 origin_server()->GetURL(std::string()));
7242
7243 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7244 origin_server()->GetURL("path/to/file.html"),
7245 origin_server()->GetURL("path/to/file.html"));
7246}
7247
[email protected]73e0bba2009-02-19 22:57:097248class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507249 public:
[email protected]ef2bf422012-05-11 03:27:097250 HTTPSRequestTest() : default_context_(true) {
7251 default_context_.set_network_delegate(&default_network_delegate_);
7252 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507253 }
dcheng67be2b1f2014-10-27 21:47:297254 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507255
7256 protected:
[email protected]ceefd7fd2012-11-29 00:36:247257 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097258 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467259};
7260
[email protected]c044616e2013-02-20 02:01:267261TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227262 SpawnedTestServer test_server(
7263 SpawnedTestServer::TYPE_HTTPS,
7264 SpawnedTestServer::kLocalhost,
7265 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117266 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467267
[email protected]ea224582008-12-07 20:25:467268 TestDelegate d;
7269 {
[email protected]f7022f32014-08-21 16:32:197270 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367271 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197272 r->Start();
7273 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467274
[email protected]255620da2013-08-19 13:14:297275 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467276
7277 EXPECT_EQ(1, d.response_started_count());
7278 EXPECT_FALSE(d.received_data_before_response());
7279 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197280 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197281 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197282 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197283 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197284 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467285 }
[email protected]ea224582008-12-07 20:25:467286}
7287
[email protected]5774ada2010-07-15 06:30:547288TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227289 SpawnedTestServer::SSLOptions ssl_options(
7290 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7291 SpawnedTestServer test_server(
7292 SpawnedTestServer::TYPE_HTTPS,
7293 ssl_options,
7294 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117295 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337296
7297 bool err_allowed = true;
7298 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7299 TestDelegate d;
7300 {
7301 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197302 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367303 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337304
[email protected]f7022f32014-08-21 16:32:197305 r->Start();
7306 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337307
[email protected]255620da2013-08-19 13:14:297308 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337309
7310 EXPECT_EQ(1, d.response_started_count());
7311 EXPECT_FALSE(d.received_data_before_response());
7312 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177313 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337314 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197315 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177316 } else {
[email protected]bacff652009-03-31 17:50:337317 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177318 }
[email protected]bacff652009-03-31 17:50:337319 }
7320 }
7321}
7322
[email protected]5774ada2010-07-15 06:30:547323TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227324 SpawnedTestServer::SSLOptions ssl_options(
7325 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7326 SpawnedTestServer test_server(
7327 SpawnedTestServer::TYPE_HTTPS,
7328 ssl_options,
7329 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117330 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337331
7332 // Iterate from false to true, just so that we do the opposite of the
7333 // previous test in order to increase test coverage.
7334 bool err_allowed = false;
7335 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7336 TestDelegate d;
7337 {
7338 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197339 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367340 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337341
[email protected]f7022f32014-08-21 16:32:197342 r->Start();
7343 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337344
[email protected]255620da2013-08-19 13:14:297345 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337346
7347 EXPECT_EQ(1, d.response_started_count());
7348 EXPECT_FALSE(d.received_data_before_response());
7349 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177350 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337351 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197352 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177353 } else {
[email protected]bacff652009-03-31 17:50:337354 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177355 }
[email protected]bacff652009-03-31 17:50:337356 }
7357 }
7358}
[email protected]73e0bba2009-02-19 22:57:097359
davidbena4c9d062015-04-03 22:34:257360// Tests that servers which require a deprecated cipher suite still work.
7361TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517362 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257363 default_context_.set_net_log(&net_log);
7364
7365 SpawnedTestServer::SSLOptions ssl_options;
7366 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7367 SpawnedTestServer test_server(
7368 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7369 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7370 ASSERT_TRUE(test_server.Start());
7371
7372 TestDelegate d;
7373 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7374 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7375 r->Start();
7376 EXPECT_TRUE(r->is_pending());
7377
7378 base::RunLoop().Run();
7379
7380 EXPECT_EQ(1, d.response_started_count());
7381 EXPECT_FALSE(d.received_data_before_response());
7382 EXPECT_NE(0, d.bytes_received());
7383 CheckSSLInfo(r->ssl_info());
7384 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7385 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7386
7387 // No version downgrade should have been necessary.
7388 EXPECT_FALSE(r->ssl_info().connection_status &
7389 SSL_CONNECTION_VERSION_FALLBACK);
7390 int expected_version = SSL_CONNECTION_VERSION_TLS1_2;
7391 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7392 SSL_PROTOCOL_VERSION_TLS1_2) {
7393 expected_version = SSL_CONNECTION_VERSION_TLS1_1;
7394 }
7395 EXPECT_EQ(expected_version,
7396 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7397
mmenke43758e62015-05-04 21:09:467398 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257399 net_log.GetEntries(&entries);
7400 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7401 NetLog::PHASE_NONE);
7402}
7403
[email protected]316c1e5e2012-09-12 15:17:447404// This tests that a load of www.google.com with a certificate error sets
7405// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7406// the interstitial to be fatal.
7407TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227408 SpawnedTestServer::SSLOptions ssl_options(
7409 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7410 SpawnedTestServer test_server(
7411 SpawnedTestServer::TYPE_HTTPS,
7412 ssl_options,
7413 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447414 ASSERT_TRUE(test_server.Start());
7415
7416 // We require that the URL be www.google.com in order to pick up the
7417 // preloaded HSTS entries in the TransportSecurityState. This means that we
7418 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247419 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447420
7421 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247422 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447423 TestURLRequestContext context(true);
7424 context.set_network_delegate(&network_delegate);
7425 context.set_host_resolver(&host_resolver);
7426 TransportSecurityState transport_security_state;
7427 context.set_transport_security_state(&transport_security_state);
7428 context.Init();
7429
7430 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197431 scoped_ptr<URLRequest> r(context.CreateRequest(
7432 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367433 test_server.host_port_pair().port())),
7434 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447435
[email protected]f7022f32014-08-21 16:32:197436 r->Start();
7437 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447438
[email protected]255620da2013-08-19 13:14:297439 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447440
7441 EXPECT_EQ(1, d.response_started_count());
7442 EXPECT_FALSE(d.received_data_before_response());
7443 EXPECT_TRUE(d.have_certificate_errors());
7444 EXPECT_TRUE(d.certificate_errors_are_fatal());
7445}
7446
7447// This tests that cached HTTPS page loads do not cause any updates to the
7448// TransportSecurityState.
7449TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7450 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7451 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227452 SpawnedTestServer::SSLOptions ssl_options(
7453 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7454 SpawnedTestServer test_server(
7455 SpawnedTestServer::TYPE_HTTPS,
7456 ssl_options,
7457 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447458 ASSERT_TRUE(test_server.Start());
7459
[email protected]9e6968d2014-05-07 21:46:267460 // We require that the URL be www.google.com in order to pick up the static
7461 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7462 // that we have to use a MockHostResolver in order to direct www.google.com to
7463 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447464
7465 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247466 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447467 TestURLRequestContext context(true);
7468 context.set_network_delegate(&network_delegate);
7469 context.set_host_resolver(&host_resolver);
7470 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267471
7472 TransportSecurityState::DomainState static_domain_state;
7473 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127474 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447475 context.set_transport_security_state(&transport_security_state);
7476 context.Init();
7477
[email protected]9e6968d2014-05-07 21:46:267478 TransportSecurityState::DomainState dynamic_domain_state;
7479 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7480 "www.google.com", &dynamic_domain_state));
7481
[email protected]316c1e5e2012-09-12 15:17:447482 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197483 scoped_ptr<URLRequest> r(context.CreateRequest(
7484 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367485 test_server.host_port_pair().port())),
7486 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447487
[email protected]f7022f32014-08-21 16:32:197488 r->Start();
7489 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447490
[email protected]255620da2013-08-19 13:14:297491 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447492
7493 EXPECT_EQ(1, d.response_started_count());
7494 EXPECT_FALSE(d.received_data_before_response());
7495 EXPECT_TRUE(d.have_certificate_errors());
7496 EXPECT_TRUE(d.certificate_errors_are_fatal());
7497
[email protected]9e6968d2014-05-07 21:46:267498 // Get a fresh copy of the states, and check that they haven't changed.
7499 TransportSecurityState::DomainState new_static_domain_state;
7500 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127501 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267502 TransportSecurityState::DomainState new_dynamic_domain_state;
7503 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7504 "www.google.com", &new_dynamic_domain_state));
7505
7506 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7507 static_domain_state.sts.upgrade_mode);
7508 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7509 static_domain_state.sts.include_subdomains);
7510 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7511 static_domain_state.pkp.include_subdomains);
7512 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7513 static_domain_state.pkp.spki_hashes));
7514 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7515 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447516}
7517
[email protected]8ccc69f2012-11-28 19:52:147518// Make sure HSTS preserves a POST request's method and body.
7519TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7520 static const char kData[] = "hello world";
7521
[email protected]ce7d0cbc2013-05-03 18:57:227522 SpawnedTestServer::SSLOptions ssl_options(
7523 SpawnedTestServer::SSLOptions::CERT_OK);
7524 SpawnedTestServer test_server(
7525 SpawnedTestServer::TYPE_HTTPS,
7526 ssl_options,
7527 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147528 ASSERT_TRUE(test_server.Start());
7529
7530
7531 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7532 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227533 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7534 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147535 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147536
7537 // Force https for www.somewhere.com.
7538 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207539 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7540 bool include_subdomains = false;
7541 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7542 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147543
7544 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7545
7546 TestURLRequestContext context(true);
7547 context.set_host_resolver(&host_resolver);
7548 context.set_transport_security_state(&transport_security_state);
7549 context.set_network_delegate(&network_delegate);
7550 context.Init();
7551
7552 TestDelegate d;
7553 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7554 // cause a certificate error. Ignore the error.
7555 d.set_allow_certificate_errors(true);
7556
[email protected]f7022f32014-08-21 16:32:197557 scoped_ptr<URLRequest> req(context.CreateRequest(
7558 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367559 test_server.host_port_pair().port())),
7560 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197561 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077562 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147563
[email protected]f7022f32014-08-21 16:32:197564 req->Start();
[email protected]255620da2013-08-19 13:14:297565 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147566
[email protected]f7022f32014-08-21 16:32:197567 EXPECT_EQ("https", req->url().scheme());
7568 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147569 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407570
7571 LoadTimingInfo load_timing_info;
7572 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7573 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7574 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147575}
7576
rob4e0be1f2014-09-11 23:40:227577// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7578TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7579 static const char kOriginHeaderValue[] = "http://www.example.com";
7580
7581 SpawnedTestServer::SSLOptions ssl_options(
7582 SpawnedTestServer::SSLOptions::CERT_OK);
7583 SpawnedTestServer test_server(
7584 SpawnedTestServer::TYPE_HTTPS,
7585 ssl_options,
7586 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7587 ASSERT_TRUE(test_server.Start());
7588
7589 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7590 // address, so a MockHostResolver is needed to redirect example.net to the
7591 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7592 MockHostResolver host_resolver;
7593
7594 TransportSecurityState transport_security_state;
7595 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7596 bool include_subdomains = false;
7597 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7598
7599 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7600
7601 MockCertVerifier cert_verifier;
7602 cert_verifier.set_default_result(OK);
7603
7604 TestURLRequestContext context(true);
7605 context.set_host_resolver(&host_resolver);
7606 context.set_transport_security_state(&transport_security_state);
7607 context.set_network_delegate(&network_delegate);
7608 context.set_cert_verifier(&cert_verifier);
7609 context.Init();
7610
7611 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7612 test_server.host_port_pair().port()));
7613 url::Replacements<char> replacements;
7614 const char kNewScheme[] = "https";
7615 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7616 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7617
7618 TestDelegate d;
7619 // Quit on redirect to allow response header inspection upon redirect.
7620 d.set_quit_on_redirect(true);
7621
davidben151423e2015-03-23 18:48:367622 scoped_ptr<URLRequest> req(
7623 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227624 // Set Origin header to simulate a cross-origin request.
7625 HttpRequestHeaders request_headers;
7626 request_headers.SetHeader("Origin", kOriginHeaderValue);
7627 req->SetExtraRequestHeaders(request_headers);
7628
7629 req->Start();
7630 base::RunLoop().Run();
7631
7632 EXPECT_EQ(1, d.received_redirect_count());
7633
7634 const HttpResponseHeaders* headers = req->response_headers();
7635 std::string redirect_location;
7636 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7637 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7638
7639 std::string received_cors_header;
7640 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7641 &received_cors_header));
7642 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7643}
7644
Adam Ricecb76ac62015-02-20 05:33:257645// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7646// are performed in net/websockets/websocket_end_to_end_test.cc.
7647TEST(WebSocketURLRequestTest, HSTSApplied) {
7648 TestNetworkDelegate network_delegate;
7649 TransportSecurityState transport_security_state;
7650 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7651 bool include_subdomains = false;
7652 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7653 TestURLRequestContext context(true);
7654 context.set_transport_security_state(&transport_security_state);
7655 context.set_network_delegate(&network_delegate);
7656 context.Init();
7657 GURL ws_url("ws://example.net/echo");
7658 TestDelegate delegate;
7659 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367660 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257661 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7662 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7663}
7664
[email protected]316c1e5e2012-09-12 15:17:447665namespace {
7666
7667class SSLClientAuthTestDelegate : public TestDelegate {
7668 public:
7669 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7670 }
dchengb03027d2014-10-21 12:00:207671 void OnCertificateRequested(URLRequest* request,
7672 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447673 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347674 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447675 }
7676 int on_certificate_requested_count() {
7677 return on_certificate_requested_count_;
7678 }
7679 private:
7680 int on_certificate_requested_count_;
7681};
7682
7683} // namespace
7684
7685// TODO(davidben): Test the rest of the code. Specifically,
7686// - Filtering which certificates to select.
7687// - Sending a certificate back.
7688// - Getting a certificate request in an SSL renegotiation sending the
7689// HTTP request.
7690TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227691 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447692 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227693 SpawnedTestServer test_server(
7694 SpawnedTestServer::TYPE_HTTPS,
7695 ssl_options,
7696 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447697 ASSERT_TRUE(test_server.Start());
7698
7699 SSLClientAuthTestDelegate d;
7700 {
[email protected]f7022f32014-08-21 16:32:197701 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367702 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447703
[email protected]f7022f32014-08-21 16:32:197704 r->Start();
7705 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447706
[email protected]255620da2013-08-19 13:14:297707 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447708
7709 EXPECT_EQ(1, d.on_certificate_requested_count());
7710 EXPECT_FALSE(d.received_data_before_response());
7711 EXPECT_EQ(0, d.bytes_received());
7712
7713 // Send no certificate.
7714 // TODO(davidben): Get temporary client cert import (with keys) working on
7715 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197716 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447717
[email protected]255620da2013-08-19 13:14:297718 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447719
7720 EXPECT_EQ(1, d.response_started_count());
7721 EXPECT_FALSE(d.received_data_before_response());
7722 EXPECT_NE(0, d.bytes_received());
7723 }
7724}
7725
7726TEST_F(HTTPSRequestTest, ResumeTest) {
7727 // Test that we attempt a session resume when making two connections to the
7728 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227729 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447730 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227731 SpawnedTestServer test_server(
7732 SpawnedTestServer::TYPE_HTTPS,
7733 ssl_options,
7734 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447735 ASSERT_TRUE(test_server.Start());
7736
7737 SSLClientSocket::ClearSessionCache();
7738
7739 {
7740 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197741 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367742 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447743
[email protected]f7022f32014-08-21 16:32:197744 r->Start();
7745 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447746
[email protected]255620da2013-08-19 13:14:297747 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447748
7749 EXPECT_EQ(1, d.response_started_count());
7750 }
7751
7752 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7753 CloseAllConnections();
7754
7755 {
7756 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197757 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367758 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447759
[email protected]f7022f32014-08-21 16:32:197760 r->Start();
7761 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447762
[email protected]255620da2013-08-19 13:14:297763 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447764
7765 // The response will look like;
7766 // insert abc
7767 // lookup abc
7768 // insert xyz
7769 //
7770 // With a newline at the end which makes the split think that there are
7771 // four lines.
7772
7773 EXPECT_EQ(1, d.response_started_count());
7774 std::vector<std::string> lines;
7775 base::SplitString(d.data_received(), '\n', &lines);
7776 ASSERT_EQ(4u, lines.size()) << d.data_received();
7777
7778 std::string session_id;
7779
7780 for (size_t i = 0; i < 2; i++) {
7781 std::vector<std::string> parts;
7782 base::SplitString(lines[i], '\t', &parts);
7783 ASSERT_EQ(2u, parts.size());
7784 if (i == 0) {
7785 EXPECT_EQ("insert", parts[0]);
7786 session_id = parts[1];
7787 } else {
7788 EXPECT_EQ("lookup", parts[0]);
7789 EXPECT_EQ(session_id, parts[1]);
7790 }
7791 }
7792 }
7793}
7794
Adam Langley32352ad2014-10-14 22:31:007795// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7796// the result of fetching "ssl-session-cache" from the test server, indicates
7797// that exactly two different sessions were inserted, with no lookups etc.
7798static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7799 std::vector<std::string> lines;
7800 base::SplitString(session_info, '\n', &lines);
7801 ASSERT_EQ(3u, lines.size()) << session_info;
7802
7803 std::string session_id;
7804 for (size_t i = 0; i < 2; i++) {
7805 std::vector<std::string> parts;
7806 base::SplitString(lines[i], '\t', &parts);
7807 ASSERT_EQ(2u, parts.size());
7808 EXPECT_EQ("insert", parts[0]);
7809 if (i == 0) {
7810 session_id = parts[1];
7811 } else {
7812 EXPECT_NE(session_id, parts[1]);
7813 }
7814 }
7815}
7816
[email protected]316c1e5e2012-09-12 15:17:447817TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7818 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7819 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227820 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447821 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227822 SpawnedTestServer test_server(
7823 SpawnedTestServer::TYPE_HTTPS,
7824 ssl_options,
7825 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447826 ASSERT_TRUE(test_server.Start());
7827
7828 SSLClientSocket::ClearSessionCache();
7829
7830 {
7831 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197832 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367833 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447834
[email protected]f7022f32014-08-21 16:32:197835 r->Start();
7836 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447837
[email protected]255620da2013-08-19 13:14:297838 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447839
7840 EXPECT_EQ(1, d.response_started_count());
7841 }
7842
7843 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7844 HttpNetworkSession::Params params;
7845 params.host_resolver = default_context_.host_resolver();
7846 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117847 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447848 params.proxy_service = default_context_.proxy_service();
7849 params.ssl_config_service = default_context_.ssl_config_service();
7850 params.http_auth_handler_factory =
7851 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417852 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447853 params.http_server_properties = default_context_.http_server_properties();
7854 params.ssl_session_cache_shard = "alternate";
7855
[email protected]cba24642014-08-15 20:49:597856 scoped_ptr<HttpCache> cache(new HttpCache(
7857 new HttpNetworkSession(params),
7858 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447859
7860 default_context_.set_http_transaction_factory(cache.get());
7861
7862 {
7863 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197864 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367865 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447866
[email protected]f7022f32014-08-21 16:32:197867 r->Start();
7868 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447869
[email protected]255620da2013-08-19 13:14:297870 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447871
7872 // The response will look like;
7873 // insert abc
7874 // insert xyz
7875 //
7876 // With a newline at the end which makes the split think that there are
7877 // three lines.
7878
7879 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007880 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447881 }
7882}
7883
davidben8ecc3072014-09-03 23:19:097884#if defined(OS_WIN)
7885
7886namespace {
7887
7888bool IsECDSACipherSuite(uint16_t cipher_suite) {
7889 const char* key_exchange;
7890 const char* cipher;
7891 const char* mac;
7892 bool is_aead;
7893 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7894 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7895}
7896
7897} // namespace
7898
7899// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7900// verified.
davidben9399c952014-10-07 04:09:117901TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097902 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7903 LOG(INFO) << "Skipping test on this version.";
7904 return;
7905 }
7906
7907 SpawnedTestServer test_server(
7908 SpawnedTestServer::TYPE_HTTPS,
7909 SpawnedTestServer::kLocalhost,
7910 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7911 ASSERT_TRUE(test_server.Start());
7912
7913 TestDelegate d;
7914 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367915 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:097916 r->Start();
7917 EXPECT_TRUE(r->is_pending());
7918
7919 base::RunLoop().Run();
7920
7921 EXPECT_EQ(1, d.response_started_count());
7922 std::vector<std::string> lines;
7923 base::SplitString(d.data_received(), '\n', &lines);
7924
7925 for (size_t i = 0; i < lines.size(); i++) {
7926 int cipher_suite;
7927 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7928 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7929 << "ClientHello advertised " << cipher_suite;
7930 }
7931}
7932
7933#endif // OS_WIN
7934
Adam Langley32352ad2014-10-14 22:31:007935class TestSSLConfigService : public SSLConfigService {
7936 public:
7937 TestSSLConfigService(bool ev_enabled,
7938 bool online_rev_checking,
7939 bool rev_checking_required_local_anchors)
7940 : ev_enabled_(ev_enabled),
7941 online_rev_checking_(online_rev_checking),
7942 rev_checking_required_local_anchors_(
7943 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027944 min_version_(kDefaultSSLVersionMin),
7945 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7946
7947 void set_min_version(uint16 version) {
7948 min_version_ = version;
7949 }
Adam Langley32352ad2014-10-14 22:31:007950
7951 void set_fallback_min_version(uint16 version) {
7952 fallback_min_version_ = version;
7953 }
7954
7955 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207956 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007957 *config = SSLConfig();
7958 config->rev_checking_enabled = online_rev_checking_;
7959 config->verify_ev_cert = ev_enabled_;
7960 config->rev_checking_required_local_anchors =
7961 rev_checking_required_local_anchors_;
7962 if (fallback_min_version_) {
7963 config->version_fallback_min = fallback_min_version_;
7964 }
Adam Langleyac6f24b42014-10-31 20:24:027965 if (min_version_) {
7966 config->version_min = min_version_;
7967 }
Adam Langley32352ad2014-10-14 22:31:007968 }
7969
7970 protected:
dchengb03027d2014-10-21 12:00:207971 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007972
7973 private:
7974 const bool ev_enabled_;
7975 const bool online_rev_checking_;
7976 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027977 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007978 uint16 fallback_min_version_;
7979};
7980
7981class FallbackTestURLRequestContext : public TestURLRequestContext {
7982 public:
7983 explicit FallbackTestURLRequestContext(bool delay_initialization)
7984 : TestURLRequestContext(delay_initialization) {}
7985
7986 void set_fallback_min_version(uint16 version) {
7987 TestSSLConfigService *ssl_config_service =
7988 new TestSSLConfigService(true /* check for EV */,
7989 false /* online revocation checking */,
7990 false /* require rev. checking for local
7991 anchors */);
Adam Langley32352ad2014-10-14 22:31:007992 ssl_config_service->set_fallback_min_version(version);
7993 set_ssl_config_service(ssl_config_service);
7994 }
7995};
7996
[email protected]48d2b7c52014-06-27 01:16:557997class HTTPSFallbackTest : public testing::Test {
7998 public:
Adam Langley32352ad2014-10-14 22:31:007999 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298000 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558001
8002 protected:
8003 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8004 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008005 context_.Init();
8006 delegate_.set_allow_certificate_errors(true);
8007
[email protected]48d2b7c52014-06-27 01:16:558008 SpawnedTestServer test_server(
8009 SpawnedTestServer::TYPE_HTTPS,
8010 ssl_options,
8011 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8012 ASSERT_TRUE(test_server.Start());
8013
davidben151423e2015-03-23 18:48:368014 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
8015 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558016 request_->Start();
8017
8018 base::RunLoop().Run();
8019 }
8020
Adam Langley32352ad2014-10-14 22:31:008021 void set_fallback_min_version(uint16 version) {
8022 context_.set_fallback_min_version(version);
8023 }
8024
[email protected]48d2b7c52014-06-27 01:16:558025 void ExpectConnection(int version) {
8026 EXPECT_EQ(1, delegate_.response_started_count());
8027 EXPECT_NE(0, delegate_.bytes_received());
8028 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8029 request_->ssl_info().connection_status));
8030 EXPECT_TRUE(request_->ssl_info().connection_status &
8031 SSL_CONNECTION_VERSION_FALLBACK);
8032 }
8033
8034 void ExpectFailure(int error) {
8035 EXPECT_EQ(1, delegate_.response_started_count());
8036 EXPECT_FALSE(request_->status().is_success());
8037 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8038 EXPECT_EQ(error, request_->status().error());
8039 }
8040
8041 private:
8042 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008043 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558044 scoped_ptr<URLRequest> request_;
8045};
8046
8047// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
8048// than necessary.
8049TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
8050 SpawnedTestServer::SSLOptions ssl_options(
8051 SpawnedTestServer::SSLOptions::CERT_OK);
8052 ssl_options.tls_intolerant =
8053 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8054
8055 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8056 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8057}
8058
8059// This test is disabled on Android because the remote test server doesn't cause
8060// a TCP reset.
8061#if !defined(OS_ANDROID)
8062// Tests fallback to TLS 1.0 on connection reset.
8063TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
8064 SpawnedTestServer::SSLOptions ssl_options(
8065 SpawnedTestServer::SSLOptions::CERT_OK);
8066 ssl_options.tls_intolerant =
8067 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8068 ssl_options.tls_intolerance_type =
8069 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8070
8071 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8072 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8073}
8074#endif // !OS_ANDROID
8075
[email protected]12833302014-07-02 01:57:318076// Tests that we don't fallback on handshake failure with servers that implement
8077// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558078TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558079 SpawnedTestServer::SSLOptions ssl_options(
8080 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438081 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558082 // a version fallback.
8083 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438084 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558085 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8086 // connections are rejected.
8087 ssl_options.fallback_scsv_enabled = true;
8088
8089 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8090
8091 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8092 // intolerance. If the fallback SCSV is processed when the original error
8093 // that caused the fallback should be returned, which should be
8094 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8095 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8096}
8097
[email protected]12833302014-07-02 01:57:318098// Tests that we don't fallback on connection closed with servers that implement
8099// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318100TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318101 SpawnedTestServer::SSLOptions ssl_options(
8102 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438103 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318104 // a version fallback.
8105 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438106 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318107 ssl_options.tls_intolerance_type =
8108 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8109 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8110 // connections are rejected.
8111 ssl_options.fallback_scsv_enabled = true;
8112
8113 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8114
8115 // The original error should be replayed on rejected fallback.
8116 ExpectFailure(ERR_CONNECTION_CLOSED);
8117}
8118
davidbenb937d6c2015-05-14 04:53:428119// Tests that the SSLv3 fallback doesn't happen.
[email protected]48d2b7c52014-06-27 01:16:558120TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
8121 SpawnedTestServer::SSLOptions ssl_options(
8122 SpawnedTestServer::SSLOptions::CERT_OK);
8123 ssl_options.tls_intolerant =
8124 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8125
8126 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:028127 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:008128}
8129
davidbenb937d6c2015-05-14 04:53:428130// Tests that the TLSv1 fallback triggers on closed connections.
[email protected]48d2b7c52014-06-27 01:16:558131TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8132 SpawnedTestServer::SSLOptions ssl_options(
8133 SpawnedTestServer::SSLOptions::CERT_OK);
8134 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428135 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558136 ssl_options.tls_intolerance_type =
8137 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
[email protected]48d2b7c52014-06-27 01:16:558138
8139 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb937d6c2015-05-14 04:53:428140 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
[email protected]48d2b7c52014-06-27 01:16:558141}
8142
davidbenb937d6c2015-05-14 04:53:428143// Test that fallback probe connections don't cause sessions to be cached.
8144TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008145 SpawnedTestServer::SSLOptions ssl_options(
8146 SpawnedTestServer::SSLOptions::CERT_OK);
8147 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428148 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008149 ssl_options.tls_intolerance_type =
8150 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8151 ssl_options.record_resume = true;
8152
8153 SpawnedTestServer test_server(
8154 SpawnedTestServer::TYPE_HTTPS,
8155 ssl_options,
8156 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8157 ASSERT_TRUE(test_server.Start());
8158
8159 SSLClientSocket::ClearSessionCache();
8160
davidbenb937d6c2015-05-14 04:53:428161 // Make a connection that does a probe fallback to TLSv1 but fails because
8162 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008163 // be inserted locally.
8164 {
8165 TestDelegate delegate;
8166 FallbackTestURLRequestContext context(true);
8167
davidbenb937d6c2015-05-14 04:53:428168 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008169 context.Init();
8170 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368171 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008172 request->Start();
8173
8174 base::RunLoop().Run();
8175
8176 EXPECT_EQ(1, delegate.response_started_count());
8177 EXPECT_FALSE(request->status().is_success());
8178 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8179 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8180 request->status().error());
8181 }
8182
davidbenb937d6c2015-05-14 04:53:428183 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008184 {
8185 TestDelegate delegate;
8186 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428187 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008188
8189 context.Init();
davidben151423e2015-03-23 18:48:368190 scoped_ptr<URLRequest> request(context.CreateRequest(
8191 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008192 request->Start();
8193
8194 base::RunLoop().Run();
8195
8196 EXPECT_EQ(1, delegate.response_started_count());
8197 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428198 EXPECT_EQ(
8199 SSL_CONNECTION_VERSION_TLS1,
8200 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008201 EXPECT_TRUE(request->ssl_info().connection_status &
8202 SSL_CONNECTION_VERSION_FALLBACK);
8203
8204 std::vector<std::string> lines;
8205 // If no sessions were cached then the server should have seen two sessions
8206 // inserted with no lookups.
8207 AssertTwoDistinctSessionsInserted(delegate.data_received());
8208 }
8209}
8210
[email protected]a8fed1742013-12-27 02:14:248211class HTTPSSessionTest : public testing::Test {
8212 public:
8213 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598214 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248215
8216 default_context_.set_network_delegate(&default_network_delegate_);
8217 default_context_.set_cert_verifier(&cert_verifier_);
8218 default_context_.Init();
8219 }
dcheng67be2b1f2014-10-27 21:47:298220 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248221
8222 protected:
8223 MockCertVerifier cert_verifier_;
8224 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8225 TestURLRequestContext default_context_;
8226};
8227
8228// Tests that session resumption is not attempted if an invalid certificate
8229// is presented.
8230TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8231 SpawnedTestServer::SSLOptions ssl_options;
8232 ssl_options.record_resume = true;
8233 SpawnedTestServer test_server(
8234 SpawnedTestServer::TYPE_HTTPS,
8235 ssl_options,
8236 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8237 ASSERT_TRUE(test_server.Start());
8238
8239 SSLClientSocket::ClearSessionCache();
8240
8241 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598242 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248243 {
8244 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198245 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368246 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248247
[email protected]f7022f32014-08-21 16:32:198248 r->Start();
8249 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248250
8251 base::RunLoop().Run();
8252
8253 EXPECT_EQ(1, d.response_started_count());
8254 }
8255
8256 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8257 CloseAllConnections();
8258
8259 // Now change the certificate to be acceptable (so that the response is
8260 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598261 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248262 {
8263 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198264 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368265 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248266
[email protected]f7022f32014-08-21 16:32:198267 r->Start();
8268 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248269
8270 base::RunLoop().Run();
8271
8272 // The response will look like;
8273 // insert abc
8274 // insert xyz
8275 //
8276 // With a newline at the end which makes the split think that there are
8277 // three lines.
8278 //
8279 // If a session was presented (eg: a bug), then the response would look
8280 // like;
8281 // insert abc
8282 // lookup abc
8283 // insert xyz
8284
8285 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008286 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248287 }
8288}
8289
[email protected]dffe8242012-03-20 15:14:278290// This the fingerprint of the "Testing CA" certificate used by the testserver.
8291// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268292static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278293 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8294 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8295
[email protected]51523f52013-07-31 21:57:288296// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8297// testserver.
8298static const SHA256HashValue kOCSPTestCertSPKI = { {
8299 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8300 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8301 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8302 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8303} };
8304
[email protected]dffe8242012-03-20 15:14:278305// This is the policy OID contained in the certificates that testserver
8306// generates.
8307static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8308
8309class HTTPSOCSPTest : public HTTPSRequestTest {
8310 public:
8311 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098312 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088313 ev_test_policy_(
8314 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8315 kOCSPTestCertFingerprint,
8316 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028317 }
8318
dcheng67be2b1f2014-10-27 21:47:298319 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098320 SetupContext(&context_);
8321 context_.Init();
[email protected]dffe8242012-03-20 15:14:278322
[email protected]cba24642014-08-15 20:49:598323 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208324 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428325 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508326 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278327
davidben71f35ff2015-04-17 20:54:488328#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098329 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278330 EnsureNSSHttpIOInit();
8331#endif
8332 }
8333
[email protected]ce7d0cbc2013-05-03 18:57:228334 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278335 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538336 // We always overwrite out_cert_status.
8337 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228338 SpawnedTestServer test_server(
8339 SpawnedTestServer::TYPE_HTTPS,
8340 ssl_options,
8341 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278342 ASSERT_TRUE(test_server.Start());
8343
8344 TestDelegate d;
8345 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198346 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368347 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198348 r->Start();
[email protected]dffe8242012-03-20 15:14:278349
[email protected]255620da2013-08-19 13:14:298350 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278351
8352 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198353 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278354 }
8355
dcheng67be2b1f2014-10-27 21:47:298356 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488357#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278358 ShutdownNSSHttpIO();
8359#endif
8360 }
8361
[email protected]a13234c2012-03-20 21:45:028362 protected:
8363 // SetupContext configures the URLRequestContext that will be used for making
8364 // connetions to testserver. This can be overridden in test subclasses for
8365 // different behaviour.
8366 virtual void SetupContext(URLRequestContext* context) {
8367 context->set_ssl_config_service(
8368 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208369 true /* online revocation checking */,
8370 false /* require rev. checking for local
8371 anchors */));
[email protected]a13234c2012-03-20 21:45:028372 }
8373
[email protected]dffe8242012-03-20 15:14:278374 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098375 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088376 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278377};
8378
[email protected]a13234c2012-03-20 21:45:028379static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018380#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028381 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8382 // have that ability on other platforms.
8383 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8384#else
8385 return 0;
8386#endif
8387}
8388
[email protected]3a86a712013-07-30 07:16:208389// SystemSupportsHardFailRevocationChecking returns true iff the current
8390// operating system supports revocation checking and can distinguish between
8391// situations where a given certificate lacks any revocation information (eg:
8392// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8393// revocation information cannot be obtained (eg: the CRL was unreachable).
8394// If it does not, then tests which rely on 'hard fail' behaviour should be
8395// skipped.
8396static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488397#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208398 return true;
8399#else
8400 return false;
8401#endif
8402}
8403
[email protected]a13234c2012-03-20 21:45:028404// SystemUsesChromiumEVMetadata returns true iff the current operating system
8405// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8406// several tests are effected because our testing EV certificate won't be
8407// recognised as EV.
8408static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328409#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578410 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8411 return false;
[email protected]e1b2d732014-03-28 16:20:328412#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8413 // On OS X and Android, we use the system to tell us whether a certificate is
8414 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018415 return false;
8416#else
8417 return true;
8418#endif
8419}
8420
[email protected]b6f2de32012-08-17 04:35:088421static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008422#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578423 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8424 return false;
8425#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028426 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8427#elif defined(OS_ANDROID)
8428 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8429 return false;
8430#else
8431 return true;
8432#endif
8433}
8434
davidbend1fb2f12014-11-08 02:51:008435static bool SystemSupportsOCSPStapling() {
davidben71f35ff2015-04-17 20:54:488436#if defined(USE_NSS_CERTS)
davidbend1fb2f12014-11-08 02:51:008437 return true;
8438#elif defined(OS_WIN)
8439 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8440#else
8441 return false;
8442#endif
8443}
8444
[email protected]dffe8242012-03-20 15:14:278445TEST_F(HTTPSOCSPTest, Valid) {
8446 if (!SystemSupportsOCSP()) {
8447 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8448 return;
8449 }
8450
[email protected]ce7d0cbc2013-05-03 18:57:228451 SpawnedTestServer::SSLOptions ssl_options(
8452 SpawnedTestServer::SSLOptions::CERT_AUTO);
8453 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278454
[email protected]924e9f92012-12-16 22:00:538455 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128456 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278457
8458 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8459
[email protected]a13234c2012-03-20 21:45:028460 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8461 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278462
8463 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8464}
8465
8466TEST_F(HTTPSOCSPTest, Revoked) {
8467 if (!SystemSupportsOCSP()) {
8468 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8469 return;
8470 }
8471
[email protected]ce7d0cbc2013-05-03 18:57:228472 SpawnedTestServer::SSLOptions ssl_options(
8473 SpawnedTestServer::SSLOptions::CERT_AUTO);
8474 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278475
8476 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128477 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278478
[email protected]a592c0432012-12-01 18:10:298479#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278480 // Doesn't pass on OS X yet for reasons that need to be investigated.
8481 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8482#endif
8483 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8484 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8485}
8486
8487TEST_F(HTTPSOCSPTest, Invalid) {
8488 if (!SystemSupportsOCSP()) {
8489 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8490 return;
8491 }
8492
[email protected]ce7d0cbc2013-05-03 18:57:228493 SpawnedTestServer::SSLOptions ssl_options(
8494 SpawnedTestServer::SSLOptions::CERT_AUTO);
8495 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278496
[email protected]924e9f92012-12-16 22:00:538497 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128498 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278499
[email protected]a13234c2012-03-20 21:45:028500 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278501 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278502
8503 // Without a positive OCSP response, we shouldn't show the EV status.
8504 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8505 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8506}
[email protected]a13234c2012-03-20 21:45:028507
davidbend1fb2f12014-11-08 02:51:008508TEST_F(HTTPSOCSPTest, ValidStapled) {
8509 if (!SystemSupportsOCSPStapling()) {
8510 LOG(WARNING)
8511 << "Skipping test because system doesn't support OCSP stapling";
8512 return;
8513 }
8514
8515 SpawnedTestServer::SSLOptions ssl_options(
8516 SpawnedTestServer::SSLOptions::CERT_AUTO);
8517 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8518 ssl_options.staple_ocsp_response = true;
8519 ssl_options.ocsp_server_unavailable = true;
8520
8521 CertStatus cert_status;
8522 DoConnection(ssl_options, &cert_status);
8523
8524 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8525
8526 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8527 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8528
8529 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8530}
8531
davidben6c3191b2014-11-21 22:38:048532// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:488533#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:048534#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8535#else
8536#define MAYBE_RevokedStapled RevokedStapled
8537#endif
8538TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008539 if (!SystemSupportsOCSPStapling()) {
8540 LOG(WARNING)
8541 << "Skipping test because system doesn't support OCSP stapling";
8542 return;
8543 }
8544
8545 SpawnedTestServer::SSLOptions ssl_options(
8546 SpawnedTestServer::SSLOptions::CERT_AUTO);
8547 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8548 ssl_options.staple_ocsp_response = true;
8549 ssl_options.ocsp_server_unavailable = true;
8550
8551 CertStatus cert_status;
8552 DoConnection(ssl_options, &cert_status);
8553
8554 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8555 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8556 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8557}
8558
[email protected]3a86a712013-07-30 07:16:208559class HTTPSHardFailTest : public HTTPSOCSPTest {
8560 protected:
dchengb03027d2014-10-21 12:00:208561 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208562 context->set_ssl_config_service(
8563 new TestSSLConfigService(false /* check for EV */,
8564 false /* online revocation checking */,
8565 true /* require rev. checking for local
8566 anchors */));
8567 }
8568};
8569
[email protected]3a86a712013-07-30 07:16:208570TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8571 if (!SystemSupportsOCSP()) {
8572 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8573 return;
8574 }
8575
8576 if (!SystemSupportsHardFailRevocationChecking()) {
8577 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8578 << "revocation checking";
8579 return;
8580 }
8581
8582 SpawnedTestServer::SSLOptions ssl_options(
8583 SpawnedTestServer::SSLOptions::CERT_AUTO);
8584 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8585
8586 CertStatus cert_status;
8587 DoConnection(ssl_options, &cert_status);
8588
8589 EXPECT_EQ(CERT_STATUS_REVOKED,
8590 cert_status & CERT_STATUS_REVOKED);
8591
8592 // Without a positive OCSP response, we shouldn't show the EV status.
8593 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8594}
8595
[email protected]a13234c2012-03-20 21:45:028596class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8597 protected:
dchengb03027d2014-10-21 12:00:208598 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028599 context->set_ssl_config_service(
8600 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208601 false /* online revocation checking */,
8602 false /* require rev. checking for local
8603 anchors */));
[email protected]a13234c2012-03-20 21:45:028604 }
8605};
8606
8607TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8608 if (!SystemSupportsOCSP()) {
8609 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8610 return;
8611 }
8612
[email protected]ce7d0cbc2013-05-03 18:57:228613 SpawnedTestServer::SSLOptions ssl_options(
8614 SpawnedTestServer::SSLOptions::CERT_AUTO);
8615 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028616 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8617
[email protected]924e9f92012-12-16 22:00:538618 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128619 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028620
8621 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8622 cert_status & CERT_STATUS_ALL_ERRORS);
8623
8624 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088625 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8626 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028627}
8628
[email protected]be0fff62013-08-29 23:37:488629TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8630 if (!SystemSupportsOCSP()) {
8631 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8632 return;
8633 }
8634
8635 SpawnedTestServer::SSLOptions ssl_options(
8636 SpawnedTestServer::SSLOptions::CERT_AUTO);
8637 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8638 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8639
8640 CertStatus cert_status;
8641 DoConnection(ssl_options, &cert_status);
8642
8643 // Currently only works for Windows. When using NSS or OS X, it's not
8644 // possible to determine whether the check failed because of actual
8645 // revocation or because there was an OCSP failure.
8646#if defined(OS_WIN)
8647 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8648#else
8649 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8650#endif
8651
8652 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8653 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8654 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8655}
8656
[email protected]a13234c2012-03-20 21:45:028657TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8658 if (!SystemSupportsOCSP()) {
8659 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8660 return;
8661 }
8662
[email protected]ce7d0cbc2013-05-03 18:57:228663 SpawnedTestServer::SSLOptions ssl_options(
8664 SpawnedTestServer::SSLOptions::CERT_AUTO);
8665 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028666 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8667
8668 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128669 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028670
8671 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8672
8673 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8674 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088675 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8676 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028677}
8678
8679TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8680 if (!SystemSupportsOCSP()) {
8681 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8682 return;
8683 }
8684
[email protected]ce7d0cbc2013-05-03 18:57:228685 SpawnedTestServer::SSLOptions ssl_options(
8686 SpawnedTestServer::SSLOptions::CERT_AUTO);
8687 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028688 SSLConfigService::SetCRLSet(
8689 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8690
8691 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128692 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028693
8694 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8695 cert_status & CERT_STATUS_ALL_ERRORS);
8696
8697 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088698 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8699 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028700}
8701
[email protected]51523f52013-07-31 21:57:288702TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8703 if (!SystemSupportsOCSP()) {
8704 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8705 return;
8706 }
8707
8708 SpawnedTestServer::SSLOptions ssl_options(
8709 SpawnedTestServer::SSLOptions::CERT_AUTO);
8710 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8711 SSLConfigService::SetCRLSet(
8712 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8713 false, &kOCSPTestCertSPKI, "")));
8714
8715 CertStatus cert_status;
8716 DoConnection(ssl_options, &cert_status);
8717
8718 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8719 // revocation check for EV.
8720 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8721 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8722 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8723 EXPECT_FALSE(
8724 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8725}
8726
8727TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8728 if (!SystemSupportsOCSP()) {
8729 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8730 return;
8731 }
8732
[email protected]ce7d0cbc2013-05-03 18:57:228733 SpawnedTestServer::SSLOptions ssl_options(
8734 SpawnedTestServer::SSLOptions::CERT_AUTO);
8735 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028736 SSLConfigService::SetCRLSet(
8737 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8738
[email protected]51523f52013-07-31 21:57:288739 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128740 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028741
[email protected]51523f52013-07-31 21:57:288742 // Even with a fresh CRLSet, we should still do online revocation checks when
8743 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8744 // test.
8745 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8746 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028747
[email protected]51523f52013-07-31 21:57:288748 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028749 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288750 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028751}
8752
[email protected]b6f2de32012-08-17 04:35:088753TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8754 // Test that when EV verification is requested, but online revocation
8755 // checking is disabled, and the leaf certificate is not in fact EV, that
8756 // no revocation checking actually happens.
8757 if (!SystemSupportsOCSP()) {
8758 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8759 return;
8760 }
8761
8762 // Unmark the certificate's OID as EV, which should disable revocation
8763 // checking (as per the user preference)
8764 ev_test_policy_.reset();
8765
[email protected]ce7d0cbc2013-05-03 18:57:228766 SpawnedTestServer::SSLOptions ssl_options(
8767 SpawnedTestServer::SSLOptions::CERT_AUTO);
8768 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088769 SSLConfigService::SetCRLSet(
8770 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8771
8772 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128773 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088774
8775 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8776
8777 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8778 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8779}
8780
[email protected]a13234c2012-03-20 21:45:028781class HTTPSCRLSetTest : public HTTPSOCSPTest {
8782 protected:
dchengb03027d2014-10-21 12:00:208783 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028784 context->set_ssl_config_service(
8785 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208786 false /* online revocation checking */,
8787 false /* require rev. checking for local
8788 anchors */));
[email protected]a13234c2012-03-20 21:45:028789 }
8790};
8791
8792TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228793 SpawnedTestServer::SSLOptions ssl_options(
8794 SpawnedTestServer::SSLOptions::CERT_AUTO);
8795 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028796 SSLConfigService::SetCRLSet(
8797 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8798
[email protected]924e9f92012-12-16 22:00:538799 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128800 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028801
8802 // If we're not trying EV verification then, even if the CRLSet has expired,
8803 // we don't fall back to online revocation checks.
8804 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8805 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8806 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8807}
[email protected]51523f52013-07-31 21:57:288808
8809TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308810#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288811 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8812 return;
8813#endif
8814
8815 SpawnedTestServer::SSLOptions ssl_options(
8816 SpawnedTestServer::SSLOptions::CERT_AUTO);
8817 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8818 ssl_options.cert_serial = 10;
8819 SSLConfigService::SetCRLSet(
8820 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8821 false, &kOCSPTestCertSPKI, "\x0a")));
8822
8823 CertStatus cert_status = 0;
8824 DoConnection(ssl_options, &cert_status);
8825
8826 // If the certificate is recorded as revoked in the CRLSet, that should be
8827 // reflected without online revocation checking.
8828 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8829 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8830 EXPECT_FALSE(
8831 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8832}
[email protected]316c1e5e2012-09-12 15:17:448833#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278834
mmenke9f2ec60c2015-06-01 20:59:478835#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
8836// These tests aren't passing on Android. Either the RemoteTestServer isn't
8837// starting up successfully, or it can't access the test files.
8838// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:318839class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118840 public:
[email protected]d9fca99a2012-02-24 16:16:208841 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:478842 : ftp_transaction_factory_(&host_resolver_),
8843 test_server_(SpawnedTestServer::TYPE_FTP,
8844 SpawnedTestServer::kLocalhost,
8845 base::FilePath(kTestFilePath)) {
8846 // Can't use |default_context_|'s HostResolver to set up the
8847 // FTPTransactionFactory because it hasn't been created yet.
8848 default_context_.set_host_resolver(&host_resolver_);
8849 }
8850
8851 // URLRequestTest interface:
8852 void SetUpFactory() override {
8853 // Add FTP support to the default URLRequestContext.
8854 job_factory_impl_->SetProtocolHandler(
8855 "ftp", new FtpProtocolHandler(&ftp_transaction_factory_));
8856 }
8857
8858 std::string GetTestFileContents() {
8859 base::FilePath path;
8860 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
8861 path = path.Append(kTestFilePath);
8862 path = path.AppendASCII(kFtpTestFile);
8863 std::string contents;
8864 EXPECT_TRUE(base::ReadFileToString(path, &contents));
8865 return contents;
[email protected]95409e12010-08-17 20:07:118866 }
8867
[email protected]b89ca032009-08-31 21:41:318868 protected:
mmenke9f2ec60c2015-06-01 20:59:478869 MockHostResolver host_resolver_;
8870 FtpNetworkLayer ftp_transaction_factory_;
8871
[email protected]ce7d0cbc2013-05-03 18:57:228872 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318873};
8874
[email protected]d2a133182012-08-05 16:44:088875// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098876TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088877 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088878
8879 TestDelegate d;
8880 {
davidben151423e2015-03-23 18:48:368881 scoped_ptr<URLRequest> r(
8882 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198883 r->Start();
8884 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088885
[email protected]255620da2013-08-19 13:14:298886 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088887
[email protected]f7022f32014-08-21 16:32:198888 EXPECT_FALSE(r->is_pending());
8889 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8890 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088891 }
8892}
8893
mmenke9f2ec60c2015-06-01 20:59:478894TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118895 ASSERT_TRUE(test_server_.Start());
8896
[email protected]a25e90e2009-09-09 17:05:378897 TestDelegate d;
8898 {
[email protected]f7022f32014-08-21 16:32:198899 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368900 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198901 r->Start();
8902 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378903
[email protected]255620da2013-08-19 13:14:298904 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378905
[email protected]f7022f32014-08-21 16:32:198906 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378907 EXPECT_EQ(1, d.response_started_count());
8908 EXPECT_FALSE(d.received_data_before_response());
8909 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198910 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198911 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198912 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198913 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378914 }
8915}
8916
mmenke9f2ec60c2015-06-01 20:59:478917TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118918 ASSERT_TRUE(test_server_.Start());
8919
[email protected]dd265012009-01-08 20:45:278920 TestDelegate d;
8921 {
[email protected]f7022f32014-08-21 16:32:198922 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:478923 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198924 r->Start();
8925 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278926
[email protected]255620da2013-08-19 13:14:298927 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278928
[email protected]f7022f32014-08-21 16:32:198929 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278930 EXPECT_EQ(1, d.response_started_count());
8931 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:478932 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:198933 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198934 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198935 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198936 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278937 }
8938}
8939
mmenke9f2ec60c2015-06-01 20:59:478940TEST_F(URLRequestTestFTP, FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118941 ASSERT_TRUE(test_server_.Start());
8942
[email protected]dd265012009-01-08 20:45:278943 TestDelegate d;
8944 {
mmenke9f2ec60c2015-06-01 20:59:478945 scoped_ptr<URLRequest> r(
8946 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8947 kFtpTestFile, "chrome", "chrome"),
8948 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198949 r->Start();
8950 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278951
[email protected]255620da2013-08-19 13:14:298952 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278953
[email protected]f7022f32014-08-21 16:32:198954 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:478955 EXPECT_EQ(1, d.response_started_count());
8956 EXPECT_FALSE(d.received_data_before_response());
8957 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]6d81b482011-02-22 19:47:198958 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198959 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198960 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198961 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:258962
8963 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198964 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258965 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278966 }
8967}
8968
mmenke9f2ec60c2015-06-01 20:59:478969TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118970 ASSERT_TRUE(test_server_.Start());
8971
[email protected]dd265012009-01-08 20:45:278972 TestDelegate d;
8973 {
[email protected]f7022f32014-08-21 16:32:198974 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:478975 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:198976 "wrong_password"),
davidben151423e2015-03-23 18:48:368977 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198978 r->Start();
8979 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278980
[email protected]255620da2013-08-19 13:14:298981 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278982
[email protected]f7022f32014-08-21 16:32:198983 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278984 EXPECT_EQ(1, d.response_started_count());
8985 EXPECT_FALSE(d.received_data_before_response());
8986 EXPECT_EQ(d.bytes_received(), 0);
8987 }
8988}
8989
mmenke9f2ec60c2015-06-01 20:59:478990TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:118991 ASSERT_TRUE(test_server_.Start());
8992
[email protected]8b8a197d2009-08-26 15:57:588993 TestDelegate d;
8994 // Set correct login credentials. The delegate will be asked for them when
8995 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588996 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588997 {
[email protected]f7022f32014-08-21 16:32:198998 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:478999 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199000 "wrong_password"),
davidben151423e2015-03-23 18:48:369001 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199002 r->Start();
9003 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589004
[email protected]255620da2013-08-19 13:14:299005 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589006
[email protected]f7022f32014-08-21 16:32:199007 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589008 EXPECT_EQ(1, d.response_started_count());
9009 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479010 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589011 }
9012}
9013
mmenke9f2ec60c2015-06-01 20:59:479014TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:119015 ASSERT_TRUE(test_server_.Start());
9016
[email protected]dd265012009-01-08 20:45:279017 TestDelegate d;
9018 {
mmenke9f2ec60c2015-06-01 20:59:479019 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9020 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9021 "chrome"),
9022 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199023 r->Start();
9024 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279025
[email protected]255620da2013-08-19 13:14:299026 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279027
[email protected]f7022f32014-08-21 16:32:199028 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279029 EXPECT_EQ(1, d.response_started_count());
9030 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479031 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279032 }
9033}
[email protected]8b8a197d2009-08-26 15:57:589034
mmenke9f2ec60c2015-06-01 20:59:479035TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119036 ASSERT_TRUE(test_server_.Start());
9037
[email protected]8b8a197d2009-08-26 15:57:589038 TestDelegate d;
9039 // Set correct login credentials. The delegate will be asked for them when
9040 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589041 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589042 {
mmenke9f2ec60c2015-06-01 20:59:479043 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9044 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9045 "chrome"),
9046 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199047 r->Start();
9048 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589049
[email protected]255620da2013-08-19 13:14:299050 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589051
[email protected]f7022f32014-08-21 16:32:199052 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589053 EXPECT_EQ(1, d.response_started_count());
9054 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479055 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589056 }
9057}
[email protected]60a3df52009-09-22 16:13:249058
mmenke9f2ec60c2015-06-01 20:59:479059TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119060 ASSERT_TRUE(test_server_.Start());
9061
[email protected]60a3df52009-09-22 16:13:249062 scoped_ptr<TestDelegate> d(new TestDelegate);
9063 {
9064 // Pass correct login identity in the URL.
mmenke9f2ec60c2015-06-01 20:59:479065 scoped_ptr<URLRequest> r(
9066 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9067 kFtpTestFile, "chrome", "chrome"),
9068 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199069 r->Start();
9070 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249071
[email protected]255620da2013-08-19 13:14:299072 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249073
[email protected]f7022f32014-08-21 16:32:199074 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249075 EXPECT_EQ(1, d->response_started_count());
9076 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479077 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249078 }
9079
9080 d.reset(new TestDelegate);
9081 {
9082 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199083 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479084 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199085 r->Start();
9086 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249087
[email protected]255620da2013-08-19 13:14:299088 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249089
[email protected]f7022f32014-08-21 16:32:199090 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249091 EXPECT_EQ(1, d->response_started_count());
9092 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479093 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249094 }
9095}
9096
mmenke9f2ec60c2015-06-01 20:59:479097TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119098 ASSERT_TRUE(test_server_.Start());
9099
[email protected]60a3df52009-09-22 16:13:249100 scoped_ptr<TestDelegate> d(new TestDelegate);
9101 // Set correct login credentials. The delegate will be asked for them when
9102 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589103 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249104 {
[email protected]f7022f32014-08-21 16:32:199105 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479106 test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
[email protected]f7022f32014-08-21 16:32:199107 "wrong_password"),
davidben151423e2015-03-23 18:48:369108 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199109 r->Start();
9110 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249111
[email protected]255620da2013-08-19 13:14:299112 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249113
[email protected]f7022f32014-08-21 16:32:199114 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249115 EXPECT_EQ(1, d->response_started_count());
9116 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479117 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249118 }
9119
9120 // Use a new delegate without explicit credentials. The cached ones should be
9121 // used.
9122 d.reset(new TestDelegate);
9123 {
9124 // Don't pass wrong credentials in the URL, they would override valid cached
9125 // ones.
[email protected]f7022f32014-08-21 16:32:199126 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke9f2ec60c2015-06-01 20:59:479127 test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199128 r->Start();
9129 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249130
[email protected]255620da2013-08-19 13:14:299131 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249132
[email protected]f7022f32014-08-21 16:32:199133 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249134 EXPECT_EQ(1, d->response_started_count());
9135 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479136 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:249137 }
9138}
[email protected]316c1e5e2012-09-12 15:17:449139#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519140
ttuttlec0c828492015-05-15 01:25:559141TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9142 TestDelegate d;
9143 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9144 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9145 d.set_quit_on_network_start(true);
9146
9147 EXPECT_FALSE(req->response_info().network_accessed);
9148
9149 req->Start();
9150 base::RunLoop().Run();
9151
9152 EXPECT_EQ(1, d.received_before_network_start_count());
9153 EXPECT_EQ(0, d.response_started_count());
9154 EXPECT_FALSE(req->response_info().network_accessed);
9155
9156 req->ResumeNetworkStart();
9157 base::RunLoop().Run();
9158}
9159
9160TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9161 TestDelegate d;
9162 scoped_ptr<URLRequest> req(
9163 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9164
9165 EXPECT_FALSE(req->response_info().network_accessed);
9166
9167 req->Start();
9168 base::RunLoop().Run();
9169
9170 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9171 EXPECT_FALSE(req->response_info().network_accessed);
9172}
9173
9174TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9175 MockHostResolver host_resolver;
9176 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9177 TestURLRequestContext context(true);
9178 context.set_network_delegate(&network_delegate);
9179 context.set_host_resolver(&host_resolver);
9180 host_resolver.rules()->AddSimulatedFailure("*");
9181 context.Init();
9182
9183 TestDelegate d;
9184 scoped_ptr<URLRequest> req(context.CreateRequest(
9185 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9186
9187 EXPECT_FALSE(req->response_info().network_accessed);
9188
9189 req->Start();
9190 base::RunLoop().Run();
9191 EXPECT_TRUE(req->response_info().network_accessed);
9192}
9193
[email protected]7461a402011-03-24 23:19:519194} // namespace net