blob: a47ca99fbcb86738cc5134ab01ea3c7f1d191c7a [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"
thestigd8df0332014-09-04 06:33:2919#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0720#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2821#include "base/format_macros.h"
mmenke19378d22014-09-09 04:12:5922#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4723#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2224#include "base/message_loop/message_loop.h"
[email protected]255620da2013-08-19 13:14:2925#include "base/message_loop/message_loop_proxy.h"
initial.commit586acc5fe2008-07-26 22:42:5226#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2927#include "base/run_loop.h"
[email protected]4dc3ad4f2013-06-11 07:15:5028#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5529#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2230#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2231#include "base/strings/string_util.h"
32#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0533#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0034#include "base/test/histogram_tester.h"
mmenkecbc2b712014-10-09 20:29:0735#include "net/base/chunked_upload_data_stream.h"
36#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5237#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2538#include "net/base/load_timing_info.h"
39#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0640#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5241#include "net/base/net_module.h"
42#include "net/base/net_util.h"
tbansalea2fb8c2015-05-22 22:23:0043#include "net/base/network_quality.h"
44#include "net/base/network_quality_estimator.h"
[email protected]2ca01e52013-10-31 22:05:1945#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4046#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2847#include "net/base/upload_bytes_element_reader.h"
48#include "net/base/upload_data_stream.h"
49#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1150#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2451#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1152#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4953#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0654#include "net/cookies/cookie_monster.h"
55#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5256#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5357#include "net/dns/mock_host_resolver.h"
[email protected]ba2f3342009-07-30 18:08:4258#include "net/ftp/ftp_network_layer.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
95#if !defined(DISABLE_FTP_SUPPORT)
96#include "net/url_request/ftp_protocol_handler.h"
97#endif
98
[email protected]dffe8242012-03-20 15:14:2799#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48100#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56101#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27102#include "base/win/windows_version.h"
103#endif
104
[email protected]ad65a3e2013-12-25 18:18:01105using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33106using base::Time;
halton.huoe4e45742014-12-08 07:55:46107using std::string;
[email protected]e1acf6f2008-10-27 20:43:33108
[email protected]7461a402011-03-24 23:19:51109namespace net {
110
initial.commit586acc5fe2008-07-26 22:42:52111namespace {
112
[email protected]42cba2fb2013-03-29 19:58:57113const base::string16 kChrome(ASCIIToUTF16("chrome"));
114const base::string16 kSecret(ASCIIToUTF16("secret"));
115const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44116
[email protected]2bba3252013-04-08 19:50:59117// Tests load timing information in the case a fresh connection was used, with
118// no proxy.
[email protected]cba24642014-08-15 20:49:59119void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25120 int connect_timing_flags) {
121 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59122 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25123
124 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
125 EXPECT_FALSE(load_timing_info.request_start.is_null());
126
127 EXPECT_LE(load_timing_info.request_start,
128 load_timing_info.connect_timing.connect_start);
129 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
130 connect_timing_flags);
131 EXPECT_LE(load_timing_info.connect_timing.connect_end,
132 load_timing_info.send_start);
133 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
134 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
135
[email protected]58e32bb2013-01-21 18:23:25136 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
137 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
138}
139
[email protected]2bba3252013-04-08 19:50:59140// Same as above, but with proxy times.
141void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59142 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59143 int connect_timing_flags) {
144 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59145 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59146
147 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
148 EXPECT_FALSE(load_timing_info.request_start.is_null());
149
150 EXPECT_LE(load_timing_info.request_start,
151 load_timing_info.proxy_resolve_start);
152 EXPECT_LE(load_timing_info.proxy_resolve_start,
153 load_timing_info.proxy_resolve_end);
154 EXPECT_LE(load_timing_info.proxy_resolve_end,
155 load_timing_info.connect_timing.connect_start);
156 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
157 connect_timing_flags);
158 EXPECT_LE(load_timing_info.connect_timing.connect_end,
159 load_timing_info.send_start);
160 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
161 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
162}
163
164// Same as above, but with a reused socket and proxy times.
165void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59166 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59167 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59168 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59169
170 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
171 EXPECT_FALSE(load_timing_info.request_start.is_null());
172
173 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
174
175 EXPECT_LE(load_timing_info.request_start,
176 load_timing_info.proxy_resolve_start);
177 EXPECT_LE(load_timing_info.proxy_resolve_start,
178 load_timing_info.proxy_resolve_end);
179 EXPECT_LE(load_timing_info.proxy_resolve_end,
180 load_timing_info.send_start);
181 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
182 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
183}
184
xunjielia6888202015-04-14 21:34:25185#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25186// Tests load timing information in the case of a cache hit, when no cache
187// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17188base::StringPiece TestNetResourceProvider(int key) {
189 return "header";
190}
191
192void FillBuffer(char* buffer, size_t len) {
193 static bool called = false;
194 if (!called) {
195 called = true;
196 int seed = static_cast<int>(Time::Now().ToInternalValue());
197 srand(seed);
198 }
199
200 for (size_t i = 0; i < len; i++) {
201 buffer[i] = static_cast<char>(rand());
202 if (!buffer[i])
203 buffer[i] = 'g';
204 }
205}
xunjielia6888202015-04-14 21:34:25206#endif
[email protected]e3a85452013-11-14 01:46:17207
208#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25209void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59210 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25211 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59212 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25213
214 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
215 EXPECT_FALSE(load_timing_info.request_start.is_null());
216
217 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
218 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
219 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
220 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
221
222 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
223 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
224}
225
xunjielia6888202015-04-14 21:34:25226#if !defined(DISABLE_FTP_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25227// Tests load timing in the case that there is no HTTP response. This can be
228// used to test in the case of errors or non-HTTP requests.
229void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59230 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25231 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59232 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25233
234 // Only the request times should be non-null.
235 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
236 EXPECT_FALSE(load_timing_info.request_start.is_null());
237
238 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
239
240 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
241 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
242 EXPECT_TRUE(load_timing_info.send_start.is_null());
243 EXPECT_TRUE(load_timing_info.send_end.is_null());
244 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
245}
xunjielia6888202015-04-14 21:34:25246#endif
[email protected]58e32bb2013-01-21 18:23:25247
[email protected]71c64f62008-11-15 04:36:51248// Do a case-insensitive search through |haystack| for |needle|.
249bool ContainsString(const std::string& haystack, const char* needle) {
250 std::string::const_iterator it =
251 std::search(haystack.begin(),
252 haystack.end(),
253 needle,
254 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35255 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51256 return it != haystack.end();
257}
258
mmenkecbc2b712014-10-09 20:29:07259scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28260 scoped_ptr<UploadElementReader> reader(
261 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07262 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23263}
264
[email protected]96adadb2010-08-28 01:16:17265// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51266void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17267 // -1 means unknown. 0 means no encryption.
268 EXPECT_GT(ssl_info.security_bits, 0);
269
270 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29271 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17272 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29273 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17274}
275
[email protected]79e1fd62013-06-20 06:50:04276void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
277 const GURL& host_url) {
278 std::string sent_value;
279
280 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
281 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
282
283 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
284 EXPECT_EQ("keep-alive", sent_value);
285}
286
[email protected]ede03212012-09-07 12:52:26287bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27288 size_t size = a.size();
289
290 if (size != b.size())
291 return false;
292
293 for (size_t i = 0; i < size; ++i) {
294 if (!a[i].Equals(b[i]))
295 return false;
296 }
297
298 return true;
299}
[email protected]e3a85452013-11-14 01:46:17300#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27301
[email protected]dc5a5cf2012-09-26 02:49:30302// A network delegate that allows the user to choose a subset of request stages
303// to block in. When blocking, the delegate can do one of the following:
304// * synchronously return a pre-specified error code, or
305// * asynchronously return that value via an automatically called callback,
306// or
307// * block and wait for the user to do a callback.
308// Additionally, the user may also specify a redirect URL -- then each request
309// with the current URL different from the redirect target will be redirected
310// to that target, in the on-before-URL-request stage, independent of whether
311// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12312class BlockingNetworkDelegate : public TestNetworkDelegate {
313 public:
[email protected]dc5a5cf2012-09-26 02:49:30314 // Stages in which the delegate can block.
315 enum Stage {
[email protected]9045b8822012-01-13 20:35:35316 NOT_BLOCKED = 0,
317 ON_BEFORE_URL_REQUEST = 1 << 0,
318 ON_BEFORE_SEND_HEADERS = 1 << 1,
319 ON_HEADERS_RECEIVED = 1 << 2,
320 ON_AUTH_REQUIRED = 1 << 3
321 };
322
[email protected]dc5a5cf2012-09-26 02:49:30323 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59324 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30325 enum BlockMode {
326 SYNCHRONOUS, // No callback, returns specified return values.
327 AUTO_CALLBACK, // |this| posts a task to run the callback using the
328 // specified return codes.
329 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
330 // |auth_retval_| are ignored. In every blocking stage the
331 // message loop is quit.
332 };
333
334 // Creates a delegate which does not block at all.
335 explicit BlockingNetworkDelegate(BlockMode block_mode);
336
337 // For users to trigger a callback returning |response|.
338 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
339 // Only call if |block_mode_| == USER_CALLBACK.
340 void DoCallback(int response);
341 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
342
343 // Setters.
344 void set_retval(int retval) {
345 ASSERT_NE(USER_CALLBACK, block_mode_);
346 ASSERT_NE(ERR_IO_PENDING, retval);
347 ASSERT_NE(OK, retval);
348 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35349 }
350
[email protected]dc5a5cf2012-09-26 02:49:30351 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
352 // |auth_credentials_| will be passed with the response.
353 void set_auth_retval(AuthRequiredResponse auth_retval) {
354 ASSERT_NE(USER_CALLBACK, block_mode_);
355 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
356 auth_retval_ = auth_retval;
357 }
358 void set_auth_credentials(const AuthCredentials& auth_credentials) {
359 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35360 }
361
[email protected]dc5a5cf2012-09-26 02:49:30362 void set_redirect_url(const GURL& url) {
363 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35364 }
365
[email protected]dc5a5cf2012-09-26 02:49:30366 void set_block_on(int block_on) {
367 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35368 }
369
[email protected]dc5a5cf2012-09-26 02:49:30370 // Allows the user to check in which state did we block.
371 Stage stage_blocked_for_callback() const {
372 EXPECT_EQ(USER_CALLBACK, block_mode_);
373 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35374 }
375
376 private:
[email protected]dc5a5cf2012-09-26 02:49:30377 void RunCallback(int response, const CompletionCallback& callback);
378 void RunAuthCallback(AuthRequiredResponse response,
379 const AuthCallback& callback);
380
[email protected]9045b8822012-01-13 20:35:35381 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20382 int OnBeforeURLRequest(URLRequest* request,
383 const CompletionCallback& callback,
384 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35385
dchengb03027d2014-10-21 12:00:20386 int OnBeforeSendHeaders(URLRequest* request,
387 const CompletionCallback& callback,
388 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35389
dchengb03027d2014-10-21 12:00:20390 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35391 URLRequest* request,
392 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32393 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16394 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13395 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35396
dchengb03027d2014-10-21 12:00:20397 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35398 URLRequest* request,
399 const AuthChallengeInfo& auth_info,
400 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13401 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35402
[email protected]dc5a5cf2012-09-26 02:49:30403 // Resets the callbacks and |stage_blocked_for_callback_|.
404 void Reset();
[email protected]9045b8822012-01-13 20:35:35405
[email protected]dc5a5cf2012-09-26 02:49:30406 // Checks whether we should block in |stage|. If yes, returns an error code
407 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
408 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
409
410 // Configuration parameters, can be adjusted by public methods:
411 const BlockMode block_mode_;
412
413 // Values returned on blocking stages when mode is SYNCHRONOUS or
414 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
415 int retval_; // To be returned in non-auth stages.
416 AuthRequiredResponse auth_retval_;
417
[email protected]5f714132014-03-26 10:41:16418 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30419 int block_on_; // Bit mask: in which stages to block.
420
421 // |auth_credentials_| will be copied to |*target_auth_credential_| on
422 // callback.
423 AuthCredentials auth_credentials_;
424 AuthCredentials* target_auth_credentials_;
425
426 // Internal variables, not set by not the user:
427 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
428 // USER_CALLBACK).
429 Stage stage_blocked_for_callback_;
430
431 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35432 CompletionCallback callback_;
433 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30434
435 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
436
437 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35438};
439
[email protected]dc5a5cf2012-09-26 02:49:30440BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
441 : block_mode_(block_mode),
442 retval_(OK),
443 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
444 block_on_(0),
445 target_auth_credentials_(NULL),
446 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32447 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30448}
449
450void BlockingNetworkDelegate::DoCallback(int response) {
451 ASSERT_EQ(USER_CALLBACK, block_mode_);
452 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
453 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
454 CompletionCallback callback = callback_;
455 Reset();
456 RunCallback(response, callback);
457}
458
459void BlockingNetworkDelegate::DoAuthCallback(
460 NetworkDelegate::AuthRequiredResponse response) {
461 ASSERT_EQ(USER_CALLBACK, block_mode_);
462 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
463 AuthCallback auth_callback = auth_callback_;
464 Reset();
465 RunAuthCallback(response, auth_callback);
466}
467
468void BlockingNetworkDelegate::RunCallback(int response,
469 const CompletionCallback& callback) {
470 callback.Run(response);
471}
472
473void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
474 const AuthCallback& callback) {
475 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
476 ASSERT_TRUE(target_auth_credentials_ != NULL);
477 *target_auth_credentials_ = auth_credentials_;
478 }
479 callback.Run(response);
480}
481
482int BlockingNetworkDelegate::OnBeforeURLRequest(
483 URLRequest* request,
484 const CompletionCallback& callback,
485 GURL* new_url) {
486 if (redirect_url_ == request->url())
487 return OK; // We've already seen this request and redirected elsewhere.
488
489 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
490
491 if (!redirect_url_.is_empty())
492 *new_url = redirect_url_;
493
494 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
495}
496
497int BlockingNetworkDelegate::OnBeforeSendHeaders(
498 URLRequest* request,
499 const CompletionCallback& callback,
500 HttpRequestHeaders* headers) {
501 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
502
503 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
504}
505
506int BlockingNetworkDelegate::OnHeadersReceived(
507 URLRequest* request,
508 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32509 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16510 scoped_refptr<HttpResponseHeaders>* override_response_headers,
511 GURL* allowed_unsafe_redirect_url) {
512 TestNetworkDelegate::OnHeadersReceived(request,
513 callback,
514 original_response_headers,
515 override_response_headers,
516 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30517
518 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
519}
520
521NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
522 URLRequest* request,
523 const AuthChallengeInfo& auth_info,
524 const AuthCallback& callback,
525 AuthCredentials* credentials) {
526 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
527 credentials);
528 // Check that the user has provided callback for the previous blocked stage.
529 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
530
531 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
532 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
533 }
534
535 target_auth_credentials_ = credentials;
536
537 switch (block_mode_) {
538 case SYNCHRONOUS:
539 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
540 *target_auth_credentials_ = auth_credentials_;
541 return auth_retval_;
542
543 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34544 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30545 FROM_HERE,
546 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
547 weak_factory_.GetWeakPtr(), auth_retval_, callback));
548 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
549
550 case USER_CALLBACK:
551 auth_callback_ = callback;
552 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34553 base::MessageLoop::current()->PostTask(FROM_HERE,
554 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30555 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
556 }
557 NOTREACHED();
558 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
559}
560
561void BlockingNetworkDelegate::Reset() {
562 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
563 stage_blocked_for_callback_ = NOT_BLOCKED;
564 callback_.Reset();
565 auth_callback_.Reset();
566}
567
568int BlockingNetworkDelegate::MaybeBlockStage(
569 BlockingNetworkDelegate::Stage stage,
570 const CompletionCallback& callback) {
571 // Check that the user has provided callback for the previous blocked stage.
572 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
573
574 if ((block_on_ & stage) == 0) {
575 return OK;
576 }
577
578 switch (block_mode_) {
579 case SYNCHRONOUS:
580 EXPECT_NE(OK, retval_);
581 return retval_;
582
583 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34584 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30585 FROM_HERE,
586 base::Bind(&BlockingNetworkDelegate::RunCallback,
587 weak_factory_.GetWeakPtr(), retval_, callback));
588 return ERR_IO_PENDING;
589
590 case USER_CALLBACK:
591 callback_ = callback;
592 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34593 base::MessageLoop::current()->PostTask(FROM_HERE,
594 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30595 return ERR_IO_PENDING;
596 }
597 NOTREACHED();
598 return 0;
599}
600
[email protected]d5a4dd62012-05-23 01:41:04601class TestURLRequestContextWithProxy : public TestURLRequestContext {
602 public:
603 // Does not own |delegate|.
604 TestURLRequestContextWithProxy(const std::string& proxy,
605 NetworkDelegate* delegate)
606 : TestURLRequestContext(true) {
607 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
608 set_network_delegate(delegate);
609 Init();
610 }
dchengb03027d2014-10-21 12:00:20611 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04612};
613
614} // namespace
615
[email protected]a592c0432012-12-01 18:10:29616// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48617class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00618 public:
[email protected]ef2bf422012-05-11 03:27:09619 URLRequestTest() : default_context_(true) {
620 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25621 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50622 job_factory_impl_ = new URLRequestJobFactoryImpl();
623 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50624 }
bengr1bf8e942014-11-07 01:36:50625
dcheng67be2b1f2014-10-27 21:47:29626 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18627 // URLRequestJobs may post clean-up tasks on destruction.
628 base::RunLoop().RunUntilIdle();
629 }
[email protected]87a09a92011-07-14 15:50:50630
dcheng2339883c2014-12-23 00:23:05631 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50632 SetUpFactory();
633 default_context_.set_job_factory(job_factory_.get());
634 default_context_.Init();
635 PlatformTest::SetUp();
636 }
637
638 virtual void SetUpFactory() {
639 job_factory_impl_->SetProtocolHandler("data", new DataProtocolHandler);
640#if !defined(DISABLE_FILE_SUPPORT)
641 job_factory_impl_->SetProtocolHandler(
642 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
643#endif
644 }
645
646 TestNetworkDelegate* default_network_delegate() {
647 return &default_network_delegate_;
648 }
649
650 const TestURLRequestContext& default_context() const {
651 return default_context_;
652 }
653
654
[email protected]3c5ca8c2011-09-29 01:14:51655 // Adds the TestJobInterceptor to the default context.
656 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23657 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
bengr1bf8e942014-11-07 01:36:50658 job_factory_impl_->SetProtocolHandler("http", NULL);
659 job_factory_impl_->SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23660 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51661 }
662
[email protected]87a09a92011-07-14 15:50:50663 protected:
vishal.b62985ca92015-04-17 08:45:51664 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24665 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50666 URLRequestJobFactoryImpl* job_factory_impl_;
667 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09668 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48669};
670
[email protected]316c1e5e2012-09-12 15:17:44671TEST_F(URLRequestTest, AboutBlankTest) {
672 TestDelegate d;
673 {
[email protected]f7022f32014-08-21 16:32:19674 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36675 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44676
[email protected]f7022f32014-08-21 16:32:19677 r->Start();
678 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44679
[email protected]255620da2013-08-19 13:14:29680 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44681
[email protected]f7022f32014-08-21 16:32:19682 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44683 EXPECT_FALSE(d.received_data_before_response());
684 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19685 EXPECT_EQ("", r->GetSocketAddress().host());
686 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04687
688 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19689 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44690 }
691}
692
693TEST_F(URLRequestTest, DataURLImageTest) {
694 TestDelegate d;
695 {
696 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19697 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19698 GURL(
davidben151423e2015-03-23 18:48:36699 "data:image/png;base64,"
700 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
701 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
702 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
703 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
704 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
705 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
706 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
707 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
708 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
709 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
710 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
711 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
712 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
713 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
714 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
715 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
716 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
717 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
718 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
719 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44720
[email protected]f7022f32014-08-21 16:32:19721 r->Start();
722 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44723
[email protected]255620da2013-08-19 13:14:29724 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44725
[email protected]f7022f32014-08-21 16:32:19726 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44727 EXPECT_FALSE(d.received_data_before_response());
728 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19729 EXPECT_EQ("", r->GetSocketAddress().host());
730 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04731
732 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19733 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44734 }
735}
736
[email protected]5ecf7cb282014-05-11 01:49:55737#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44738TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15739 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44740 PathService::Get(base::FILE_EXE, &app_path);
741 GURL app_url = FilePathToFileURL(app_path);
742
743 TestDelegate d;
744 {
davidben151423e2015-03-23 18:48:36745 scoped_ptr<URLRequest> r(
746 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44747
[email protected]f7022f32014-08-21 16:32:19748 r->Start();
749 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44750
[email protected]255620da2013-08-19 13:14:29751 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44752
753 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49754 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44755
[email protected]f7022f32014-08-21 16:32:19756 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44757 EXPECT_EQ(1, d.response_started_count());
758 EXPECT_FALSE(d.received_data_before_response());
759 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19760 EXPECT_EQ("", r->GetSocketAddress().host());
761 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04762
763 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19764 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44765 }
766}
767
[email protected]ba40bb762012-12-17 07:11:04768TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15769 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04770 PathService::Get(base::FILE_EXE, &app_path);
771 GURL app_url = FilePathToFileURL(app_path);
772
773 TestDelegate d;
774 {
davidben151423e2015-03-23 18:48:36775 scoped_ptr<URLRequest> r(
776 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04777
[email protected]f7022f32014-08-21 16:32:19778 r->Start();
779 EXPECT_TRUE(r->is_pending());
780 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04781 }
[email protected]79e1fd62013-06-20 06:50:04782 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04783 // destroyed.
[email protected]255620da2013-08-19 13:14:29784 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04785}
786
[email protected]316c1e5e2012-09-12 15:17:44787TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
788 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17789 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44790 FillBuffer(buffer.get(), buffer_size);
791
[email protected]6cdfd7f2013-02-08 20:40:15792 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52793 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44794 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30795 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44796
797 int64 file_size;
[email protected]56285702013-12-04 18:22:49798 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44799
800 const size_t first_byte_position = 500;
801 const size_t last_byte_position = buffer_size - first_byte_position;
802 const size_t content_length = last_byte_position - first_byte_position + 1;
803 std::string partial_buffer_string(buffer.get() + first_byte_position,
804 buffer.get() + last_byte_position + 1);
805
806 TestDelegate d;
807 {
davidben151423e2015-03-23 18:48:36808 scoped_ptr<URLRequest> r(
809 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44810
811 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38812 headers.SetHeader(
813 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59814 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38815 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19816 r->SetExtraRequestHeaders(headers);
817 r->Start();
818 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44819
[email protected]255620da2013-08-19 13:14:29820 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19821 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44822 EXPECT_EQ(1, d.response_started_count());
823 EXPECT_FALSE(d.received_data_before_response());
824 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
825 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
826 EXPECT_TRUE(partial_buffer_string == d.data_received());
827 }
828
[email protected]dd3aa792013-07-16 19:10:23829 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44830}
831
832TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
833 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17834 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44835 FillBuffer(buffer.get(), buffer_size);
836
[email protected]6cdfd7f2013-02-08 20:40:15837 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52838 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44839 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30840 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44841
842 int64 file_size;
[email protected]56285702013-12-04 18:22:49843 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44844
845 const size_t first_byte_position = 500;
846 const size_t last_byte_position = buffer_size - 1;
847 const size_t content_length = last_byte_position - first_byte_position + 1;
848 std::string partial_buffer_string(buffer.get() + first_byte_position,
849 buffer.get() + last_byte_position + 1);
850
851 TestDelegate d;
852 {
davidben151423e2015-03-23 18:48:36853 scoped_ptr<URLRequest> r(
854 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44855
856 HttpRequestHeaders headers;
857 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59858 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38859 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19860 r->SetExtraRequestHeaders(headers);
861 r->Start();
862 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44863
[email protected]255620da2013-08-19 13:14:29864 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19865 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44866 EXPECT_EQ(1, d.response_started_count());
867 EXPECT_FALSE(d.received_data_before_response());
868 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
869 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
870 EXPECT_TRUE(partial_buffer_string == d.data_received());
871 }
872
[email protected]dd3aa792013-07-16 19:10:23873 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44874}
875
876TEST_F(URLRequestTest, FileTestMultipleRanges) {
877 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17878 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44879 FillBuffer(buffer.get(), buffer_size);
880
[email protected]6cdfd7f2013-02-08 20:40:15881 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52882 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44883 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30884 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44885
886 int64 file_size;
[email protected]56285702013-12-04 18:22:49887 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44888
889 TestDelegate d;
890 {
davidben151423e2015-03-23 18:48:36891 scoped_ptr<URLRequest> r(
892 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44893
894 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38895 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19896 r->SetExtraRequestHeaders(headers);
897 r->Start();
898 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44899
[email protected]255620da2013-08-19 13:14:29900 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44901 EXPECT_TRUE(d.request_failed());
902 }
903
[email protected]dd3aa792013-07-16 19:10:23904 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44905}
906
[email protected]3ca8b362013-11-11 22:18:07907TEST_F(URLRequestTest, AllowFileURLs) {
908 base::ScopedTempDir temp_dir;
909 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
910 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52911 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07912 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30913 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59914 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07915
916 {
917 TestDelegate d;
918 TestNetworkDelegate network_delegate;
919 network_delegate.set_can_access_files(true);
920 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36921 scoped_ptr<URLRequest> r(
922 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19923 r->Start();
[email protected]3ca8b362013-11-11 22:18:07924 base::RunLoop().Run();
925 EXPECT_FALSE(d.request_failed());
926 EXPECT_EQ(test_data, d.data_received());
927 }
928
929 {
930 TestDelegate d;
931 TestNetworkDelegate network_delegate;
932 network_delegate.set_can_access_files(false);
933 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36934 scoped_ptr<URLRequest> r(
935 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19936 r->Start();
[email protected]3ca8b362013-11-11 22:18:07937 base::RunLoop().Run();
938 EXPECT_TRUE(d.request_failed());
939 EXPECT_EQ("", d.data_received());
940 }
941}
942
[email protected]316c1e5e2012-09-12 15:17:44943
944TEST_F(URLRequestTest, FileDirCancelTest) {
945 // Put in mock resource provider.
946 NetModule::SetResourceProvider(TestNetResourceProvider);
947
948 TestDelegate d;
949 {
[email protected]6cdfd7f2013-02-08 20:40:15950 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44951 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
952 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
953 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
954
[email protected]f7022f32014-08-21 16:32:19955 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36956 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19957 req->Start();
958 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44959
960 d.set_cancel_in_received_data_pending(true);
961
[email protected]255620da2013-08-19 13:14:29962 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44963 }
964
965 // Take out mock resource provider.
966 NetModule::SetResourceProvider(NULL);
967}
968
[email protected]5f9581402013-10-30 13:08:32969TEST_F(URLRequestTest, FileDirOutputSanity) {
970 // Verify the general sanity of the the output of the file:
971 // directory lister by checking for the output of a known existing
972 // file.
973 const char sentinel_name[] = "filedir-sentinel";
974
975 base::FilePath path;
976 PathService::Get(base::DIR_SOURCE_ROOT, &path);
977 path = path.Append(FILE_PATH_LITERAL("net"));
978 path = path.Append(FILE_PATH_LITERAL("data"));
979 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
980
981 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:19982 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36983 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19984 req->Start();
[email protected]5f9581402013-10-30 13:08:32985 base::RunLoop().Run();
986
987 // Generate entry for the sentinel file.
988 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:58989 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:49990 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:32991 EXPECT_GT(info.size, 0);
992 std::string sentinel_output = GetDirectoryListingEntry(
993 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
994 std::string(sentinel_name),
995 false /* is_dir */,
996 info.size,
997 info.last_modified);
998
999 ASSERT_LT(0, d.bytes_received());
1000 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191001 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321002 // Check for the entry generated for the "sentinel" file.
1003 const std::string& data = d.data_received();
1004 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1005}
1006
[email protected]316c1e5e2012-09-12 15:17:441007TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1008 // There is an implicit redirect when loading a file path that matches a
1009 // directory and does not end with a slash. Ensure that following such
1010 // redirects does not crash. See http://crbug.com/18686.
1011
[email protected]6cdfd7f2013-02-08 20:40:151012 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441013 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1014 path = path.Append(FILE_PATH_LITERAL("net"));
1015 path = path.Append(FILE_PATH_LITERAL("data"));
1016 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1017
1018 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191019 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361020 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191021 req->Start();
[email protected]255620da2013-08-19 13:14:291022 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441023
1024 ASSERT_EQ(1, d.received_redirect_count());
1025 ASSERT_LT(0, d.bytes_received());
1026 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191027 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441028}
1029
1030#if defined(OS_WIN)
1031// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1032TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1033 TestDelegate d;
davidben151423e2015-03-23 18:48:361034 scoped_ptr<URLRequest> req(
1035 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191036 req->Start();
[email protected]255620da2013-08-19 13:14:291037 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441038
1039 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191040 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441041}
[email protected]5ecf7cb282014-05-11 01:49:551042#endif // defined(OS_WIN)
1043
1044#endif // !defined(DISABLE_FILE_SUPPORT)
1045
1046TEST_F(URLRequestTest, InvalidUrlTest) {
1047 TestDelegate d;
1048 {
[email protected]f7022f32014-08-21 16:32:191049 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361050 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551051
[email protected]f7022f32014-08-21 16:32:191052 r->Start();
1053 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551054
1055 base::RunLoop().Run();
1056 EXPECT_TRUE(d.request_failed());
1057 }
1058}
1059
jochen0e3b3a62014-09-16 18:31:231060TEST_F(URLRequestTest, InvalidReferrerTest) {
1061 TestURLRequestContext context;
1062 TestNetworkDelegate network_delegate;
1063 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1064 context.set_network_delegate(&network_delegate);
1065 TestDelegate d;
davidben151423e2015-03-23 18:48:361066 scoped_ptr<URLRequest> req(
1067 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231068 req->SetReferrer("https://somewhere.com/");
1069
1070 req->Start();
1071 base::RunLoop().Run();
1072 EXPECT_TRUE(d.request_failed());
1073}
1074
[email protected]5ecf7cb282014-05-11 01:49:551075#if defined(OS_WIN)
1076TEST_F(URLRequestTest, ResolveShortcutTest) {
1077 base::FilePath app_path;
1078 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1079 app_path = app_path.AppendASCII("net");
1080 app_path = app_path.AppendASCII("data");
1081 app_path = app_path.AppendASCII("url_request_unittest");
1082 app_path = app_path.AppendASCII("with-headers.html");
1083
1084 std::wstring lnk_path = app_path.value() + L".lnk";
1085
1086 base::win::ScopedCOMInitializer com_initializer;
1087
1088 // Temporarily create a shortcut for test
1089 {
1090 base::win::ScopedComPtr<IShellLink> shell;
1091 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1092 CLSCTX_INPROC_SERVER)));
1093 base::win::ScopedComPtr<IPersistFile> persist;
1094 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1095 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1096 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1097 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1098 }
1099
1100 TestDelegate d;
1101 {
[email protected]f7022f32014-08-21 16:32:191102 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361103 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551104
[email protected]f7022f32014-08-21 16:32:191105 r->Start();
1106 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551107
1108 base::RunLoop().Run();
1109
1110 WIN32_FILE_ATTRIBUTE_DATA data;
1111 GetFileAttributesEx(app_path.value().c_str(),
1112 GetFileExInfoStandard, &data);
1113 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1114 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1115 FILE_ATTRIBUTE_NORMAL, NULL);
1116 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1117 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1118 DWORD read_size;
1119 BOOL result;
1120 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1121 &read_size, NULL);
1122 std::string content(buffer.get(), read_size);
1123 CloseHandle(file);
1124
[email protected]f7022f32014-08-21 16:32:191125 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551126 EXPECT_EQ(1, d.received_redirect_count());
1127 EXPECT_EQ(content, d.data_received());
1128 }
1129
1130 // Clean the shortcut
1131 DeleteFile(lnk_path.c_str());
1132}
1133#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441134
1135// Custom URLRequestJobs for use with interceptor tests
1136class RestartTestJob : public URLRequestTestJob {
1137 public:
1138 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1139 : URLRequestTestJob(request, network_delegate, true) {}
1140 protected:
dchengb03027d2014-10-21 12:00:201141 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441142 private:
dchengb03027d2014-10-21 12:00:201143 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441144};
1145
1146class CancelTestJob : public URLRequestTestJob {
1147 public:
1148 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1149 : URLRequestTestJob(request, network_delegate, true) {}
1150 protected:
dchengb03027d2014-10-21 12:00:201151 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441152 private:
dchengb03027d2014-10-21 12:00:201153 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441154};
1155
1156class CancelThenRestartTestJob : public URLRequestTestJob {
1157 public:
1158 explicit CancelThenRestartTestJob(URLRequest* request,
1159 NetworkDelegate* network_delegate)
1160 : URLRequestTestJob(request, network_delegate, true) {
1161 }
1162 protected:
dchengb03027d2014-10-21 12:00:201163 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441164 request_->Cancel();
1165 this->NotifyRestartRequired();
1166 }
1167 private:
dchengb03027d2014-10-21 12:00:201168 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441169};
1170
bengr1bf8e942014-11-07 01:36:501171// An Interceptor for use with interceptor tests.
1172class MockURLRequestInterceptor : public URLRequestInterceptor {
1173 public:
1174 // Static getters for canned response header and data strings.
1175 static std::string ok_data() {
1176 return URLRequestTestJob::test_data_1();
1177 }
1178
1179 static std::string ok_headers() {
1180 return URLRequestTestJob::test_headers();
1181 }
1182
1183 static std::string redirect_data() {
1184 return std::string();
1185 }
1186
1187 static std::string redirect_headers() {
1188 return URLRequestTestJob::test_redirect_headers();
1189 }
1190
1191 static std::string error_data() {
1192 return std::string("ohhh nooooo mr. bill!");
1193 }
1194
1195 static std::string error_headers() {
1196 return URLRequestTestJob::test_error_headers();
1197 }
1198
1199 MockURLRequestInterceptor()
1200 : intercept_main_request_(false), restart_main_request_(false),
1201 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1202 simulate_main_network_error_(false),
1203 intercept_redirect_(false), cancel_redirect_request_(false),
1204 intercept_final_response_(false), cancel_final_request_(false),
1205 use_url_request_http_job_(false),
1206 did_intercept_main_(false), did_restart_main_(false),
1207 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1208 did_simulate_error_main_(false),
1209 did_intercept_redirect_(false), did_cancel_redirect_(false),
1210 did_intercept_final_(false), did_cancel_final_(false) {
1211 }
1212
1213 ~MockURLRequestInterceptor() override {
1214 }
1215
1216 // URLRequestInterceptor implementation:
1217 URLRequestJob* MaybeInterceptRequest(
1218 URLRequest* request,
1219 NetworkDelegate* network_delegate) const override {
1220 if (restart_main_request_) {
1221 restart_main_request_ = false;
1222 did_restart_main_ = true;
1223 return new RestartTestJob(request, network_delegate);
1224 }
1225 if (cancel_main_request_) {
1226 cancel_main_request_ = false;
1227 did_cancel_main_ = true;
1228 return new CancelTestJob(request, network_delegate);
1229 }
1230 if (cancel_then_restart_main_request_) {
1231 cancel_then_restart_main_request_ = false;
1232 did_cancel_then_restart_main_ = true;
1233 return new CancelThenRestartTestJob(request, network_delegate);
1234 }
1235 if (simulate_main_network_error_) {
1236 simulate_main_network_error_ = false;
1237 did_simulate_error_main_ = true;
1238 if (use_url_request_http_job_) {
1239 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1240 }
1241 // This job will result in error since the requested URL is not one of the
1242 // URLs supported by these tests.
1243 return new URLRequestTestJob(request, network_delegate, true);
1244 }
1245 if (!intercept_main_request_)
1246 return nullptr;
1247 intercept_main_request_ = false;
1248 did_intercept_main_ = true;
1249 URLRequestTestJob* job = new URLRequestTestJob(request,
1250 network_delegate,
1251 main_headers_,
1252 main_data_,
1253 true);
1254 job->set_load_timing_info(main_request_load_timing_info_);
1255 return job;
1256 }
1257
1258 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1259 NetworkDelegate* network_delegate,
1260 const GURL& location) const override {
1261 if (cancel_redirect_request_) {
1262 cancel_redirect_request_ = false;
1263 did_cancel_redirect_ = true;
1264 return new CancelTestJob(request, network_delegate);
1265 }
1266 if (!intercept_redirect_)
1267 return nullptr;
1268 intercept_redirect_ = false;
1269 did_intercept_redirect_ = true;
1270 if (use_url_request_http_job_) {
1271 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1272 }
1273 return new URLRequestTestJob(request,
1274 network_delegate,
1275 redirect_headers_,
1276 redirect_data_,
1277 true);
1278 }
1279
1280 URLRequestJob* MaybeInterceptResponse(
1281 URLRequest* request,
1282 NetworkDelegate* network_delegate) const override {
1283 if (cancel_final_request_) {
1284 cancel_final_request_ = false;
1285 did_cancel_final_ = true;
1286 return new CancelTestJob(request, network_delegate);
1287 }
1288 if (!intercept_final_response_)
1289 return nullptr;
1290 intercept_final_response_ = false;
1291 did_intercept_final_ = true;
1292 if (use_url_request_http_job_) {
1293 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1294 }
1295 return new URLRequestTestJob(request,
1296 network_delegate,
1297 final_headers_,
1298 final_data_,
1299 true);
1300 }
1301
1302 void set_intercept_main_request(bool intercept_main_request) {
1303 intercept_main_request_ = intercept_main_request;
1304 }
1305
1306 void set_main_headers(const std::string& main_headers) {
1307 main_headers_ = main_headers;
1308 }
1309
1310 void set_main_data(const std::string& main_data) {
1311 main_data_ = main_data;
1312 }
1313
1314 void set_main_request_load_timing_info(
1315 const LoadTimingInfo& main_request_load_timing_info) {
1316 main_request_load_timing_info_ = main_request_load_timing_info;
1317 }
1318
1319 void set_restart_main_request(bool restart_main_request) {
1320 restart_main_request_ = restart_main_request;
1321 }
1322
1323 void set_cancel_main_request(bool cancel_main_request) {
1324 cancel_main_request_ = cancel_main_request;
1325 }
1326
1327 void set_cancel_then_restart_main_request(
1328 bool cancel_then_restart_main_request) {
1329 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1330 }
1331
1332 void set_simulate_main_network_error(bool simulate_main_network_error) {
1333 simulate_main_network_error_ = simulate_main_network_error;
1334 }
1335
1336 void set_intercept_redirect(bool intercept_redirect) {
1337 intercept_redirect_ = intercept_redirect;
1338 }
1339
1340 void set_redirect_headers(const std::string& redirect_headers) {
1341 redirect_headers_ = redirect_headers;
1342 }
1343
1344 void set_redirect_data(const std::string& redirect_data) {
1345 redirect_data_ = redirect_data;
1346 }
1347
1348 void set_cancel_redirect_request(bool cancel_redirect_request) {
1349 cancel_redirect_request_ = cancel_redirect_request;
1350 }
1351
1352 void set_intercept_final_response(bool intercept_final_response) {
1353 intercept_final_response_ = intercept_final_response;
1354 }
1355
1356 void set_final_headers(const std::string& final_headers) {
1357 final_headers_ = final_headers;
1358 }
1359
1360 void set_final_data(const std::string& final_data) {
1361 final_data_ = final_data;
1362 }
1363
1364 void set_cancel_final_request(bool cancel_final_request) {
1365 cancel_final_request_ = cancel_final_request;
1366 }
1367
1368 void set_use_url_request_http_job(bool use_url_request_http_job) {
1369 use_url_request_http_job_ = use_url_request_http_job;
1370 }
1371
1372 bool did_intercept_main() const {
1373 return did_intercept_main_;
1374 }
1375
1376 bool did_restart_main() const {
1377 return did_restart_main_;
1378 }
1379
1380 bool did_cancel_main() const {
1381 return did_cancel_main_;
1382 }
1383
1384 bool did_cancel_then_restart_main() const {
1385 return did_cancel_then_restart_main_;
1386 }
1387
1388 bool did_simulate_error_main() const {
1389 return did_simulate_error_main_;
1390 }
1391
1392 bool did_intercept_redirect() const {
1393 return did_intercept_redirect_;
1394 }
1395
1396 bool did_cancel_redirect() const {
1397 return did_cancel_redirect_;
1398 }
1399
1400 bool did_intercept_final() const {
1401 return did_intercept_final_;
1402 }
1403
1404 bool did_cancel_final() const {
1405 return did_cancel_final_;
1406 }
1407
1408 private:
1409 // Indicate whether to intercept the main request, and if so specify the
1410 // response to return and the LoadTimingInfo to use.
1411 mutable bool intercept_main_request_;
1412 mutable std::string main_headers_;
1413 mutable std::string main_data_;
1414 mutable LoadTimingInfo main_request_load_timing_info_;
1415
1416 // These indicate actions that can be taken within MaybeInterceptRequest.
1417 mutable bool restart_main_request_;
1418 mutable bool cancel_main_request_;
1419 mutable bool cancel_then_restart_main_request_;
1420 mutable bool simulate_main_network_error_;
1421
1422 // Indicate whether to intercept redirects, and if so specify the response to
1423 // return.
1424 mutable bool intercept_redirect_;
1425 mutable std::string redirect_headers_;
1426 mutable std::string redirect_data_;
1427
1428 // Cancel the request within MaybeInterceptRedirect.
1429 mutable bool cancel_redirect_request_;
1430
1431 // Indicate whether to intercept the final response, and if so specify the
1432 // response to return.
1433 mutable bool intercept_final_response_;
1434 mutable std::string final_headers_;
1435 mutable std::string final_data_;
1436
1437 // Cancel the final request within MaybeInterceptResponse.
1438 mutable bool cancel_final_request_;
1439
1440 // Instruct the interceptor to use a real URLRequestHTTPJob.
1441 mutable bool use_url_request_http_job_;
1442
1443 // These indicate if the interceptor did something or not.
1444 mutable bool did_intercept_main_;
1445 mutable bool did_restart_main_;
1446 mutable bool did_cancel_main_;
1447 mutable bool did_cancel_then_restart_main_;
1448 mutable bool did_simulate_error_main_;
1449 mutable bool did_intercept_redirect_;
1450 mutable bool did_cancel_redirect_;
1451 mutable bool did_intercept_final_;
1452 mutable bool did_cancel_final_;
1453};
1454
1455// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1456class URLRequestInterceptorTest : public URLRequestTest {
1457 public:
1458 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1459 }
1460
1461 ~URLRequestInterceptorTest() override {
1462 // URLRequestJobs may post clean-up tasks on destruction.
1463 base::RunLoop().RunUntilIdle();
1464 }
1465
1466 void SetUpFactory() override {
1467 interceptor_ = new MockURLRequestInterceptor();
1468 job_factory_.reset(new URLRequestInterceptingJobFactory(
1469 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1470 }
1471
1472 MockURLRequestInterceptor* interceptor() const {
1473 return interceptor_;
1474 }
1475
1476 private:
1477 MockURLRequestInterceptor* interceptor_;
1478};
1479
1480TEST_F(URLRequestInterceptorTest, Intercept) {
1481 // Intercept the main request and respond with a simple response.
1482 interceptor()->set_intercept_main_request(true);
1483 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1484 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591485 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501486 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361487 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501488 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1489 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1490 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1491 req->SetUserData(nullptr, user_data0);
1492 req->SetUserData(&user_data1, user_data1);
1493 req->SetUserData(&user_data2, user_data2);
1494 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191495 req->Start();
[email protected]255620da2013-08-19 13:14:291496 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591497
bengr1bf8e942014-11-07 01:36:501498 // Make sure we can retrieve our specific user data.
1499 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1500 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1501 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591502
bengr1bf8e942014-11-07 01:36:501503 // Check that we got one good response.
1504 EXPECT_TRUE(req->status().is_success());
1505 EXPECT_EQ(200, req->response_headers()->response_code());
1506 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1507 EXPECT_EQ(1, d.response_started_count());
1508 EXPECT_EQ(0, d.received_redirect_count());
1509}
[email protected]2bba3252013-04-08 19:50:591510
bengr1bf8e942014-11-07 01:36:501511TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1512 // Intercept the main request and respond with a redirect.
1513 interceptor()->set_intercept_main_request(true);
1514 interceptor()->set_main_headers(
1515 MockURLRequestInterceptor::redirect_headers());
1516 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1517
1518 // Intercept that redirect and respond with a final OK response.
1519 interceptor()->set_intercept_redirect(true);
1520 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1521 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1522
1523 TestDelegate d;
1524 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361525 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501526 req->set_method("GET");
1527 req->Start();
1528 base::RunLoop().Run();
1529
1530 // Check that the interceptor got called as expected.
1531 EXPECT_TRUE(interceptor()->did_intercept_main());
1532 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1533
1534 // Check that we got one good response.
1535 EXPECT_TRUE(req->status().is_success());
1536 if (req->status().is_success())
1537 EXPECT_EQ(200, req->response_headers()->response_code());
1538
1539 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1540 EXPECT_EQ(1, d.response_started_count());
1541 EXPECT_EQ(0, d.received_redirect_count());
1542}
1543
1544TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1545 // Intercept the main request to generate a server error response.
1546 interceptor()->set_intercept_main_request(true);
1547 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1548 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1549
1550 // Intercept that error and respond with an OK response.
1551 interceptor()->set_intercept_final_response(true);
1552 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1553 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1554
1555 TestDelegate d;
1556 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361557 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501558 req->set_method("GET");
1559 req->Start();
1560 base::RunLoop().Run();
1561
1562 // Check that the interceptor got called as expected.
1563 EXPECT_TRUE(interceptor()->did_intercept_main());
1564 EXPECT_TRUE(interceptor()->did_intercept_final());
1565
1566 // Check that we got one good response.
1567 EXPECT_TRUE(req->status().is_success());
1568 EXPECT_EQ(200, req->response_headers()->response_code());
1569 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1570 EXPECT_EQ(1, d.response_started_count());
1571 EXPECT_EQ(0, d.received_redirect_count());
1572}
1573
1574TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1575 // Intercept the main request to simulate a network error.
1576 interceptor()->set_simulate_main_network_error(true);
1577
1578 // Intercept that error and respond with an OK response.
1579 interceptor()->set_intercept_final_response(true);
1580 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1581 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1582
1583 TestDelegate d;
1584 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361585 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501586 req->set_method("GET");
1587 req->Start();
1588 base::RunLoop().Run();
1589
1590 // Check that the interceptor got called as expected.
1591 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1592 EXPECT_TRUE(interceptor()->did_intercept_final());
1593
1594 // Check that we received one good response.
1595 EXPECT_TRUE(req->status().is_success());
1596 EXPECT_EQ(200, req->response_headers()->response_code());
1597 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1598 EXPECT_EQ(1, d.response_started_count());
1599 EXPECT_EQ(0, d.received_redirect_count());
1600}
1601
1602TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1603 // Restart the main request.
1604 interceptor()->set_restart_main_request(true);
1605
1606 // then intercept the new main request and respond with an OK response
1607 interceptor()->set_intercept_main_request(true);
1608 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1609 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1610
1611 TestDelegate d;
1612 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361613 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501614 req->set_method("GET");
1615 req->Start();
1616 base::RunLoop().Run();
1617
1618 // Check that the interceptor got called as expected.
1619 EXPECT_TRUE(interceptor()->did_restart_main());
1620 EXPECT_TRUE(interceptor()->did_intercept_main());
1621
1622 // Check that we received one good response.
1623 EXPECT_TRUE(req->status().is_success());
1624 if (req->status().is_success())
1625 EXPECT_EQ(200, req->response_headers()->response_code());
1626
1627 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1628 EXPECT_EQ(1, d.response_started_count());
1629 EXPECT_EQ(0, d.received_redirect_count());
1630}
1631
1632TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1633 // Intercept the main request and cancel from within the restarted job.
1634 interceptor()->set_cancel_main_request(true);
1635
1636 // Set up to intercept the final response and override it with an OK response.
1637 interceptor()->set_intercept_final_response(true);
1638 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1639 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1640
1641 TestDelegate d;
1642 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361643 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501644 req->set_method("GET");
1645 req->Start();
1646 base::RunLoop().Run();
1647
1648 // Check that the interceptor got called as expected.
1649 EXPECT_TRUE(interceptor()->did_cancel_main());
1650 EXPECT_FALSE(interceptor()->did_intercept_final());
1651
1652 // Check that we see a canceled request.
1653 EXPECT_FALSE(req->status().is_success());
1654 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1655}
1656
1657TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1658 // Intercept the main request and respond with a redirect.
1659 interceptor()->set_intercept_main_request(true);
1660 interceptor()->set_main_headers(
1661 MockURLRequestInterceptor::redirect_headers());
1662 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1663
1664 // Intercept the redirect and cancel from within that job.
1665 interceptor()->set_cancel_redirect_request(true);
1666
1667 // Set up to intercept the final response and override it with an OK response.
1668 interceptor()->set_intercept_final_response(true);
1669 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1670 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1671
1672 TestDelegate d;
1673 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361674 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501675 req->set_method("GET");
1676 req->Start();
1677 base::RunLoop().Run();
1678
1679 // Check that the interceptor got called as expected.
1680 EXPECT_TRUE(interceptor()->did_intercept_main());
1681 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1682 EXPECT_FALSE(interceptor()->did_intercept_final());
1683
1684 // Check that we see a canceled request.
1685 EXPECT_FALSE(req->status().is_success());
1686 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1687}
1688
1689TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1690 // Intercept the main request to simulate a network error.
1691 interceptor()->set_simulate_main_network_error(true);
1692
1693 // Set up to intercept final the response and cancel from within that job.
1694 interceptor()->set_cancel_final_request(true);
1695
1696 TestDelegate d;
1697 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361698 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501699 req->set_method("GET");
1700 req->Start();
1701 base::RunLoop().Run();
1702
1703 // Check that the interceptor got called as expected.
1704 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1705 EXPECT_TRUE(interceptor()->did_cancel_final());
1706
1707 // Check that we see a canceled request.
1708 EXPECT_FALSE(req->status().is_success());
1709 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1710}
1711
1712TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1713 // Intercept the main request and cancel then restart from within that job.
1714 interceptor()->set_cancel_then_restart_main_request(true);
1715
1716 // Set up to intercept the final response and override it with an OK response.
1717 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501718 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1719 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501720
1721 TestDelegate d;
1722 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361723 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501724 req->set_method("GET");
1725 req->Start();
1726 base::RunLoop().Run();
1727
1728 // Check that the interceptor got called as expected.
1729 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1730 EXPECT_FALSE(interceptor()->did_intercept_final());
1731
1732 // Check that we see a canceled request.
1733 EXPECT_FALSE(req->status().is_success());
1734 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591735}
1736
1737// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1738// reused. |connect_time_flags| is used to indicate if there should be dns
1739// or SSL times, and |used_proxy| is used for proxy times.
1740LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1741 int connect_time_flags,
1742 bool used_proxy) {
1743 LoadTimingInfo load_timing;
1744 load_timing.socket_log_id = 1;
1745
1746 if (used_proxy) {
1747 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1748 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1749 }
1750
1751 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1752 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1753 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1754 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1755 }
1756 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1757 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1758 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1759 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1760 }
1761 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1762
1763 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1764 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1765 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1766 return load_timing;
1767}
1768
1769// Same as above, but in the case of a reused socket.
1770LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1771 bool used_proxy) {
1772 LoadTimingInfo load_timing;
1773 load_timing.socket_log_id = 1;
1774 load_timing.socket_reused = true;
1775
1776 if (used_proxy) {
1777 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1778 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1779 }
1780
1781 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1782 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1783 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1784 return load_timing;
1785}
1786
bengr1bf8e942014-11-07 01:36:501787LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1788 const LoadTimingInfo& job_load_timing,
1789 const URLRequestContext& context,
1790 MockURLRequestInterceptor* interceptor) {
1791 interceptor->set_intercept_main_request(true);
1792 interceptor->set_main_request_load_timing_info(job_load_timing);
1793 TestDelegate d;
1794 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361795 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501796 req->Start();
1797 base::RunLoop().Run();
1798
1799 LoadTimingInfo resulting_load_timing;
1800 req->GetLoadTimingInfo(&resulting_load_timing);
1801
1802 // None of these should be modified by the URLRequest.
1803 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1804 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1805 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1806 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1807 EXPECT_EQ(job_load_timing.receive_headers_end,
1808 resulting_load_timing.receive_headers_end);
1809
1810 return resulting_load_timing;
1811}
1812
[email protected]2bba3252013-04-08 19:50:591813// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501814TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591815 base::TimeTicks now = base::TimeTicks::Now();
1816 LoadTimingInfo job_load_timing =
1817 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1818
[email protected]2ca01e52013-10-31 22:05:191819 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501820 RunURLRequestInterceptorLoadTimingTest(
1821 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591822
1823 // Nothing should have been changed by the URLRequest.
1824 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1825 load_timing_result.proxy_resolve_start);
1826 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1827 load_timing_result.proxy_resolve_end);
1828 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1829 load_timing_result.connect_timing.dns_start);
1830 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1831 load_timing_result.connect_timing.dns_end);
1832 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1833 load_timing_result.connect_timing.connect_start);
1834 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1835 load_timing_result.connect_timing.connect_end);
1836 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1837 load_timing_result.connect_timing.ssl_start);
1838 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1839 load_timing_result.connect_timing.ssl_end);
1840
1841 // Redundant sanity check.
1842 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1843}
1844
1845// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501846TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591847 base::TimeTicks now = base::TimeTicks::Now();
1848 LoadTimingInfo job_load_timing =
1849 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1850
[email protected]2ca01e52013-10-31 22:05:191851 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501852 RunURLRequestInterceptorLoadTimingTest(
1853 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591854
1855 // Nothing should have been changed by the URLRequest.
1856 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1857 load_timing_result.proxy_resolve_start);
1858 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1859 load_timing_result.proxy_resolve_end);
1860 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1861 load_timing_result.connect_timing.dns_start);
1862 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1863 load_timing_result.connect_timing.dns_end);
1864 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1865 load_timing_result.connect_timing.connect_start);
1866 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1867 load_timing_result.connect_timing.connect_end);
1868 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1869 load_timing_result.connect_timing.ssl_start);
1870 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1871 load_timing_result.connect_timing.ssl_end);
1872
1873 // Redundant sanity check.
1874 TestLoadTimingNotReusedWithProxy(load_timing_result,
1875 CONNECT_TIMING_HAS_SSL_TIMES);
1876}
1877
1878// Make sure that URLRequest correctly adjusts proxy times when they're before
1879// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101880// the case of reusing a SPDY session. The connected socket is not considered
1881// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591882//
1883// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501884TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591885 base::TimeTicks now = base::TimeTicks::Now();
1886 LoadTimingInfo job_load_timing =
1887 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1888 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1889 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1890 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1891 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1892 job_load_timing.connect_timing.connect_start =
1893 now - base::TimeDelta::FromDays(2);
1894 job_load_timing.connect_timing.connect_end =
1895 now - base::TimeDelta::FromDays(1);
1896
[email protected]2ca01e52013-10-31 22:05:191897 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501898 RunURLRequestInterceptorLoadTimingTest(
1899 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591900
1901 // Proxy times, connect times, and DNS times should all be replaced with
1902 // request_start.
1903 EXPECT_EQ(load_timing_result.request_start,
1904 load_timing_result.proxy_resolve_start);
1905 EXPECT_EQ(load_timing_result.request_start,
1906 load_timing_result.proxy_resolve_end);
1907 EXPECT_EQ(load_timing_result.request_start,
1908 load_timing_result.connect_timing.dns_start);
1909 EXPECT_EQ(load_timing_result.request_start,
1910 load_timing_result.connect_timing.dns_end);
1911 EXPECT_EQ(load_timing_result.request_start,
1912 load_timing_result.connect_timing.connect_start);
1913 EXPECT_EQ(load_timing_result.request_start,
1914 load_timing_result.connect_timing.connect_end);
1915
1916 // Other times should have been left null.
1917 TestLoadTimingNotReusedWithProxy(load_timing_result,
1918 CONNECT_TIMING_HAS_DNS_TIMES);
1919}
1920
1921// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501922TEST_F(URLRequestInterceptorTest,
1923 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591924 base::TimeTicks now = base::TimeTicks::Now();
1925 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1926 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1927 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1928
[email protected]2ca01e52013-10-31 22:05:191929 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501930 RunURLRequestInterceptorLoadTimingTest(
1931 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591932
1933 // Proxy times and connect times should all be replaced with request_start.
1934 EXPECT_EQ(load_timing_result.request_start,
1935 load_timing_result.proxy_resolve_start);
1936 EXPECT_EQ(load_timing_result.request_start,
1937 load_timing_result.proxy_resolve_end);
1938
1939 // Other times should have been left null.
1940 TestLoadTimingReusedWithProxy(load_timing_result);
1941}
1942
1943// Make sure that URLRequest correctly adjusts connect times when they're before
1944// |request_start|, due to reusing a connected socket. The connected socket is
1945// not considered reused in this test (May be a preconnect).
1946//
1947// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501948TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:591949 base::TimeTicks now = base::TimeTicks::Now();
1950 LoadTimingInfo job_load_timing =
1951 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1952 job_load_timing.connect_timing.connect_start =
1953 now - base::TimeDelta::FromDays(1);
1954 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1955 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1956 job_load_timing.connect_timing.connect_end =
1957 now - base::TimeDelta::FromDays(4);
1958
[email protected]2ca01e52013-10-31 22:05:191959 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501960 RunURLRequestInterceptorLoadTimingTest(
1961 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591962
1963 // Connect times, and SSL times should be replaced with request_start.
1964 EXPECT_EQ(load_timing_result.request_start,
1965 load_timing_result.connect_timing.connect_start);
1966 EXPECT_EQ(load_timing_result.request_start,
1967 load_timing_result.connect_timing.ssl_start);
1968 EXPECT_EQ(load_timing_result.request_start,
1969 load_timing_result.connect_timing.ssl_end);
1970 EXPECT_EQ(load_timing_result.request_start,
1971 load_timing_result.connect_timing.connect_end);
1972
1973 // Other times should have been left null.
1974 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1975}
1976
1977// Make sure that URLRequest correctly adjusts connect times when they're before
1978// |request_start|, due to reusing a connected socket in the case that there
1979// are also proxy times. The connected socket is not considered reused in this
1980// test (May be a preconnect).
1981//
1982// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:501983TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:591984 base::TimeTicks now = base::TimeTicks::Now();
1985 LoadTimingInfo job_load_timing =
1986 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1987 job_load_timing.connect_timing.connect_start =
1988 now - base::TimeDelta::FromDays(1);
1989 job_load_timing.connect_timing.connect_end =
1990 now - base::TimeDelta::FromDays(2);
1991
[email protected]2ca01e52013-10-31 22:05:191992 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501993 RunURLRequestInterceptorLoadTimingTest(
1994 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591995
1996 // Connect times should be replaced with proxy_resolve_end.
1997 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1998 load_timing_result.connect_timing.connect_start);
1999 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2000 load_timing_result.connect_timing.connect_end);
2001
2002 // Other times should have been left null.
2003 TestLoadTimingNotReusedWithProxy(load_timing_result,
2004 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2005}
2006
[email protected]316c1e5e2012-09-12 15:17:442007// Check that two different URL requests have different identifiers.
2008TEST_F(URLRequestTest, Identifiers) {
2009 TestDelegate d;
2010 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362011 scoped_ptr<URLRequest> req(
2012 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2013 scoped_ptr<URLRequest> other_req(
2014 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442015
mmenke19378d22014-09-09 04:12:592016 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442017}
2018
2019// Check that a failure to connect to the proxy is reported to the network
2020// delegate.
2021TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2022 MockHostResolver host_resolver;
2023 host_resolver.rules()->AddSimulatedFailure("*");
2024
[email protected]ceefd7fd2012-11-29 00:36:242025 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442026 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2027
2028 TestDelegate d;
davidben151423e2015-03-23 18:48:362029 scoped_ptr<URLRequest> req(
2030 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192031 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442032
[email protected]f7022f32014-08-21 16:32:192033 req->Start();
[email protected]255620da2013-08-19 13:14:292034 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442035
2036 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192037 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152038 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192039 EXPECT_TRUE(req->proxy_server().IsEmpty());
2040 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2041 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442042
2043 EXPECT_EQ(1, network_delegate.error_count());
2044 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2045 EXPECT_EQ(1, network_delegate.completed_requests());
2046}
2047
[email protected]cba24642014-08-15 20:49:592048// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442049// content is empty.
2050TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2051 TestDelegate d;
davidben151423e2015-03-23 18:48:362052 scoped_ptr<URLRequest> req(
2053 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192054 req->Start();
[email protected]255620da2013-08-19 13:14:292055 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442056 EXPECT_EQ("", d.data_received());
2057 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2058}
2059
[email protected]5033ab82013-03-22 20:17:462060// Make sure that SetPriority actually sets the URLRequest's priority
2061// correctly, both before and after start.
2062TEST_F(URLRequestTest, SetPriorityBasic) {
2063 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192064 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362065 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192066 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462067
[email protected]f7022f32014-08-21 16:32:192068 req->SetPriority(LOW);
2069 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462070
[email protected]f7022f32014-08-21 16:32:192071 req->Start();
2072 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462073
[email protected]f7022f32014-08-21 16:32:192074 req->SetPriority(MEDIUM);
2075 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462076}
2077
2078// Make sure that URLRequest calls SetPriority on a job before calling
2079// Start on it.
2080TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2081 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192082 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362083 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192084 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462085
2086 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192087 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502088 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462089 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2090
[email protected]f7022f32014-08-21 16:32:192091 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462092
[email protected]f7022f32014-08-21 16:32:192093 req->Start();
[email protected]5033ab82013-03-22 20:17:462094 EXPECT_EQ(LOW, job->priority());
2095}
2096
2097// Make sure that URLRequest passes on its priority updates to its
2098// job.
2099TEST_F(URLRequestTest, SetJobPriority) {
2100 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192101 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362102 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462103
2104 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192105 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502106 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462107
[email protected]f7022f32014-08-21 16:32:192108 req->SetPriority(LOW);
2109 req->Start();
[email protected]5033ab82013-03-22 20:17:462110 EXPECT_EQ(LOW, job->priority());
2111
[email protected]f7022f32014-08-21 16:32:192112 req->SetPriority(MEDIUM);
2113 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462114 EXPECT_EQ(MEDIUM, job->priority());
2115}
2116
[email protected]bb1c4662013-11-14 00:00:072117// Setting the IGNORE_LIMITS load flag should be okay if the priority
2118// is MAXIMUM_PRIORITY.
2119TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2120 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192121 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362122 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192123 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072124
2125 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192126 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072127 AddTestInterceptor()->set_main_intercept_job(job.get());
2128
[email protected]f7022f32014-08-21 16:32:192129 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2130 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072131
[email protected]f7022f32014-08-21 16:32:192132 req->SetPriority(MAXIMUM_PRIORITY);
2133 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072134
[email protected]f7022f32014-08-21 16:32:192135 req->Start();
2136 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072137 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2138}
2139
[email protected]ce7d0cbc2013-05-03 18:57:222140// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442141#if !defined(OS_IOS)
nick5d570de92015-05-04 20:16:162142namespace {
2143
2144// Less verbose way of running a simple testserver for the tests below.
[email protected]ce7d0cbc2013-05-03 18:57:222145class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442146 public:
[email protected]6cdfd7f2013-02-08 20:40:152147 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222148 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162149 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222150 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442151 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222152 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
nick5d570de92015-05-04 20:16:162153 SpawnedTestServer::kLocalhost,
[email protected]ce7d0cbc2013-05-03 18:57:222154 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442155};
2156
nick5d570de92015-05-04 20:16:162157} // namespace
2158
[email protected]f2f31b32013-01-16 23:24:092159TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442160 LocalHttpTestServer test_server;
2161 ASSERT_TRUE(test_server.Start());
2162
2163 TestURLRequestContext context;
2164 scoped_refptr<DelayedCookieMonster> delayed_cm =
2165 new DelayedCookieMonster();
2166 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502167 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442168
2169 // Set up a cookie.
2170 {
2171 TestNetworkDelegate network_delegate;
2172 context.set_network_delegate(&network_delegate);
2173 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192174 scoped_ptr<URLRequest> req(context.CreateRequest(
2175 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362176 &d));
[email protected]f7022f32014-08-21 16:32:192177 req->Start();
[email protected]255620da2013-08-19 13:14:292178 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442179 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2180 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2181 EXPECT_EQ(1, network_delegate.set_cookie_count());
2182 }
2183
2184 // Verify that the cookie is set.
2185 {
2186 TestNetworkDelegate network_delegate;
2187 context.set_network_delegate(&network_delegate);
2188 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192189 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:362190 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192191 req->Start();
[email protected]255620da2013-08-19 13:14:292192 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442193
2194 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2195 != std::string::npos);
2196 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2197 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2198 }
2199}
2200
[email protected]f2f31b32013-01-16 23:24:092201TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442202 LocalHttpTestServer test_server;
2203 ASSERT_TRUE(test_server.Start());
2204
2205 // Set up a cookie.
2206 {
2207 TestNetworkDelegate network_delegate;
2208 default_context_.set_network_delegate(&network_delegate);
2209 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192210 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2211 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362212 &d));
[email protected]f7022f32014-08-21 16:32:192213 req->Start();
[email protected]255620da2013-08-19 13:14:292214 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442215 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2216 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2217 }
2218
2219 // Verify that the cookie is set.
2220 {
2221 TestNetworkDelegate network_delegate;
2222 default_context_.set_network_delegate(&network_delegate);
2223 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192224 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362225 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192226 req->Start();
[email protected]255620da2013-08-19 13:14:292227 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442228
2229 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2230 != std::string::npos);
2231 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2232 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2233 }
2234
2235 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2236 {
2237 TestNetworkDelegate network_delegate;
2238 default_context_.set_network_delegate(&network_delegate);
2239 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192240 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362241 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192242 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2243 req->Start();
[email protected]255620da2013-08-19 13:14:292244 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442245
2246 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2247 == std::string::npos);
2248
2249 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2250 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2251 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2252 }
2253}
2254
2255TEST_F(URLRequestTest, DoNotSaveCookies) {
2256 LocalHttpTestServer test_server;
2257 ASSERT_TRUE(test_server.Start());
2258
2259 // Set up a cookie.
2260 {
2261 TestNetworkDelegate network_delegate;
2262 default_context_.set_network_delegate(&network_delegate);
2263 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192264 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2265 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362266 &d));
[email protected]f7022f32014-08-21 16:32:192267 req->Start();
[email protected]255620da2013-08-19 13:14:292268 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442269
2270 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2271 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2272 EXPECT_EQ(1, network_delegate.set_cookie_count());
2273 }
2274
2275 // Try to set-up another cookie and update the previous cookie.
2276 {
2277 TestNetworkDelegate network_delegate;
2278 default_context_.set_network_delegate(&network_delegate);
2279 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192280 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442281 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362282 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192283 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2284 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442285
[email protected]255620da2013-08-19 13:14:292286 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442287
2288 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2289 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2290 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2291 EXPECT_EQ(0, network_delegate.set_cookie_count());
2292 }
2293
2294 // Verify the cookies weren't saved or updated.
2295 {
2296 TestNetworkDelegate network_delegate;
2297 default_context_.set_network_delegate(&network_delegate);
2298 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192299 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362300 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192301 req->Start();
[email protected]255620da2013-08-19 13:14:292302 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442303
2304 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2305 == std::string::npos);
2306 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2307 != std::string::npos);
2308
2309 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2310 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2311 EXPECT_EQ(0, network_delegate.set_cookie_count());
2312 }
2313}
2314
2315TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2316 LocalHttpTestServer test_server;
2317 ASSERT_TRUE(test_server.Start());
2318
2319 // Set up a cookie.
2320 {
2321 TestNetworkDelegate network_delegate;
2322 default_context_.set_network_delegate(&network_delegate);
2323 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192324 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2325 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362326 &d));
[email protected]f7022f32014-08-21 16:32:192327 req->Start();
[email protected]255620da2013-08-19 13:14:292328 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442329
2330 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2331 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2332 }
2333
2334 // Verify that the cookie is set.
2335 {
2336 TestNetworkDelegate network_delegate;
2337 default_context_.set_network_delegate(&network_delegate);
2338 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192339 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362340 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192341 req->Start();
[email protected]255620da2013-08-19 13:14:292342 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442343
2344 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2345 != std::string::npos);
2346
2347 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2348 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2349 }
2350
2351 // Verify that the cookie isn't sent.
2352 {
2353 TestNetworkDelegate network_delegate;
2354 default_context_.set_network_delegate(&network_delegate);
2355 TestDelegate d;
2356 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192357 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362358 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192359 req->Start();
[email protected]255620da2013-08-19 13:14:292360 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442361
2362 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2363 == std::string::npos);
2364
[email protected]22e045f2013-09-20 03:54:032365 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442366 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2367 }
2368}
2369
2370TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2371 LocalHttpTestServer test_server;
2372 ASSERT_TRUE(test_server.Start());
2373
2374 // Set up a cookie.
2375 {
2376 TestNetworkDelegate network_delegate;
2377 default_context_.set_network_delegate(&network_delegate);
2378 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192379 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2380 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362381 &d));
[email protected]f7022f32014-08-21 16:32:192382 req->Start();
[email protected]255620da2013-08-19 13:14:292383 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442384
2385 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2386 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2387 }
2388
2389 // Try to set-up another cookie and update the previous cookie.
2390 {
2391 TestNetworkDelegate network_delegate;
2392 default_context_.set_network_delegate(&network_delegate);
2393 TestDelegate d;
2394 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192395 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442396 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362397 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192398 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442399
[email protected]255620da2013-08-19 13:14:292400 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442401
2402 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2403 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2404 }
2405
2406 // Verify the cookies weren't saved or updated.
2407 {
2408 TestNetworkDelegate network_delegate;
2409 default_context_.set_network_delegate(&network_delegate);
2410 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192411 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362412 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192413 req->Start();
[email protected]255620da2013-08-19 13:14:292414 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442415
2416 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2417 == std::string::npos);
2418 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2419 != std::string::npos);
2420
2421 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2422 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2423 }
2424}
2425
2426TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2427 LocalHttpTestServer test_server;
2428 ASSERT_TRUE(test_server.Start());
2429
2430 // Set up an empty cookie.
2431 {
2432 TestNetworkDelegate network_delegate;
2433 default_context_.set_network_delegate(&network_delegate);
2434 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192435 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362436 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192437 req->Start();
[email protected]255620da2013-08-19 13:14:292438 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442439
2440 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2441 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2442 EXPECT_EQ(0, network_delegate.set_cookie_count());
2443 }
2444}
2445
2446TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2447 LocalHttpTestServer test_server;
2448 ASSERT_TRUE(test_server.Start());
2449
2450 // Set up a cookie.
2451 {
2452 TestNetworkDelegate network_delegate;
2453 default_context_.set_network_delegate(&network_delegate);
2454 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192455 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2456 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362457 &d));
[email protected]f7022f32014-08-21 16:32:192458 req->Start();
[email protected]255620da2013-08-19 13:14:292459 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442460
2461 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2462 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2463 }
2464
2465 // Verify that the cookie is set.
2466 {
2467 TestNetworkDelegate network_delegate;
2468 default_context_.set_network_delegate(&network_delegate);
2469 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192470 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362471 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192472 req->Start();
[email protected]255620da2013-08-19 13:14:292473 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442474
2475 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2476 != std::string::npos);
2477
2478 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2479 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2480 }
2481
2482 // Verify that the cookie isn't sent.
2483 {
2484 TestNetworkDelegate network_delegate;
2485 default_context_.set_network_delegate(&network_delegate);
2486 TestDelegate d;
2487 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192488 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362489 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192490 req->Start();
[email protected]255620da2013-08-19 13:14:292491 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442492
2493 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2494 == std::string::npos);
2495
[email protected]22e045f2013-09-20 03:54:032496 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442497 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2498 }
2499}
2500
2501TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2502 LocalHttpTestServer test_server;
2503 ASSERT_TRUE(test_server.Start());
2504
2505 // Set up a cookie.
2506 {
2507 TestNetworkDelegate network_delegate;
2508 default_context_.set_network_delegate(&network_delegate);
2509 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192510 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2511 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362512 &d));
[email protected]f7022f32014-08-21 16:32:192513 req->Start();
[email protected]255620da2013-08-19 13:14:292514 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442515
2516 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2517 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2518 }
2519
2520 // Try to set-up another cookie and update the previous cookie.
2521 {
2522 TestNetworkDelegate network_delegate;
2523 default_context_.set_network_delegate(&network_delegate);
2524 TestDelegate d;
2525 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192526 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442527 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362528 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192529 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442530
[email protected]255620da2013-08-19 13:14:292531 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442532
2533 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2534 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2535 }
2536
2537 // Verify the cookies weren't saved or updated.
2538 {
2539 TestNetworkDelegate network_delegate;
2540 default_context_.set_network_delegate(&network_delegate);
2541 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192542 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362543 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192544 req->Start();
[email protected]255620da2013-08-19 13:14:292545 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442546
2547 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2548 == std::string::npos);
2549 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2550 != std::string::npos);
2551
2552 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2553 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2554 }
2555}
2556
mkwst3f3daac2015-02-26 20:15:262557TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2558 LocalHttpTestServer test_server;
2559 ASSERT_TRUE(test_server.Start());
2560
2561 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2562 // LocalHttpTestServer points).
2563 {
2564 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152565 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262566 default_context_.set_network_delegate(&network_delegate);
2567
2568 TestDelegate d;
2569 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2570 test_server.GetURL(
2571 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362572 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262573 req->Start();
2574 base::RunLoop().Run();
2575 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2576 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2577 EXPECT_EQ(1, network_delegate.set_cookie_count());
2578 }
2579
2580 // Verify that the cookie is sent for first-party requests.
2581 {
2582 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152583 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262584 default_context_.set_network_delegate(&network_delegate);
2585 TestDelegate d;
2586 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362587 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472588 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst3f3daac2015-02-26 20:15:262589 req->Start();
2590 base::RunLoop().Run();
2591
2592 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2593 std::string::npos);
2594 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2595 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2596 }
2597
2598 // Verify that the cookie is not-sent for non-first-party requests.
2599 {
2600 TestNetworkDelegate network_delegate;
mkwst0513c9d2015-04-01 05:53:152601 network_delegate.set_first_party_only_cookies_enabled(true);
mkwst3f3daac2015-02-26 20:15:262602 default_context_.set_network_delegate(&network_delegate);
2603 TestDelegate d;
2604 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362605 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262606 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2607 req->Start();
2608 base::RunLoop().Run();
2609
2610 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2611 std::string::npos);
2612 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2613 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2614 }
2615}
2616
mkwst0513c9d2015-04-01 05:53:152617TEST_F(URLRequestTest, FirstPartyOnlyCookiesDisabled) {
2618 LocalHttpTestServer test_server;
2619 ASSERT_TRUE(test_server.Start());
2620
2621 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2622 // LocalHttpTestServer points).
2623 {
2624 TestNetworkDelegate network_delegate;
2625 network_delegate.set_first_party_only_cookies_enabled(false);
2626 default_context_.set_network_delegate(&network_delegate);
2627
2628 TestDelegate d;
2629 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2630 test_server.GetURL(
2631 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
2632 DEFAULT_PRIORITY, &d));
2633 req->Start();
2634 base::RunLoop().Run();
2635 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2636 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2637 EXPECT_EQ(1, network_delegate.set_cookie_count());
2638 }
2639
2640 // Verify that the cookie is sent for first-party requests.
2641 {
2642 TestNetworkDelegate network_delegate;
2643 network_delegate.set_first_party_only_cookies_enabled(false);
2644 default_context_.set_network_delegate(&network_delegate);
2645 TestDelegate d;
2646 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2647 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estark92df3fd2015-04-06 19:57:472648 req->set_first_party_for_cookies(test_server.GetURL(""));
mkwst0513c9d2015-04-01 05:53:152649 req->Start();
2650 base::RunLoop().Run();
2651
2652 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2653 std::string::npos);
2654 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2655 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2656 }
2657
2658 // Verify that the cookie is also sent for non-first-party requests.
2659 {
2660 TestNetworkDelegate network_delegate;
2661 network_delegate.set_first_party_only_cookies_enabled(false);
2662 default_context_.set_network_delegate(&network_delegate);
2663 TestDelegate d;
2664 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2665 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2666 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2667 req->Start();
2668 base::RunLoop().Run();
2669
2670 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2671 std::string::npos);
2672 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2673 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2674 }
2675}
2676
[email protected]5095cd72012-11-01 10:29:162677// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2678// value for the |fixed_date| argument given to the constructor.
2679class FixedDateNetworkDelegate : public TestNetworkDelegate {
2680 public:
2681 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2682 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202683 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162684
[email protected]cba24642014-08-15 20:49:592685 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202686 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592687 URLRequest* request,
2688 const CompletionCallback& callback,
2689 const HttpResponseHeaders* original_response_headers,
2690 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132691 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162692
2693 private:
2694 std::string fixed_date_;
2695
2696 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2697};
2698
2699int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592700 URLRequest* request,
2701 const CompletionCallback& callback,
2702 const HttpResponseHeaders* original_response_headers,
2703 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162704 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592705 HttpResponseHeaders* new_response_headers =
2706 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162707
2708 new_response_headers->RemoveHeader("Date");
2709 new_response_headers->AddHeader("Date: " + fixed_date_);
2710
2711 *override_response_headers = new_response_headers;
2712 return TestNetworkDelegate::OnHeadersReceived(request,
2713 callback,
2714 original_response_headers,
[email protected]5f714132014-03-26 10:41:162715 override_response_headers,
2716 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162717}
2718
2719// Test that cookie expiration times are adjusted for server/client clock
2720// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2721// headers by defaulting to GMT. (crbug.com/135131)
2722TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2723 LocalHttpTestServer test_server;
2724 ASSERT_TRUE(test_server.Start());
2725
2726 // Set up an expired cookie.
2727 {
2728 TestNetworkDelegate network_delegate;
2729 default_context_.set_network_delegate(&network_delegate);
2730 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192731 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192732 test_server.GetURL(
2733 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362734 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192735 req->Start();
[email protected]255620da2013-08-19 13:14:292736 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162737 }
2738 // Verify that the cookie is not set.
2739 {
2740 TestNetworkDelegate network_delegate;
2741 default_context_.set_network_delegate(&network_delegate);
2742 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192743 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362744 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192745 req->Start();
[email protected]255620da2013-08-19 13:14:292746 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162747
2748 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2749 }
2750 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2751 {
2752 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2753 default_context_.set_network_delegate(&network_delegate);
2754 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192755 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192756 test_server.GetURL(
2757 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362758 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192759 req->Start();
[email protected]255620da2013-08-19 13:14:292760 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162761 }
2762 // Verify that the cookie is set.
2763 {
2764 TestNetworkDelegate network_delegate;
2765 default_context_.set_network_delegate(&network_delegate);
2766 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192767 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362768 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192769 req->Start();
[email protected]255620da2013-08-19 13:14:292770 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162771
2772 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2773 }
2774}
2775
2776
[email protected]316c1e5e2012-09-12 15:17:442777// Check that it is impossible to change the referrer in the extra headers of
2778// an URLRequest.
2779TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2780 LocalHttpTestServer test_server;
2781 ASSERT_TRUE(test_server.Start());
2782
2783 // If extra headers contain referer and the request contains a referer,
2784 // only the latter shall be respected.
2785 {
2786 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192787 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362788 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192789 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442790
2791 HttpRequestHeaders headers;
2792 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192793 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:442794
[email protected]f7022f32014-08-21 16:32:192795 req->Start();
[email protected]255620da2013-08-19 13:14:292796 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442797
2798 EXPECT_EQ("http://foo.com/", d.data_received());
2799 }
2800
2801 // If extra headers contain a referer but the request does not, no referer
2802 // shall be sent in the header.
2803 {
2804 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192805 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362806 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442807
2808 HttpRequestHeaders headers;
2809 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192810 req->SetExtraRequestHeaders(headers);
2811 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442812
[email protected]f7022f32014-08-21 16:32:192813 req->Start();
[email protected]255620da2013-08-19 13:14:292814 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442815
2816 EXPECT_EQ("None", d.data_received());
2817 }
2818}
2819
[email protected]b89290212009-08-14 22:37:352820class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112821 public:
2822 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152823 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112824 "net/data/url_request_unittest"))) {
2825 }
2826
[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);
5162 path = path.Append(FILE_PATH_LITERAL("net"));
5163 path = path.Append(FILE_PATH_LITERAL("data"));
5164 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5165 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365166 element_readers.push_back(
5167 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5168 path,
5169 0,
5170 kuint64max,
5171 base::Time()));
mmenkecbc2b712014-10-09 20:29:075172 r->set_upload(make_scoped_ptr<UploadDataStream>(
5173 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445174
[email protected]f7022f32014-08-21 16:32:195175 r->Start();
5176 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445177
[email protected]255620da2013-08-19 13:14:295178 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445179
pkasting6b68a162014-12-01 22:10:295180 int64 size64 = 0;
5181 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5182 ASSERT_LE(size64, std::numeric_limits<int>::max());
5183 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175184 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445185
[email protected]7600d0b2013-12-08 21:43:305186 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445187
[email protected]329b68b2012-11-14 17:54:275188 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195189 << "request failed: " << r->status().status()
5190 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445191
5192 EXPECT_FALSE(d.received_data_before_response());
5193
[email protected]329b68b2012-11-14 17:54:275194 EXPECT_EQ(size, d.bytes_received());
5195 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445196 }
5197}
5198
[email protected]999dd8c2013-11-12 06:45:545199TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5200 ASSERT_TRUE(test_server_.Start());
5201
5202 TestDelegate d;
5203 {
[email protected]f7022f32014-08-21 16:32:195204 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365205 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195206 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545207
5208 ScopedVector<UploadElementReader> element_readers;
5209
5210 element_readers.push_back(new UploadFileElementReader(
5211 base::MessageLoopProxy::current().get(),
5212 base::FilePath(FILE_PATH_LITERAL(
5213 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5214 0,
5215 kuint64max,
5216 base::Time()));
mmenkecbc2b712014-10-09 20:29:075217 r->set_upload(make_scoped_ptr<UploadDataStream>(
5218 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545219
[email protected]f7022f32014-08-21 16:32:195220 r->Start();
5221 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545222
5223 base::RunLoop().Run();
5224
[email protected]999dd8c2013-11-12 06:45:545225 EXPECT_TRUE(d.request_failed());
5226 EXPECT_FALSE(d.received_data_before_response());
5227 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195228 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5229 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545230 }
5231}
5232
[email protected]316c1e5e2012-09-12 15:17:445233TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5234 ASSERT_TRUE(test_server_.Start());
5235
5236 TestDelegate d;
5237 {
[email protected]f7022f32014-08-21 16:32:195238 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365239 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195240 r->EnableChunkedUpload();
5241 r->set_method("POST");
5242 AddChunksToUpload(r.get());
5243 r->Start();
5244 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445245
[email protected]255620da2013-08-19 13:14:295246 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445247
[email protected]f7022f32014-08-21 16:32:195248 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445249 }
5250}
5251
[email protected]329b68b2012-11-14 17:54:275252TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5253 ASSERT_TRUE(test_server_.Start());
5254
5255 TestDelegate d;
5256 {
[email protected]f7022f32014-08-21 16:32:195257 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365258 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195259 r->EnableChunkedUpload();
5260 r->set_method("POST");
5261 r->Start();
5262 EXPECT_TRUE(r->is_pending());
5263 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295264 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275265
[email protected]f7022f32014-08-21 16:32:195266 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275267 }
5268}
5269
[email protected]316c1e5e2012-09-12 15:17:445270TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5271 ASSERT_TRUE(test_server_.Start());
5272
5273 TestDelegate d;
5274 {
[email protected]f7022f32014-08-21 16:32:195275 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365276 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195277 r->EnableChunkedUpload();
5278 r->set_method("POST");
5279 r->Start();
5280 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445281
[email protected]255620da2013-08-19 13:14:295282 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195283 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295284 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445285
[email protected]f7022f32014-08-21 16:32:195286 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445287 }
5288}
5289
5290TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5291 ASSERT_TRUE(test_server_.Start());
5292
5293 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195294 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365295 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195296 req->Start();
[email protected]255620da2013-08-19 13:14:295297 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445298
[email protected]f7022f32014-08-21 16:32:195299 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445300
5301 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195302 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445303
5304 std::string header;
5305 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5306 EXPECT_EQ("private", header);
5307
5308 header.clear();
5309 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5310 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5311
5312 // The response has two "X-Multiple-Entries" headers.
5313 // This verfies our output has them concatenated together.
5314 header.clear();
5315 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5316 EXPECT_EQ("a, b", header);
5317}
5318
[email protected]242d8562012-10-30 21:20:465319TEST_F(URLRequestTestHTTP, ProcessSTS) {
estarka5da76702015-04-09 04:00:165320 SpawnedTestServer::SSLOptions ssl_options(
5321 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]ce7d0cbc2013-05-03 18:57:225322 SpawnedTestServer https_test_server(
5323 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465324 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155325 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465326 ASSERT_TRUE(https_test_server.Start());
5327
estarka5da76702015-04-09 04:00:165328 std::string test_server_hostname = https_test_server.GetURL("").host();
5329
[email protected]242d8562012-10-30 21:20:465330 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195331 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365332 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5333 &d));
[email protected]f7022f32014-08-21 16:32:195334 request->Start();
[email protected]255620da2013-08-19 13:14:295335 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465336
5337 TransportSecurityState* security_state =
5338 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465339 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165340 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5341 &domain_state));
[email protected]242d8562012-10-30 21:20:465342 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265343 domain_state.sts.upgrade_mode);
5344 EXPECT_TRUE(domain_state.sts.include_subdomains);
5345 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275346#if defined(OS_ANDROID)
5347 // Android's CertVerifyProc does not (yet) handle pins.
5348#else
5349 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5350#endif
5351}
5352
estarka5da76702015-04-09 04:00:165353TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
5354 SpawnedTestServer https_test_server(
5355 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
5356 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5357 ASSERT_TRUE(https_test_server.Start());
5358 // Make sure this test fails if the test server is changed to not
5359 // listen on an IP by default.
5360 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5361 std::string test_server_hostname = https_test_server.GetURL("").host();
5362
5363 TestDelegate d;
5364 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5365 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5366 &d));
5367 request->Start();
5368 base::RunLoop().Run();
5369
5370 TransportSecurityState* security_state =
5371 default_context_.transport_security_state();
5372 TransportSecurityState::DomainState domain_state;
5373 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5374 &domain_state));
5375}
5376
[email protected]37fd55fb2013-06-29 13:13:275377// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5378// reject HPKP headers, and a test setting only HPKP headers will fail (no
5379// DomainState present because header rejected).
5380#if defined(OS_ANDROID)
5381#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5382#else
5383#define MAYBE_ProcessPKP ProcessPKP
5384#endif
5385
5386// Tests that enabling HPKP on a domain does not affect the HSTS
5387// validity/expiration.
5388TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estarka5da76702015-04-09 04:00:165389 SpawnedTestServer::SSLOptions ssl_options(
5390 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]37fd55fb2013-06-29 13:13:275391 SpawnedTestServer https_test_server(
5392 SpawnedTestServer::TYPE_HTTPS,
5393 ssl_options,
5394 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5395 ASSERT_TRUE(https_test_server.Start());
5396
estarka5da76702015-04-09 04:00:165397 std::string test_server_hostname = https_test_server.GetURL("").host();
5398
[email protected]37fd55fb2013-06-29 13:13:275399 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195400 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365401 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5402 &d));
[email protected]f7022f32014-08-21 16:32:195403 request->Start();
[email protected]255620da2013-08-19 13:14:295404 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275405
5406 TransportSecurityState* security_state =
5407 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275408 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165409 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5410 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275411 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265412 domain_state.sts.upgrade_mode);
5413 EXPECT_FALSE(domain_state.sts.include_subdomains);
5414 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275415 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265416 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465417}
5418
estarka5da76702015-04-09 04:00:165419TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
5420 SpawnedTestServer https_test_server(
5421 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::SSLOptions(),
5422 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5423 ASSERT_TRUE(https_test_server.Start());
5424 // Make sure this test fails if the test server is changed to not
5425 // listen on an IP by default.
5426 ASSERT_TRUE(https_test_server.GetURL("").HostIsIPAddress());
5427 std::string test_server_hostname = https_test_server.GetURL("").host();
5428
5429 TestDelegate d;
5430 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5431 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5432 &d));
5433 request->Start();
5434 base::RunLoop().Run();
5435
5436 TransportSecurityState* security_state =
5437 default_context_.transport_security_state();
5438 TransportSecurityState::DomainState domain_state;
5439 EXPECT_FALSE(security_state->GetDynamicDomainState(test_server_hostname,
5440 &domain_state));
5441}
5442
[email protected]242d8562012-10-30 21:20:465443TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
estarka5da76702015-04-09 04:00:165444 SpawnedTestServer::SSLOptions ssl_options(
5445 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]ce7d0cbc2013-05-03 18:57:225446 SpawnedTestServer https_test_server(
5447 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465448 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155449 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465450 ASSERT_TRUE(https_test_server.Start());
5451
estarka5da76702015-04-09 04:00:165452 std::string test_server_hostname = https_test_server.GetURL("").host();
5453
[email protected]242d8562012-10-30 21:20:465454 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195455 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465456 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365457 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195458 request->Start();
[email protected]255620da2013-08-19 13:14:295459 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465460
5461 // We should have set parameters from the first header, not the second.
5462 TransportSecurityState* security_state =
5463 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465464 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165465 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5466 &domain_state));
[email protected]242d8562012-10-30 21:20:465467 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265468 domain_state.sts.upgrade_mode);
5469 EXPECT_FALSE(domain_state.sts.include_subdomains);
5470 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465471}
5472
[email protected]9f972ec2013-04-10 20:24:365473TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
estarka5da76702015-04-09 04:00:165474 SpawnedTestServer::SSLOptions ssl_options(
5475 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]ce7d0cbc2013-05-03 18:57:225476 SpawnedTestServer https_test_server(
5477 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:365478 ssl_options,
5479 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5480 ASSERT_TRUE(https_test_server.Start());
5481
estarka5da76702015-04-09 04:00:165482 std::string test_server_hostname = https_test_server.GetURL("").host();
5483
[email protected]9f972ec2013-04-10 20:24:365484 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195485 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365486 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
davidben151423e2015-03-23 18:48:365487 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195488 request->Start();
[email protected]255620da2013-08-19 13:14:295489 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365490
5491 // We should have set parameters from the first header, not the second.
5492 TransportSecurityState* security_state =
5493 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365494 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165495 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5496 &domain_state));
[email protected]9f972ec2013-04-10 20:24:365497 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265498 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365499#if defined(OS_ANDROID)
5500 // Android's CertVerifyProc does not (yet) handle pins.
5501#else
5502 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5503#endif
[email protected]9e6968d2014-05-07 21:46:265504 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365505
[email protected]a165f092013-06-12 16:10:055506 // Even though there is an HSTS header asserting includeSubdomains, it is
5507 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265508 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055509 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265510 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365511}
5512
[email protected]37fd55fb2013-06-29 13:13:275513// Tests that when multiple HPKP headers are present, asserting different
5514// policies, that only the first such policy is processed.
5515TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
estarka5da76702015-04-09 04:00:165516 SpawnedTestServer::SSLOptions ssl_options(
5517 SpawnedTestServer::SSLOptions::CERT_COMMON_NAME_IS_DOMAIN);
[email protected]37fd55fb2013-06-29 13:13:275518 SpawnedTestServer https_test_server(
5519 SpawnedTestServer::TYPE_HTTPS,
5520 ssl_options,
5521 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5522 ASSERT_TRUE(https_test_server.Start());
5523
estarka5da76702015-04-09 04:00:165524 std::string test_server_hostname = https_test_server.GetURL("").host();
5525
[email protected]37fd55fb2013-06-29 13:13:275526 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195527 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275528 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:365529 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195530 request->Start();
[email protected]255620da2013-08-19 13:14:295531 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275532
5533 TransportSecurityState* security_state =
5534 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275535 TransportSecurityState::DomainState domain_state;
estarka5da76702015-04-09 04:00:165536 EXPECT_TRUE(security_state->GetDynamicDomainState(test_server_hostname,
5537 &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275538 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265539 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275540#if defined(OS_ANDROID)
5541 // Android's CertVerifyProc does not (yet) handle pins.
5542#else
5543 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5544#endif
[email protected]9e6968d2014-05-07 21:46:265545 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275546
[email protected]9e6968d2014-05-07 21:46:265547 EXPECT_TRUE(domain_state.sts.include_subdomains);
5548 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275549}
5550
[email protected]316c1e5e2012-09-12 15:17:445551TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5552 ASSERT_TRUE(test_server_.Start());
5553
5554 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195555 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5556 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:365557 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195558 req->Start();
[email protected]255620da2013-08-19 13:14:295559 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445560
5561 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195562 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445563 EXPECT_EQ("text/html", mime_type);
5564
5565 std::string charset;
[email protected]f7022f32014-08-21 16:32:195566 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445567 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195568 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445569}
5570
[email protected]02494ec2014-05-07 15:05:295571TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345572 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345573 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345574 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025575 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345576
5577 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505578 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345579}
5580
[email protected]02494ec2014-05-07 15:05:295581#if !defined(DISABLE_FILE_SUPPORT)
5582TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5583 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5584 GURL file_url("file:///foo.txt");
5585 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5586 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5587
5588 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505589 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295590}
5591
[email protected]588614c22013-08-16 00:09:025592TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445593 ASSERT_TRUE(test_server_.Start());
5594
5595 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195596 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365597 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5598 &d));
[email protected]f7022f32014-08-21 16:32:195599 req->Start();
[email protected]255620da2013-08-19 13:14:295600 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445601
[email protected]f7022f32014-08-21 16:32:195602 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5603 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445604}
[email protected]02494ec2014-05-07 15:05:295605#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445606
[email protected]588614c22013-08-16 00:09:025607TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5608 ASSERT_TRUE(test_server_.Start());
5609
5610 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195611 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365612 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5613 &d));
[email protected]f7022f32014-08-21 16:32:195614 req->Start();
[email protected]588614c22013-08-16 00:09:025615 base::MessageLoop::current()->Run();
5616
[email protected]f7022f32014-08-21 16:32:195617 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5618 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025619}
5620
[email protected]316c1e5e2012-09-12 15:17:445621TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5622 ASSERT_TRUE(test_server_.Start());
5623
5624 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195625 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5626 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:365627 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195628 req->Start();
[email protected]255620da2013-08-19 13:14:295629 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445630
[email protected]f7022f32014-08-21 16:32:195631 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5632 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445633}
5634
[email protected]e50efea2014-03-24 18:41:005635// Make sure redirects are cached, despite not reading their bodies.
5636TEST_F(URLRequestTestHTTP, CacheRedirect) {
5637 ASSERT_TRUE(test_server_.Start());
5638 GURL redirect_url =
5639 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5640
5641 {
5642 TestDelegate d;
davidben151423e2015-03-23 18:48:365643 scoped_ptr<URLRequest> req(
5644 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195645 req->Start();
[email protected]e50efea2014-03-24 18:41:005646 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195647 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005648 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195649 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005650 }
5651
5652 {
5653 TestDelegate d;
5654 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:365655 scoped_ptr<URLRequest> req(
5656 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195657 req->Start();
[email protected]e50efea2014-03-24 18:41:005658 base::RunLoop().Run();
5659
5660 EXPECT_EQ(1, d.received_redirect_count());
5661 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195662 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005663
[email protected]f7022f32014-08-21 16:32:195664 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005665 base::RunLoop().Run();
5666 EXPECT_EQ(1, d.received_redirect_count());
5667 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195668 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5669 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005670 }
5671}
5672
5673// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5674// when the headers are read, since the body won't have been read.
5675TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5676 ASSERT_TRUE(test_server_.Start());
5677 // URL that is normally cached.
5678 GURL initial_url = test_server_.GetURL("cachetime");
5679
5680 {
5681 // Set up the TestNetworkDelegate tp force a redirect.
5682 GURL redirect_to_url = test_server_.GetURL("echo");
5683 default_network_delegate_.set_redirect_on_headers_received_url(
5684 redirect_to_url);
5685
5686 TestDelegate d;
davidben151423e2015-03-23 18:48:365687 scoped_ptr<URLRequest> req(
5688 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195689 req->Start();
[email protected]e50efea2014-03-24 18:41:005690 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195691 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005692 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195693 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005694 }
5695
5696 {
5697 TestDelegate d;
davidben151423e2015-03-23 18:48:365698 scoped_ptr<URLRequest> req(
5699 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195700 req->Start();
[email protected]e50efea2014-03-24 18:41:005701 base::RunLoop().Run();
5702
[email protected]f7022f32014-08-21 16:32:195703 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5704 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005705 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195706 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005707 }
5708}
5709
[email protected]5f714132014-03-26 10:41:165710// Tests that redirection to an unsafe URL is allowed when it has been marked as
5711// safe.
5712TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5713 ASSERT_TRUE(test_server_.Start());
5714
5715 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5716 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5717 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5718
5719 TestDelegate d;
5720 {
[email protected]f7022f32014-08-21 16:32:195721 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365722 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165723
[email protected]f7022f32014-08-21 16:32:195724 r->Start();
[email protected]5f714132014-03-26 10:41:165725 base::RunLoop().Run();
5726
[email protected]f7022f32014-08-21 16:32:195727 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165728
[email protected]f7022f32014-08-21 16:32:195729 EXPECT_EQ(2U, r->url_chain().size());
5730 EXPECT_EQ(OK, r->status().error());
5731 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165732 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5733 }
5734}
5735
5736// Tests that a redirect to a different unsafe URL is blocked, even after adding
5737// some other URL to the whitelist.
5738TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5739 ASSERT_TRUE(test_server_.Start());
5740
5741 GURL unsafe_url("data:text/html,something");
5742 GURL different_unsafe_url("data:text/html,something-else");
5743 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5744 default_network_delegate_.set_allowed_unsafe_redirect_url(
5745 different_unsafe_url);
5746
5747 TestDelegate d;
5748 {
[email protected]f7022f32014-08-21 16:32:195749 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365750 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165751
[email protected]f7022f32014-08-21 16:32:195752 r->Start();
[email protected]5f714132014-03-26 10:41:165753 base::RunLoop().Run();
5754
[email protected]f7022f32014-08-21 16:32:195755 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5756 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165757 }
5758}
5759
[email protected]5f714132014-03-26 10:41:165760// Redirects from an URL with fragment to an unsafe URL with fragment should
5761// be allowed, and the reference fragment of the target URL should be preserved.
5762TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5763 ASSERT_TRUE(test_server_.Start());
5764
5765 GURL original_url(test_server_.GetURL("original#fragment1"));
5766 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5767 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5768
5769 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5770 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5771
5772 TestDelegate d;
5773 {
davidben151423e2015-03-23 18:48:365774 scoped_ptr<URLRequest> r(
5775 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165776
[email protected]f7022f32014-08-21 16:32:195777 r->Start();
[email protected]5f714132014-03-26 10:41:165778 base::RunLoop().Run();
5779
[email protected]f7022f32014-08-21 16:32:195780 EXPECT_EQ(2U, r->url_chain().size());
5781 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5782 EXPECT_EQ(OK, r->status().error());
5783 EXPECT_EQ(original_url, r->original_url());
5784 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165785 }
5786}
5787
5788// When a delegate has specified a safe redirect URL, but it does not match the
5789// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145790TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165791 ASSERT_TRUE(test_server_.Start());
5792
5793 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5794 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5795 GURL redirect_url(test_server_.GetURL("target"));
5796 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5797
5798 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5799 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5800
5801 TestDelegate d;
5802 {
davidben151423e2015-03-23 18:48:365803 scoped_ptr<URLRequest> r(
5804 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165805
[email protected]f7022f32014-08-21 16:32:195806 r->Start();
[email protected]5f714132014-03-26 10:41:165807 base::RunLoop().Run();
5808
[email protected]f7022f32014-08-21 16:32:195809 EXPECT_EQ(2U, r->url_chain().size());
5810 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5811 EXPECT_EQ(OK, r->status().error());
5812 EXPECT_EQ(original_url, r->original_url());
5813 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:165814 }
5815}
5816
[email protected]f878230e2014-04-03 15:36:145817// When a delegate has specified a safe redirect URL, assume that the redirect
5818// URL should not be changed. In particular, the reference fragment should not
5819// be modified.
5820TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5821 ASSERT_TRUE(test_server_.Start());
5822
5823 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5824 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5825
5826 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5827 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5828
5829 TestDelegate d;
5830 {
davidben151423e2015-03-23 18:48:365831 scoped_ptr<URLRequest> r(
5832 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145833
[email protected]f7022f32014-08-21 16:32:195834 r->Start();
[email protected]f878230e2014-04-03 15:36:145835 base::RunLoop().Run();
5836
[email protected]f7022f32014-08-21 16:32:195837 EXPECT_EQ(2U, r->url_chain().size());
5838 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5839 EXPECT_EQ(OK, r->status().error());
5840 EXPECT_EQ(original_url, r->original_url());
5841 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145842 }
5843}
5844
5845// When a URLRequestRedirectJob is created, the redirection must be followed and
5846// the reference fragment of the target URL must not be modified.
5847TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5848 ASSERT_TRUE(test_server_.Start());
5849
5850 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5851 GURL redirect_url(test_server_.GetURL("echo"));
5852
5853 TestDelegate d;
davidben151423e2015-03-23 18:48:365854 scoped_ptr<URLRequest> r(
5855 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145856
5857 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:195858 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:145859 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5860 AddTestInterceptor()->set_main_intercept_job(job);
5861
[email protected]f7022f32014-08-21 16:32:195862 r->Start();
[email protected]f878230e2014-04-03 15:36:145863 base::RunLoop().Run();
5864
[email protected]f7022f32014-08-21 16:32:195865 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5866 EXPECT_EQ(OK, r->status().error());
5867 EXPECT_EQ(original_url, r->original_url());
5868 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145869}
5870
[email protected]316c1e5e2012-09-12 15:17:445871TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5872 ASSERT_TRUE(test_server_.Start());
5873
5874 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195875 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365876 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195877 req->SetReferrer("http://user:[email protected]/");
5878 req->Start();
[email protected]255620da2013-08-19 13:14:295879 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445880
5881 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5882}
5883
[email protected]99ecf6e2013-04-10 22:46:135884TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5885 ASSERT_TRUE(test_server_.Start());
5886
5887 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195888 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365889 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195890 req->SetReferrer("http://foo.com/test#fragment");
5891 req->Start();
[email protected]255620da2013-08-19 13:14:295892 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135893
5894 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5895}
5896
5897TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5898 ASSERT_TRUE(test_server_.Start());
5899
5900 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195901 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365902 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195903 req->SetReferrer("http://foo.com/test#fragment");
5904 req->SetReferrer("");
5905 req->Start();
[email protected]255620da2013-08-19 13:14:295906 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135907
5908 EXPECT_EQ(std::string("None"), d.data_received());
5909}
5910
[email protected]1826a402014-01-08 15:40:485911// Defer network start and then resume, checking that the request was a success
5912// and bytes were received.
5913TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5914 ASSERT_TRUE(test_server_.Start());
5915
5916 TestDelegate d;
5917 {
5918 d.set_quit_on_network_start(true);
5919 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365920 scoped_ptr<URLRequest> req(
5921 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485922
[email protected]f7022f32014-08-21 16:32:195923 req->Start();
[email protected]1826a402014-01-08 15:40:485924 base::RunLoop().Run();
5925
5926 EXPECT_EQ(1, d.received_before_network_start_count());
5927 EXPECT_EQ(0, d.response_started_count());
5928
[email protected]f7022f32014-08-21 16:32:195929 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485930 base::RunLoop().Run();
5931
5932 EXPECT_EQ(1, d.response_started_count());
5933 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195934 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485935 }
5936}
5937
5938// Check that OnBeforeNetworkStart is only called once even if there is a
5939// redirect.
5940TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5941 ASSERT_TRUE(test_server_.Start());
5942
5943 TestDelegate d;
5944 {
5945 d.set_quit_on_redirect(true);
5946 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:195947 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365948 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485949
[email protected]f7022f32014-08-21 16:32:195950 req->Start();
[email protected]1826a402014-01-08 15:40:485951 base::RunLoop().Run();
5952
5953 EXPECT_EQ(1, d.received_before_network_start_count());
5954 EXPECT_EQ(0, d.response_started_count());
5955 EXPECT_EQ(0, d.received_redirect_count());
5956
[email protected]f7022f32014-08-21 16:32:195957 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485958 base::RunLoop().Run();
5959
5960 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195961 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:485962 base::RunLoop().Run();
5963
5964 // Check that the redirect's new network transaction does not get propagated
5965 // to a second OnBeforeNetworkStart() notification.
5966 EXPECT_EQ(1, d.received_before_network_start_count());
5967
5968 EXPECT_EQ(1, d.response_started_count());
5969 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195970 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485971 }
5972}
5973
5974// Cancel the request after learning that the request would use the network.
5975TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5976 ASSERT_TRUE(test_server_.Start());
5977
5978 TestDelegate d;
5979 {
5980 d.set_quit_on_network_start(true);
5981 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365982 scoped_ptr<URLRequest> req(
5983 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485984
[email protected]f7022f32014-08-21 16:32:195985 req->Start();
[email protected]1826a402014-01-08 15:40:485986 base::RunLoop().Run();
5987
5988 EXPECT_EQ(1, d.received_before_network_start_count());
5989 EXPECT_EQ(0, d.response_started_count());
5990
[email protected]f7022f32014-08-21 16:32:195991 req->Cancel();
[email protected]1826a402014-01-08 15:40:485992 base::RunLoop().Run();
5993
5994 EXPECT_EQ(1, d.response_started_count());
5995 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195996 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:485997 }
5998}
5999
[email protected]316c1e5e2012-09-12 15:17:446000TEST_F(URLRequestTestHTTP, CancelRedirect) {
6001 ASSERT_TRUE(test_server_.Start());
6002
6003 TestDelegate d;
6004 {
6005 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196006 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366007 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196008 req->Start();
[email protected]255620da2013-08-19 13:14:296009 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446010
6011 EXPECT_EQ(1, d.response_started_count());
6012 EXPECT_EQ(0, d.bytes_received());
6013 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196014 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446015 }
6016}
6017
6018TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6019 ASSERT_TRUE(test_server_.Start());
6020
6021 TestDelegate d;
6022 {
6023 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:046024 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366025 scoped_ptr<URLRequest> req(
6026 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046027
[email protected]f7022f32014-08-21 16:32:196028 req->Start();
[email protected]255620da2013-08-19 13:14:296029 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446030
6031 EXPECT_EQ(1, d.received_redirect_count());
6032
[email protected]f7022f32014-08-21 16:32:196033 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296034 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446035
6036 EXPECT_EQ(1, d.response_started_count());
6037 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196038 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446039
[email protected]6cdfd7f2013-02-08 20:40:156040 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446041 PathService::Get(base::DIR_SOURCE_ROOT, &path);
6042 path = path.Append(FILE_PATH_LITERAL("net"));
6043 path = path.Append(FILE_PATH_LITERAL("data"));
6044 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6045 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6046
6047 std::string contents;
[email protected]82f84b92013-08-30 18:23:506048 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446049 EXPECT_EQ(contents, d.data_received());
6050 }
6051}
6052
[email protected]79e1fd62013-06-20 06:50:046053TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6054 ASSERT_TRUE(test_server_.Start());
6055
6056 TestDelegate d;
6057 {
6058 d.set_quit_on_redirect(true);
6059 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:366060 scoped_ptr<URLRequest> req(
6061 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046062
6063 EXPECT_FALSE(d.have_full_request_headers());
6064
[email protected]f7022f32014-08-21 16:32:196065 req->Start();
[email protected]255620da2013-08-19 13:14:296066 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046067
6068 EXPECT_EQ(1, d.received_redirect_count());
6069 EXPECT_TRUE(d.have_full_request_headers());
6070 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6071 d.ClearFullRequestHeaders();
6072
[email protected]f7022f32014-08-21 16:32:196073 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296074 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046075
6076 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6077 EXPECT_EQ(1, d.response_started_count());
6078 EXPECT_TRUE(d.have_full_request_headers());
6079 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6080 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196081 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046082
6083 base::FilePath path;
6084 PathService::Get(base::DIR_SOURCE_ROOT, &path);
6085 path = path.Append(FILE_PATH_LITERAL("net"));
6086 path = path.Append(FILE_PATH_LITERAL("data"));
6087 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6088 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6089
6090 std::string contents;
[email protected]82f84b92013-08-30 18:23:506091 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046092 EXPECT_EQ(contents, d.data_received());
6093 }
6094}
6095
[email protected]316c1e5e2012-09-12 15:17:446096TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6097 ASSERT_TRUE(test_server_.Start());
6098
6099 TestDelegate d;
6100 {
6101 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196102 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366103 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196104 req->Start();
[email protected]255620da2013-08-19 13:14:296105 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446106
6107 EXPECT_EQ(1, d.received_redirect_count());
6108
[email protected]f7022f32014-08-21 16:32:196109 req->Cancel();
[email protected]255620da2013-08-19 13:14:296110 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446111
6112 EXPECT_EQ(1, d.response_started_count());
6113 EXPECT_EQ(0, d.bytes_received());
6114 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196115 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446116 }
6117}
6118
6119TEST_F(URLRequestTestHTTP, VaryHeader) {
6120 ASSERT_TRUE(test_server_.Start());
6121
[email protected]3b23a222013-05-15 21:33:256122 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446123 {
6124 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196125 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366126 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446127 HttpRequestHeaders headers;
6128 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196129 req->SetExtraRequestHeaders(headers);
6130 req->Start();
[email protected]255620da2013-08-19 13:14:296131 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256132
6133 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196134 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256135 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446136 }
6137
[email protected]3b23a222013-05-15 21:33:256138 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446139 {
6140 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196141 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366142 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446143 HttpRequestHeaders headers;
6144 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196145 req->SetExtraRequestHeaders(headers);
6146 req->Start();
[email protected]255620da2013-08-19 13:14:296147 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446148
[email protected]f7022f32014-08-21 16:32:196149 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256150
6151 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196152 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256153 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446154 }
6155
[email protected]3b23a222013-05-15 21:33:256156 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446157 {
6158 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196159 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366160 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446161 HttpRequestHeaders headers;
6162 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196163 req->SetExtraRequestHeaders(headers);
6164 req->Start();
[email protected]255620da2013-08-19 13:14:296165 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446166
[email protected]f7022f32014-08-21 16:32:196167 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256168
6169 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196170 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256171 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446172 }
6173}
6174
6175TEST_F(URLRequestTestHTTP, BasicAuth) {
6176 ASSERT_TRUE(test_server_.Start());
6177
6178 // populate the cache
6179 {
6180 TestDelegate d;
6181 d.set_credentials(AuthCredentials(kUser, kSecret));
6182
[email protected]f7022f32014-08-21 16:32:196183 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366184 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196185 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446186
[email protected]255620da2013-08-19 13:14:296187 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446188
6189 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6190 }
6191
6192 // repeat request with end-to-end validation. since auth-basic results in a
6193 // cachable page, we expect this test to result in a 304. in which case, the
6194 // response should be fetched from the cache.
6195 {
6196 TestDelegate d;
6197 d.set_credentials(AuthCredentials(kUser, kSecret));
6198
[email protected]f7022f32014-08-21 16:32:196199 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366200 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196201 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6202 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446203
[email protected]255620da2013-08-19 13:14:296204 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446205
6206 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6207
6208 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196209 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446210 }
6211}
6212
6213// Check that Set-Cookie headers in 401 responses are respected.
6214// http://crbug.com/6450
6215TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6216 ASSERT_TRUE(test_server_.Start());
6217
6218 GURL url_requiring_auth =
6219 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6220
6221 // Request a page that will give a 401 containing a Set-Cookie header.
6222 // Verify that when the transaction is restarted, it includes the new cookie.
6223 {
[email protected]ceefd7fd2012-11-29 00:36:246224 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446225 TestURLRequestContext context(true);
6226 context.set_network_delegate(&network_delegate);
6227 context.Init();
6228
6229 TestDelegate d;
6230 d.set_credentials(AuthCredentials(kUser, kSecret));
6231
davidben151423e2015-03-23 18:48:366232 scoped_ptr<URLRequest> r(
6233 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196234 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446235
[email protected]255620da2013-08-19 13:14:296236 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446237
6238 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6239
6240 // Make sure we sent the cookie in the restarted transaction.
6241 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6242 != std::string::npos);
6243 }
6244
6245 // Same test as above, except this time the restart is initiated earlier
6246 // (without user intervention since identity is embedded in the URL).
6247 {
[email protected]ceefd7fd2012-11-29 00:36:246248 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446249 TestURLRequestContext context(true);
6250 context.set_network_delegate(&network_delegate);
6251 context.Init();
6252
6253 TestDelegate d;
6254
6255 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186256 replacements.SetUsernameStr("user2");
6257 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446258 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6259
davidben151423e2015-03-23 18:48:366260 scoped_ptr<URLRequest> r(
6261 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196262 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446263
[email protected]255620da2013-08-19 13:14:296264 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446265
6266 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6267
6268 // Make sure we sent the cookie in the restarted transaction.
6269 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6270 != std::string::npos);
6271 }
6272}
6273
[email protected]58e32bb2013-01-21 18:23:256274// Tests that load timing works as expected with auth and the cache.
6275TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6276 ASSERT_TRUE(test_server_.Start());
6277
6278 // populate the cache
6279 {
6280 TestDelegate d;
6281 d.set_credentials(AuthCredentials(kUser, kSecret));
6282
[email protected]f7022f32014-08-21 16:32:196283 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366284 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196285 r->Start();
[email protected]58e32bb2013-01-21 18:23:256286
[email protected]255620da2013-08-19 13:14:296287 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256288
6289 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6290
6291 LoadTimingInfo load_timing_info_before_auth;
6292 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6293 &load_timing_info_before_auth));
6294 TestLoadTimingNotReused(load_timing_info_before_auth,
6295 CONNECT_TIMING_HAS_DNS_TIMES);
6296
6297 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196298 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256299 // The test server does not support keep alive sockets, so the second
6300 // request with auth should use a new socket.
6301 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6302 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6303 load_timing_info.socket_log_id);
6304 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6305 load_timing_info.connect_timing.connect_start);
6306 }
6307
[email protected]3b23a222013-05-15 21:33:256308 // Repeat request with end-to-end validation. Since auth-basic results in a
6309 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256310 // response should be fetched from the cache.
6311 {
6312 TestDelegate d;
6313 d.set_credentials(AuthCredentials(kUser, kSecret));
6314
[email protected]f7022f32014-08-21 16:32:196315 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366316 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196317 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6318 r->Start();
[email protected]58e32bb2013-01-21 18:23:256319
[email protected]255620da2013-08-19 13:14:296320 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256321
6322 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6323
6324 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196325 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256326
[email protected]3b23a222013-05-15 21:33:256327 // Since there was a request that went over the wire, the load timing
6328 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256329 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196330 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256331 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256332 }
6333}
6334
[email protected]316c1e5e2012-09-12 15:17:446335// In this test, we do a POST which the server will 302 redirect.
6336// The subsequent transaction should use GET, and should not send the
6337// Content-Type header.
6338// http://code.google.com/p/chromium/issues/detail?id=843
6339TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6340 ASSERT_TRUE(test_server_.Start());
6341
6342 const char kData[] = "hello world";
6343
6344 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196345 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366346 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196347 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076348 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446349
6350 // Set headers (some of which are specific to the POST).
6351 HttpRequestHeaders headers;
6352 headers.AddHeadersFromString(
6353 "Content-Type: multipart/form-data; "
6354 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6355 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6356 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6357 "Accept-Language: en-US,en\r\n"
6358 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6359 "Content-Length: 11\r\n"
6360 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196361 req->SetExtraRequestHeaders(headers);
6362 req->Start();
[email protected]255620da2013-08-19 13:14:296363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446364
6365 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196366 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446367 EXPECT_EQ("text/html", mime_type);
6368
6369 const std::string& data = d.data_received();
6370
6371 // Check that the post-specific headers were stripped:
6372 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6373 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6374 EXPECT_FALSE(ContainsString(data, "Origin:"));
6375
6376 // These extra request headers should not have been stripped.
6377 EXPECT_TRUE(ContainsString(data, "Accept:"));
6378 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6379 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6380}
6381
jww5fe460ff2015-03-28 00:22:516382// The following tests check that we handle mutating the request for HTTP
6383// redirects as expected.
6384// See https://crbug.com/56373, https://crbug.com/102130, and
6385// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446386
6387TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6388 ASSERT_TRUE(test_server_.Start());
6389
6390 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516391 const GURL https_redirect_url =
6392 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446393
6394 HTTPRedirectMethodTest(url, "POST", "GET", true);
6395 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6396 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516397
6398 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6399 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6400 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6401 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6402 std::string());
[email protected]316c1e5e2012-09-12 15:17:446403}
6404
6405TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6406 ASSERT_TRUE(test_server_.Start());
6407
6408 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516409 const GURL https_redirect_url =
6410 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446411
6412 HTTPRedirectMethodTest(url, "POST", "GET", true);
6413 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6414 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516415
6416 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6417 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6418 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6419 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6420 std::string());
[email protected]316c1e5e2012-09-12 15:17:446421}
6422
6423TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6424 ASSERT_TRUE(test_server_.Start());
6425
6426 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516427 const GURL https_redirect_url =
6428 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446429
6430 HTTPRedirectMethodTest(url, "POST", "GET", true);
6431 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6432 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516433
6434 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6435 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6436 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6437 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6438 std::string());
[email protected]316c1e5e2012-09-12 15:17:446439}
6440
6441TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6442 ASSERT_TRUE(test_server_.Start());
6443
6444 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516445 const GURL https_redirect_url =
6446 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446447
6448 HTTPRedirectMethodTest(url, "POST", "POST", true);
6449 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6450 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516451
6452 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6453 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6454 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6455 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446456}
6457
[email protected]0a17aab32014-04-24 03:32:376458TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6459 ASSERT_TRUE(test_server_.Start());
6460
6461 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516462 const GURL https_redirect_url =
6463 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376464
6465 HTTPRedirectMethodTest(url, "POST", "POST", true);
6466 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6467 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516468
6469 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6470 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6471 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6472 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376473}
6474
6475// Make sure that 308 responses without bodies are not treated as redirects.
6476// Certain legacy apis that pre-date the response code expect this behavior
6477// (Like Google Drive).
6478TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6479 ASSERT_TRUE(test_server_.Start());
6480
6481 TestDelegate d;
6482 const GURL url = test_server_.GetURL("files/308-without-location-header");
6483
davidben151423e2015-03-23 18:48:366484 scoped_ptr<URLRequest> request(
6485 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376486
[email protected]f7022f32014-08-21 16:32:196487 request->Start();
[email protected]0a17aab32014-04-24 03:32:376488 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196489 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6490 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376491 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196492 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376493 EXPECT_EQ("This is not a redirect.", d.data_received());
6494}
6495
[email protected]f878230e2014-04-03 15:36:146496TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6497 ASSERT_TRUE(test_server_.Start());
6498
6499 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6500 GURL expected_url(test_server_.GetURL("echo#fragment"));
6501
6502 TestDelegate d;
6503 {
davidben151423e2015-03-23 18:48:366504 scoped_ptr<URLRequest> r(
6505 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146506
[email protected]f7022f32014-08-21 16:32:196507 r->Start();
[email protected]f878230e2014-04-03 15:36:146508 base::RunLoop().Run();
6509
[email protected]f7022f32014-08-21 16:32:196510 EXPECT_EQ(2U, r->url_chain().size());
6511 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6512 EXPECT_EQ(OK, r->status().error());
6513 EXPECT_EQ(original_url, r->original_url());
6514 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146515 }
6516}
6517
[email protected]cba24642014-08-15 20:49:596518TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6519 ASSERT_TRUE(test_server_.Start());
6520
6521 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6522 GURL first_party_url("http://example.com");
6523
6524 TestDelegate d;
6525 {
davidben151423e2015-03-23 18:48:366526 scoped_ptr<URLRequest> r(
6527 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196528 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596529
[email protected]f7022f32014-08-21 16:32:196530 r->Start();
[email protected]cba24642014-08-15 20:49:596531 base::RunLoop().Run();
6532
[email protected]f7022f32014-08-21 16:32:196533 EXPECT_EQ(2U, r->url_chain().size());
6534 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6535 EXPECT_EQ(OK, r->status().error());
6536 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596537 }
6538}
6539
6540TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6541 ASSERT_TRUE(test_server_.Start());
6542
6543 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6544 GURL original_first_party_url("http://example.com");
6545 GURL expected_first_party_url(test_server_.GetURL("echo"));
6546
6547 TestDelegate d;
6548 {
davidben151423e2015-03-23 18:48:366549 scoped_ptr<URLRequest> r(
6550 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196551 r->set_first_party_for_cookies(original_first_party_url);
6552 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596553 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6554
[email protected]f7022f32014-08-21 16:32:196555 r->Start();
[email protected]cba24642014-08-15 20:49:596556 base::RunLoop().Run();
6557
[email protected]f7022f32014-08-21 16:32:196558 EXPECT_EQ(2U, r->url_chain().size());
6559 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6560 EXPECT_EQ(OK, r->status().error());
6561 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596562 }
6563}
6564
[email protected]316c1e5e2012-09-12 15:17:446565TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6566 ASSERT_TRUE(test_server_.Start());
6567
6568 const char kData[] = "hello world";
6569
6570 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196571 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366572 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196573 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076574 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446575 HttpRequestHeaders headers;
6576 headers.SetHeader(HttpRequestHeaders::kContentLength,
6577 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196578 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446579
6580 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196581 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096582 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446583 AddTestInterceptor()->set_main_intercept_job(job);
6584
[email protected]f7022f32014-08-21 16:32:196585 req->Start();
[email protected]255620da2013-08-19 13:14:296586 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196587 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446588}
6589
6590TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6591 ASSERT_TRUE(test_server_.Start());
6592
6593 const char kData[] = "hello world";
6594
6595 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196596 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366597 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196598 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076599 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446600 HttpRequestHeaders headers;
6601 headers.SetHeader(HttpRequestHeaders::kContentLength,
6602 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196603 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446604
6605 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196606 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096607 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6608 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446609 AddTestInterceptor()->set_main_intercept_job(job);
6610
[email protected]f7022f32014-08-21 16:32:196611 req->Start();
[email protected]255620da2013-08-19 13:14:296612 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196613 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446614 EXPECT_EQ(kData, d.data_received());
6615}
6616
6617// Check that default A-L header is sent.
6618TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6619 ASSERT_TRUE(test_server_.Start());
6620
[email protected]8790210c2013-12-02 05:29:536621 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246622 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446623 TestURLRequestContext context(true);
6624 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436625 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446626 context.Init();
6627
6628 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196629 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366630 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196631 req->Start();
[email protected]255620da2013-08-19 13:14:296632 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446633 EXPECT_EQ("en", d.data_received());
6634}
6635
6636// Check that an empty A-L header is not sent. http://crbug.com/77365.
6637TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6638 ASSERT_TRUE(test_server_.Start());
6639
[email protected]8790210c2013-12-02 05:29:536640 std::string empty_string; // Avoid most vexing parse on line below.
6641 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246642 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446643 TestURLRequestContext context(true);
6644 context.set_network_delegate(&network_delegate);
6645 context.Init();
6646 // We override the language after initialization because empty entries
6647 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436648 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446649
6650 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196651 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366652 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196653 req->Start();
[email protected]255620da2013-08-19 13:14:296654 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446655 EXPECT_EQ("None", d.data_received());
6656}
6657
6658// Check that if request overrides the A-L header, the default is not appended.
6659// See http://crbug.com/20894
6660TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6661 ASSERT_TRUE(test_server_.Start());
6662
6663 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196664 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366665 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446666 HttpRequestHeaders headers;
6667 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196668 req->SetExtraRequestHeaders(headers);
6669 req->Start();
[email protected]255620da2013-08-19 13:14:296670 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446671 EXPECT_EQ(std::string("ru"), d.data_received());
6672}
6673
6674// Check that default A-E header is sent.
6675TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6676 ASSERT_TRUE(test_server_.Start());
6677
6678 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196679 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366680 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446681 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196682 req->SetExtraRequestHeaders(headers);
6683 req->Start();
[email protected]255620da2013-08-19 13:14:296684 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446685 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6686}
6687
6688// Check that if request overrides the A-E header, the default is not appended.
6689// See http://crbug.com/47381
6690TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6691 ASSERT_TRUE(test_server_.Start());
6692
6693 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196694 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366695 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446696 HttpRequestHeaders headers;
6697 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196698 req->SetExtraRequestHeaders(headers);
6699 req->Start();
[email protected]255620da2013-08-19 13:14:296700 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446701 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6702 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6703}
6704
[email protected]84f05432013-03-15 01:00:126705// Check that setting the A-C header sends the proper header.
6706TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446707 ASSERT_TRUE(test_server_.Start());
6708
6709 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196710 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366711 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446712 HttpRequestHeaders headers;
6713 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196714 req->SetExtraRequestHeaders(headers);
6715 req->Start();
[email protected]255620da2013-08-19 13:14:296716 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446717 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6718}
6719
6720// Check that default User-Agent header is sent.
6721TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6722 ASSERT_TRUE(test_server_.Start());
6723
6724 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196725 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366726 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196727 req->Start();
[email protected]255620da2013-08-19 13:14:296728 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196729 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376730 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446731}
6732
6733// Check that if request overrides the User-Agent header,
6734// the default is not appended.
6735TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6736 ASSERT_TRUE(test_server_.Start());
6737
6738 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196739 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366740 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446741 HttpRequestHeaders headers;
6742 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196743 req->SetExtraRequestHeaders(headers);
6744 req->Start();
[email protected]255620da2013-08-19 13:14:296745 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356746 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446747}
6748
[email protected]ee4c30d2012-11-07 15:08:436749// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6750// User-Agent header to be sent but does not send the Accept-Language and
6751// Accept-Charset headers.
6752TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6753 ASSERT_TRUE(test_server_.Start());
6754
[email protected]ceefd7fd2012-11-29 00:36:246755 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436756 TestURLRequestContext context(true);
6757 context.set_network_delegate(&network_delegate);
6758 context.Init();
6759 // We override the HttpUserAgentSettings after initialization because empty
6760 // entries get overridden by Init().
6761 context.set_http_user_agent_settings(NULL);
6762
6763 struct {
6764 const char* request;
6765 const char* expected_response;
6766 } tests[] = { { "echoheader?Accept-Language", "None" },
6767 { "echoheader?Accept-Charset", "None" },
6768 { "echoheader?User-Agent", "" } };
6769
viettrungluue4a8b882014-10-16 06:17:386770 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436771 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196772 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366773 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196774 req->Start();
[email protected]255620da2013-08-19 13:14:296775 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436776 EXPECT_EQ(tests[i].expected_response, d.data_received())
6777 << " Request = \"" << tests[i].request << "\"";
6778 }
6779}
6780
[email protected]5033ab82013-03-22 20:17:466781// Make sure that URLRequest passes on its priority updates to
6782// newly-created jobs after the first one.
6783TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6784 ASSERT_TRUE(test_server_.Start());
6785
6786 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196787 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366788 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196789 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466790
6791 scoped_refptr<URLRequestRedirectJob> redirect_job =
6792 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196793 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096794 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506795 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466796
[email protected]f7022f32014-08-21 16:32:196797 req->SetPriority(LOW);
6798 req->Start();
6799 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466800
6801 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196802 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506803 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466804
6805 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296806 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466807 EXPECT_EQ(LOW, job->priority());
6808}
6809
[email protected]80abdad2014-03-15 00:20:546810// Check that creating a network request while entering/exiting suspend mode
6811// fails as it should. This is the only case where an HttpTransactionFactory
6812// does not return an HttpTransaction.
6813TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6814 // Create a new HttpNetworkLayer that thinks it's suspended.
6815 HttpNetworkSession::Params params;
6816 params.host_resolver = default_context_.host_resolver();
6817 params.cert_verifier = default_context_.cert_verifier();
6818 params.transport_security_state = default_context_.transport_security_state();
6819 params.proxy_service = default_context_.proxy_service();
6820 params.ssl_config_service = default_context_.ssl_config_service();
6821 params.http_auth_handler_factory =
6822 default_context_.http_auth_handler_factory();
6823 params.network_delegate = &default_network_delegate_;
6824 params.http_server_properties = default_context_.http_server_properties();
6825 scoped_ptr<HttpNetworkLayer> network_layer(
6826 new HttpNetworkLayer(new HttpNetworkSession(params)));
6827 network_layer->OnSuspend();
6828
6829 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6830 HttpCache::DefaultBackend::InMemory(0));
6831
6832 TestURLRequestContext context(true);
6833 context.set_http_transaction_factory(&http_cache);
6834 context.Init();
6835
6836 TestDelegate d;
davidben151423e2015-03-23 18:48:366837 scoped_ptr<URLRequest> req(
6838 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196839 req->Start();
[email protected]80abdad2014-03-15 00:20:546840 base::RunLoop().Run();
6841
6842 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196843 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6844 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546845}
6846
6847// Check that creating a network request while entering/exiting suspend mode
6848// fails as it should in the case there is no cache. This is the only case
6849// where an HttpTransactionFactory does not return an HttpTransaction.
6850TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6851 // Create a new HttpNetworkLayer that thinks it's suspended.
6852 HttpNetworkSession::Params params;
6853 params.host_resolver = default_context_.host_resolver();
6854 params.cert_verifier = default_context_.cert_verifier();
6855 params.transport_security_state = default_context_.transport_security_state();
6856 params.proxy_service = default_context_.proxy_service();
6857 params.ssl_config_service = default_context_.ssl_config_service();
6858 params.http_auth_handler_factory =
6859 default_context_.http_auth_handler_factory();
6860 params.network_delegate = &default_network_delegate_;
6861 params.http_server_properties = default_context_.http_server_properties();
6862 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6863 network_layer.OnSuspend();
6864
6865 TestURLRequestContext context(true);
6866 context.set_http_transaction_factory(&network_layer);
6867 context.Init();
6868
6869 TestDelegate d;
davidben151423e2015-03-23 18:48:366870 scoped_ptr<URLRequest> req(
6871 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196872 req->Start();
[email protected]80abdad2014-03-15 00:20:546873 base::RunLoop().Run();
6874
6875 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196876 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6877 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546878}
6879
ttuttlec0c828492015-05-15 01:25:556880TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
6881 ASSERT_TRUE(test_server_.Start());
6882
6883 TestDelegate d;
6884 GURL test_url(test_server_.GetURL(std::string()));
6885 scoped_ptr<URLRequest> req(
6886 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6887
6888 req->Start();
6889 base::RunLoop().Run();
6890
6891 EXPECT_TRUE(req->response_info().network_accessed);
6892}
6893
6894TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
6895 ASSERT_TRUE(test_server_.Start());
6896
6897 // Populate the cache.
6898 TestDelegate d;
6899 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6900 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
6901 req->Start();
6902 base::RunLoop().Run();
6903
6904 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6905 EXPECT_TRUE(req->response_info().network_accessed);
6906 EXPECT_FALSE(req->response_info().was_cached);
6907
6908 req = default_context_.CreateRequest(test_server_.GetURL("cachetime"),
6909 DEFAULT_PRIORITY, &d);
6910 req->Start();
6911 base::RunLoop().Run();
6912
6913 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6914 EXPECT_FALSE(req->response_info().network_accessed);
6915 EXPECT_TRUE(req->response_info().was_cached);
6916}
6917
6918TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
6919 ASSERT_TRUE(test_server_.Start());
6920
6921 TestDelegate d;
6922 GURL test_url(test_server_.GetURL(std::string()));
6923 scoped_ptr<URLRequest> req(
6924 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
6925 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
6926
6927 req->Start();
6928 base::RunLoop().Run();
6929
6930 EXPECT_FALSE(req->response_info().network_accessed);
6931}
6932
bengr1bf8e942014-11-07 01:36:506933class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6934 public:
6935 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6936 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6937 // tests into the factory tests.
6938 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6939 }
6940
6941 void SetUpFactory() override {
6942 interceptor_ = new MockURLRequestInterceptor();
6943 job_factory_.reset(new URLRequestInterceptingJobFactory(
6944 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6945 }
6946
6947 MockURLRequestInterceptor* interceptor() const {
6948 return interceptor_;
6949 }
6950
6951 private:
6952 MockURLRequestInterceptor* interceptor_;
6953};
6954
6955TEST_F(URLRequestInterceptorTestHTTP,
6956 NetworkDelegateNotificationOnRedirectIntercept) {
6957 interceptor()->set_intercept_redirect(true);
6958 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6959 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6960
6961 ASSERT_TRUE(test_server()->Start());
6962
6963 TestDelegate d;
6964 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366965 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506966 req->Start();
6967 base::RunLoop().Run();
6968
6969 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6970 // Check we got one good response
6971 EXPECT_TRUE(req->status().is_success());
6972 if (req->status().is_success())
6973 EXPECT_EQ(200, req->response_headers()->response_code());
6974
6975 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6976 EXPECT_EQ(1, d.response_started_count());
6977 EXPECT_EQ(0, d.received_redirect_count());
6978
6979 EXPECT_EQ(1, default_network_delegate()->created_requests());
6980 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6981 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6982}
6983
6984TEST_F(URLRequestInterceptorTestHTTP,
6985 NetworkDelegateNotificationOnErrorIntercept) {
6986 // Intercept that error and respond with an OK response.
6987 interceptor()->set_intercept_final_response(true);
6988 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6989 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6990 default_network_delegate()->set_can_be_intercepted_on_error(true);
6991
6992 ASSERT_TRUE(test_server()->Start());
6993
6994 TestDelegate d;
6995 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6996 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366997 &d));
bengr1bf8e942014-11-07 01:36:506998 req->set_method("GET");
6999 req->Start();
7000 base::RunLoop().Run();
7001
7002 EXPECT_TRUE(interceptor()->did_intercept_final());
7003
7004 // Check we received one good response.
7005 EXPECT_TRUE(req->status().is_success());
7006 if (req->status().is_success())
7007 EXPECT_EQ(200, req->response_headers()->response_code());
7008 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7009 EXPECT_EQ(1, d.response_started_count());
7010 EXPECT_EQ(0, d.received_redirect_count());
7011
7012 EXPECT_EQ(1, default_network_delegate()->created_requests());
7013 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7014 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7015}
7016
7017TEST_F(URLRequestInterceptorTestHTTP,
7018 NetworkDelegateNotificationOnResponseIntercept) {
7019 // Intercept that error and respond with an OK response.
7020 interceptor()->set_intercept_final_response(true);
7021
7022 // Intercept with a real URLRequestHttpJob.
7023 interceptor()->set_use_url_request_http_job(true);
7024
7025 ASSERT_TRUE(test_server()->Start());
7026
7027 TestDelegate d;
7028 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:367029 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507030 req->set_method("GET");
7031 req->Start();
7032 base::RunLoop().Run();
7033
7034 EXPECT_TRUE(interceptor()->did_intercept_final());
7035
7036 // Check we received one good response.
7037 EXPECT_TRUE(req->status().is_success());
7038 if (req->status().is_success())
7039 EXPECT_EQ(200, req->response_headers()->response_code());
7040 EXPECT_EQ("hello", d.data_received());
7041 EXPECT_EQ(1, d.response_started_count());
7042 EXPECT_EQ(0, d.received_redirect_count());
7043
7044 EXPECT_EQ(1, default_network_delegate()->created_requests());
7045 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7046 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7047}
7048
mkwst0c5eab872014-11-21 14:18:547049class URLRequestTestReferrerPolicy : public URLRequestTest {
7050 public:
7051 URLRequestTestReferrerPolicy() {}
7052
7053 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
7054 origin_server_.reset(new SpawnedTestServer(
7055 origin_type, SpawnedTestServer::kLocalhost,
7056 origin_type == SpawnedTestServer::TYPE_HTTPS
7057 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7058 : base::FilePath(
7059 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7060 ASSERT_TRUE(origin_server_->Start());
7061 }
7062
7063 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
7064 SpawnedTestServer::Type destination_type) {
7065 origin_server_.reset(new SpawnedTestServer(
7066 origin_type, SpawnedTestServer::kLocalhost,
7067 origin_type == SpawnedTestServer::TYPE_HTTPS
7068 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7069 : base::FilePath(
7070 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7071 ASSERT_TRUE(origin_server_->Start());
7072
7073 destination_server_.reset(new SpawnedTestServer(
7074 destination_type, SpawnedTestServer::kLocalhost,
7075 destination_type == SpawnedTestServer::TYPE_HTTPS
7076 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
7077 : base::FilePath(
7078 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
7079 ASSERT_TRUE(destination_server_->Start());
7080 }
7081
7082 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
7083 const GURL& referrer,
7084 const GURL& expected) {
7085 // Create and execute the request: we'll only have a |destination_server_|
7086 // if the origins are meant to be distinct. Otherwise, we'll use the
7087 // |origin_server_| for both endpoints.
7088 GURL destination_url =
7089 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
7090 : origin_server_->GetURL("echoheader?Referer");
7091 GURL origin_url =
7092 origin_server_->GetURL("server-redirect?" + destination_url.spec());
7093
7094 TestDelegate d;
7095 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367096 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:547097 req->set_referrer_policy(policy);
7098 req->SetReferrer(referrer.spec());
7099 req->Start();
7100 base::RunLoop().Run();
7101
7102 EXPECT_EQ(1, d.response_started_count());
7103 EXPECT_EQ(1, d.received_redirect_count());
7104 EXPECT_EQ(destination_url, req->url());
7105 EXPECT_TRUE(req->status().is_success());
7106 EXPECT_EQ(200, req->response_headers()->response_code());
7107
7108 EXPECT_EQ(expected.spec(), req->referrer());
7109 if (expected.is_empty())
7110 EXPECT_EQ("None", d.data_received());
7111 else
7112 EXPECT_EQ(expected.spec(), d.data_received());
7113 }
7114
7115 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
7116
7117 private:
7118 scoped_ptr<SpawnedTestServer> origin_server_;
7119 scoped_ptr<SpawnedTestServer> destination_server_;
7120};
7121
7122TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
7123 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
7124
7125 VerifyReferrerAfterRedirect(
7126 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7127 origin_server()->GetURL("path/to/file.html"),
7128 origin_server()->GetURL("path/to/file.html"));
7129
7130 VerifyReferrerAfterRedirect(
7131 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7132 origin_server()->GetURL("path/to/file.html"),
7133 origin_server()->GetURL("path/to/file.html"));
7134
7135 VerifyReferrerAfterRedirect(
7136 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7137 origin_server()->GetURL("path/to/file.html"),
7138 origin_server()->GetURL("path/to/file.html"));
7139
7140 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7141 origin_server()->GetURL("path/to/file.html"),
7142 origin_server()->GetURL("path/to/file.html"));
7143}
7144
7145TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
7146 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7147 SpawnedTestServer::TYPE_HTTP);
7148
7149 VerifyReferrerAfterRedirect(
7150 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7151 origin_server()->GetURL("path/to/file.html"),
7152 origin_server()->GetURL("path/to/file.html"));
7153
7154 VerifyReferrerAfterRedirect(
7155 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7156 origin_server()->GetURL("path/to/file.html"),
7157 origin_server()->GetURL(std::string()));
7158
7159 VerifyReferrerAfterRedirect(
7160 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7161 origin_server()->GetURL("path/to/file.html"),
7162 origin_server()->GetURL(std::string()));
7163
7164 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7165 origin_server()->GetURL("path/to/file.html"),
7166 origin_server()->GetURL("path/to/file.html"));
7167}
7168
7169TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
7170 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
7171
7172 VerifyReferrerAfterRedirect(
7173 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7174 origin_server()->GetURL("path/to/file.html"),
7175 origin_server()->GetURL("path/to/file.html"));
7176
7177 VerifyReferrerAfterRedirect(
7178 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7179 origin_server()->GetURL("path/to/file.html"),
7180 origin_server()->GetURL("path/to/file.html"));
7181
7182 VerifyReferrerAfterRedirect(
7183 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7184 origin_server()->GetURL("path/to/file.html"),
7185 origin_server()->GetURL("path/to/file.html"));
7186
7187 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7188 origin_server()->GetURL("path/to/file.html"),
7189 origin_server()->GetURL("path/to/file.html"));
7190}
7191
7192TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
7193 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7194 SpawnedTestServer::TYPE_HTTPS);
7195
7196 VerifyReferrerAfterRedirect(
7197 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7198 origin_server()->GetURL("path/to/file.html"),
7199 origin_server()->GetURL("path/to/file.html"));
7200
7201 VerifyReferrerAfterRedirect(
7202 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7203 origin_server()->GetURL("path/to/file.html"),
7204 origin_server()->GetURL(std::string()));
7205
7206 VerifyReferrerAfterRedirect(
7207 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7208 origin_server()->GetURL("path/to/file.html"),
7209 origin_server()->GetURL(std::string()));
7210
7211 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7212 origin_server()->GetURL("path/to/file.html"),
7213 origin_server()->GetURL("path/to/file.html"));
7214}
7215
7216TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
7217 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
7218 SpawnedTestServer::TYPE_HTTPS);
7219
7220 VerifyReferrerAfterRedirect(
7221 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7222 origin_server()->GetURL("path/to/file.html"),
7223 origin_server()->GetURL("path/to/file.html"));
7224
7225 VerifyReferrerAfterRedirect(
7226 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7227 origin_server()->GetURL("path/to/file.html"),
7228 origin_server()->GetURL(std::string()));
7229
7230 VerifyReferrerAfterRedirect(
7231 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7232 origin_server()->GetURL("path/to/file.html"),
7233 origin_server()->GetURL(std::string()));
7234
7235 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7236 origin_server()->GetURL("path/to/file.html"),
7237 origin_server()->GetURL("path/to/file.html"));
7238}
7239
7240TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7241 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7242 SpawnedTestServer::TYPE_HTTP);
7243
7244 VerifyReferrerAfterRedirect(
7245 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7246 origin_server()->GetURL("path/to/file.html"), GURL());
7247
7248 VerifyReferrerAfterRedirect(
7249 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7250 origin_server()->GetURL("path/to/file.html"), GURL());
7251
7252 VerifyReferrerAfterRedirect(
7253 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7254 origin_server()->GetURL("path/to/file.html"),
7255 origin_server()->GetURL(std::string()));
7256
7257 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7258 origin_server()->GetURL("path/to/file.html"),
7259 origin_server()->GetURL("path/to/file.html"));
7260}
7261
[email protected]73e0bba2009-02-19 22:57:097262class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507263 public:
[email protected]ef2bf422012-05-11 03:27:097264 HTTPSRequestTest() : default_context_(true) {
7265 default_context_.set_network_delegate(&default_network_delegate_);
7266 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507267 }
dcheng67be2b1f2014-10-27 21:47:297268 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507269
7270 protected:
[email protected]ceefd7fd2012-11-29 00:36:247271 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097272 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467273};
7274
[email protected]c044616e2013-02-20 02:01:267275TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227276 SpawnedTestServer test_server(
7277 SpawnedTestServer::TYPE_HTTPS,
7278 SpawnedTestServer::kLocalhost,
7279 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117280 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467281
[email protected]ea224582008-12-07 20:25:467282 TestDelegate d;
7283 {
[email protected]f7022f32014-08-21 16:32:197284 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367285 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197286 r->Start();
7287 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467288
[email protected]255620da2013-08-19 13:14:297289 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467290
7291 EXPECT_EQ(1, d.response_started_count());
7292 EXPECT_FALSE(d.received_data_before_response());
7293 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197294 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197295 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197296 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197297 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197298 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467299 }
[email protected]ea224582008-12-07 20:25:467300}
7301
[email protected]5774ada2010-07-15 06:30:547302TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227303 SpawnedTestServer::SSLOptions ssl_options(
7304 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7305 SpawnedTestServer test_server(
7306 SpawnedTestServer::TYPE_HTTPS,
7307 ssl_options,
7308 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117309 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337310
7311 bool err_allowed = true;
7312 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7313 TestDelegate d;
7314 {
7315 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197316 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367317 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337318
[email protected]f7022f32014-08-21 16:32:197319 r->Start();
7320 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337321
[email protected]255620da2013-08-19 13:14:297322 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337323
7324 EXPECT_EQ(1, d.response_started_count());
7325 EXPECT_FALSE(d.received_data_before_response());
7326 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177327 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337328 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197329 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177330 } else {
[email protected]bacff652009-03-31 17:50:337331 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177332 }
[email protected]bacff652009-03-31 17:50:337333 }
7334 }
7335}
7336
[email protected]5774ada2010-07-15 06:30:547337TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227338 SpawnedTestServer::SSLOptions ssl_options(
7339 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7340 SpawnedTestServer test_server(
7341 SpawnedTestServer::TYPE_HTTPS,
7342 ssl_options,
7343 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117344 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337345
7346 // Iterate from false to true, just so that we do the opposite of the
7347 // previous test in order to increase test coverage.
7348 bool err_allowed = false;
7349 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7350 TestDelegate d;
7351 {
7352 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197353 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367354 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337355
[email protected]f7022f32014-08-21 16:32:197356 r->Start();
7357 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337358
[email protected]255620da2013-08-19 13:14:297359 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337360
7361 EXPECT_EQ(1, d.response_started_count());
7362 EXPECT_FALSE(d.received_data_before_response());
7363 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177364 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337365 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197366 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177367 } else {
[email protected]bacff652009-03-31 17:50:337368 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177369 }
[email protected]bacff652009-03-31 17:50:337370 }
7371 }
7372}
[email protected]73e0bba2009-02-19 22:57:097373
davidbena4c9d062015-04-03 22:34:257374// Tests that servers which require a deprecated cipher suite still work.
7375TEST_F(HTTPSRequestTest, CipherFallbackTest) {
vishal.b62985ca92015-04-17 08:45:517376 TestNetLog net_log;
davidbena4c9d062015-04-03 22:34:257377 default_context_.set_net_log(&net_log);
7378
7379 SpawnedTestServer::SSLOptions ssl_options;
7380 ssl_options.bulk_ciphers = SpawnedTestServer::SSLOptions::BULK_CIPHER_RC4;
7381 SpawnedTestServer test_server(
7382 SpawnedTestServer::TYPE_HTTPS, ssl_options,
7383 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7384 ASSERT_TRUE(test_server.Start());
7385
7386 TestDelegate d;
7387 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7388 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
7389 r->Start();
7390 EXPECT_TRUE(r->is_pending());
7391
7392 base::RunLoop().Run();
7393
7394 EXPECT_EQ(1, d.response_started_count());
7395 EXPECT_FALSE(d.received_data_before_response());
7396 EXPECT_NE(0, d.bytes_received());
7397 CheckSSLInfo(r->ssl_info());
7398 EXPECT_EQ(test_server.host_port_pair().host(), r->GetSocketAddress().host());
7399 EXPECT_EQ(test_server.host_port_pair().port(), r->GetSocketAddress().port());
7400
7401 // No version downgrade should have been necessary.
7402 EXPECT_FALSE(r->ssl_info().connection_status &
7403 SSL_CONNECTION_VERSION_FALLBACK);
7404 int expected_version = SSL_CONNECTION_VERSION_TLS1_2;
7405 if (SSLClientSocket::GetMaxSupportedSSLVersion() <
7406 SSL_PROTOCOL_VERSION_TLS1_2) {
7407 expected_version = SSL_CONNECTION_VERSION_TLS1_1;
7408 }
7409 EXPECT_EQ(expected_version,
7410 SSLConnectionStatusToVersion(r->ssl_info().connection_status));
7411
mmenke43758e62015-05-04 21:09:467412 TestNetLogEntry::List entries;
davidbena4c9d062015-04-03 22:34:257413 net_log.GetEntries(&entries);
7414 ExpectLogContainsSomewhere(entries, 0, NetLog::TYPE_SSL_CIPHER_FALLBACK,
7415 NetLog::PHASE_NONE);
7416}
7417
[email protected]316c1e5e2012-09-12 15:17:447418// This tests that a load of www.google.com with a certificate error sets
7419// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7420// the interstitial to be fatal.
7421TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227422 SpawnedTestServer::SSLOptions ssl_options(
7423 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7424 SpawnedTestServer test_server(
7425 SpawnedTestServer::TYPE_HTTPS,
7426 ssl_options,
7427 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447428 ASSERT_TRUE(test_server.Start());
7429
7430 // We require that the URL be www.google.com in order to pick up the
7431 // preloaded HSTS entries in the TransportSecurityState. This means that we
7432 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247433 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447434
7435 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247436 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447437 TestURLRequestContext context(true);
7438 context.set_network_delegate(&network_delegate);
7439 context.set_host_resolver(&host_resolver);
7440 TransportSecurityState transport_security_state;
7441 context.set_transport_security_state(&transport_security_state);
7442 context.Init();
7443
7444 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197445 scoped_ptr<URLRequest> r(context.CreateRequest(
7446 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367447 test_server.host_port_pair().port())),
7448 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447449
[email protected]f7022f32014-08-21 16:32:197450 r->Start();
7451 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447452
[email protected]255620da2013-08-19 13:14:297453 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447454
7455 EXPECT_EQ(1, d.response_started_count());
7456 EXPECT_FALSE(d.received_data_before_response());
7457 EXPECT_TRUE(d.have_certificate_errors());
7458 EXPECT_TRUE(d.certificate_errors_are_fatal());
7459}
7460
7461// This tests that cached HTTPS page loads do not cause any updates to the
7462// TransportSecurityState.
7463TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7464 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7465 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227466 SpawnedTestServer::SSLOptions ssl_options(
7467 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7468 SpawnedTestServer test_server(
7469 SpawnedTestServer::TYPE_HTTPS,
7470 ssl_options,
7471 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447472 ASSERT_TRUE(test_server.Start());
7473
[email protected]9e6968d2014-05-07 21:46:267474 // We require that the URL be www.google.com in order to pick up the static
7475 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7476 // that we have to use a MockHostResolver in order to direct www.google.com to
7477 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447478
7479 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247480 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447481 TestURLRequestContext context(true);
7482 context.set_network_delegate(&network_delegate);
7483 context.set_host_resolver(&host_resolver);
7484 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267485
7486 TransportSecurityState::DomainState static_domain_state;
7487 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127488 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447489 context.set_transport_security_state(&transport_security_state);
7490 context.Init();
7491
[email protected]9e6968d2014-05-07 21:46:267492 TransportSecurityState::DomainState dynamic_domain_state;
7493 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7494 "www.google.com", &dynamic_domain_state));
7495
[email protected]316c1e5e2012-09-12 15:17:447496 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197497 scoped_ptr<URLRequest> r(context.CreateRequest(
7498 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367499 test_server.host_port_pair().port())),
7500 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447501
[email protected]f7022f32014-08-21 16:32:197502 r->Start();
7503 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447504
[email protected]255620da2013-08-19 13:14:297505 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447506
7507 EXPECT_EQ(1, d.response_started_count());
7508 EXPECT_FALSE(d.received_data_before_response());
7509 EXPECT_TRUE(d.have_certificate_errors());
7510 EXPECT_TRUE(d.certificate_errors_are_fatal());
7511
[email protected]9e6968d2014-05-07 21:46:267512 // Get a fresh copy of the states, and check that they haven't changed.
7513 TransportSecurityState::DomainState new_static_domain_state;
7514 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127515 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267516 TransportSecurityState::DomainState new_dynamic_domain_state;
7517 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7518 "www.google.com", &new_dynamic_domain_state));
7519
7520 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7521 static_domain_state.sts.upgrade_mode);
7522 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7523 static_domain_state.sts.include_subdomains);
7524 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7525 static_domain_state.pkp.include_subdomains);
7526 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7527 static_domain_state.pkp.spki_hashes));
7528 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7529 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447530}
7531
[email protected]8ccc69f2012-11-28 19:52:147532// Make sure HSTS preserves a POST request's method and body.
7533TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7534 static const char kData[] = "hello world";
7535
[email protected]ce7d0cbc2013-05-03 18:57:227536 SpawnedTestServer::SSLOptions ssl_options(
7537 SpawnedTestServer::SSLOptions::CERT_OK);
7538 SpawnedTestServer test_server(
7539 SpawnedTestServer::TYPE_HTTPS,
7540 ssl_options,
7541 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147542 ASSERT_TRUE(test_server.Start());
7543
7544
7545 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7546 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227547 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7548 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147549 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147550
7551 // Force https for www.somewhere.com.
7552 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207553 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7554 bool include_subdomains = false;
7555 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7556 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147557
7558 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7559
7560 TestURLRequestContext context(true);
7561 context.set_host_resolver(&host_resolver);
7562 context.set_transport_security_state(&transport_security_state);
7563 context.set_network_delegate(&network_delegate);
7564 context.Init();
7565
7566 TestDelegate d;
7567 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7568 // cause a certificate error. Ignore the error.
7569 d.set_allow_certificate_errors(true);
7570
[email protected]f7022f32014-08-21 16:32:197571 scoped_ptr<URLRequest> req(context.CreateRequest(
7572 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367573 test_server.host_port_pair().port())),
7574 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197575 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077576 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147577
[email protected]f7022f32014-08-21 16:32:197578 req->Start();
[email protected]255620da2013-08-19 13:14:297579 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147580
[email protected]f7022f32014-08-21 16:32:197581 EXPECT_EQ("https", req->url().scheme());
7582 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147583 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407584
7585 LoadTimingInfo load_timing_info;
7586 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7587 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7588 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147589}
7590
rob4e0be1f2014-09-11 23:40:227591// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7592TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7593 static const char kOriginHeaderValue[] = "http://www.example.com";
7594
7595 SpawnedTestServer::SSLOptions ssl_options(
7596 SpawnedTestServer::SSLOptions::CERT_OK);
7597 SpawnedTestServer test_server(
7598 SpawnedTestServer::TYPE_HTTPS,
7599 ssl_options,
7600 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7601 ASSERT_TRUE(test_server.Start());
7602
7603 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7604 // address, so a MockHostResolver is needed to redirect example.net to the
7605 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7606 MockHostResolver host_resolver;
7607
7608 TransportSecurityState transport_security_state;
7609 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7610 bool include_subdomains = false;
7611 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7612
7613 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7614
7615 MockCertVerifier cert_verifier;
7616 cert_verifier.set_default_result(OK);
7617
7618 TestURLRequestContext context(true);
7619 context.set_host_resolver(&host_resolver);
7620 context.set_transport_security_state(&transport_security_state);
7621 context.set_network_delegate(&network_delegate);
7622 context.set_cert_verifier(&cert_verifier);
7623 context.Init();
7624
7625 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7626 test_server.host_port_pair().port()));
7627 url::Replacements<char> replacements;
7628 const char kNewScheme[] = "https";
7629 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7630 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7631
7632 TestDelegate d;
7633 // Quit on redirect to allow response header inspection upon redirect.
7634 d.set_quit_on_redirect(true);
7635
davidben151423e2015-03-23 18:48:367636 scoped_ptr<URLRequest> req(
7637 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227638 // Set Origin header to simulate a cross-origin request.
7639 HttpRequestHeaders request_headers;
7640 request_headers.SetHeader("Origin", kOriginHeaderValue);
7641 req->SetExtraRequestHeaders(request_headers);
7642
7643 req->Start();
7644 base::RunLoop().Run();
7645
7646 EXPECT_EQ(1, d.received_redirect_count());
7647
7648 const HttpResponseHeaders* headers = req->response_headers();
7649 std::string redirect_location;
7650 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7651 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7652
7653 std::string received_cors_header;
7654 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7655 &received_cors_header));
7656 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7657}
7658
Adam Ricecb76ac62015-02-20 05:33:257659// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7660// are performed in net/websockets/websocket_end_to_end_test.cc.
7661TEST(WebSocketURLRequestTest, HSTSApplied) {
7662 TestNetworkDelegate network_delegate;
7663 TransportSecurityState transport_security_state;
7664 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7665 bool include_subdomains = false;
7666 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7667 TestURLRequestContext context(true);
7668 context.set_transport_security_state(&transport_security_state);
7669 context.set_network_delegate(&network_delegate);
7670 context.Init();
7671 GURL ws_url("ws://example.net/echo");
7672 TestDelegate delegate;
7673 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367674 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257675 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7676 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7677}
7678
[email protected]316c1e5e2012-09-12 15:17:447679namespace {
7680
7681class SSLClientAuthTestDelegate : public TestDelegate {
7682 public:
7683 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7684 }
dchengb03027d2014-10-21 12:00:207685 void OnCertificateRequested(URLRequest* request,
7686 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447687 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347688 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447689 }
7690 int on_certificate_requested_count() {
7691 return on_certificate_requested_count_;
7692 }
7693 private:
7694 int on_certificate_requested_count_;
7695};
7696
7697} // namespace
7698
7699// TODO(davidben): Test the rest of the code. Specifically,
7700// - Filtering which certificates to select.
7701// - Sending a certificate back.
7702// - Getting a certificate request in an SSL renegotiation sending the
7703// HTTP request.
7704TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227705 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447706 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227707 SpawnedTestServer test_server(
7708 SpawnedTestServer::TYPE_HTTPS,
7709 ssl_options,
7710 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447711 ASSERT_TRUE(test_server.Start());
7712
7713 SSLClientAuthTestDelegate d;
7714 {
[email protected]f7022f32014-08-21 16:32:197715 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367716 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447717
[email protected]f7022f32014-08-21 16:32:197718 r->Start();
7719 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447720
[email protected]255620da2013-08-19 13:14:297721 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447722
7723 EXPECT_EQ(1, d.on_certificate_requested_count());
7724 EXPECT_FALSE(d.received_data_before_response());
7725 EXPECT_EQ(0, d.bytes_received());
7726
7727 // Send no certificate.
7728 // TODO(davidben): Get temporary client cert import (with keys) working on
7729 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197730 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447731
[email protected]255620da2013-08-19 13:14:297732 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447733
7734 EXPECT_EQ(1, d.response_started_count());
7735 EXPECT_FALSE(d.received_data_before_response());
7736 EXPECT_NE(0, d.bytes_received());
7737 }
7738}
7739
7740TEST_F(HTTPSRequestTest, ResumeTest) {
7741 // Test that we attempt a session resume when making two connections to the
7742 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227743 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447744 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227745 SpawnedTestServer test_server(
7746 SpawnedTestServer::TYPE_HTTPS,
7747 ssl_options,
7748 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447749 ASSERT_TRUE(test_server.Start());
7750
7751 SSLClientSocket::ClearSessionCache();
7752
7753 {
7754 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197755 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367756 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447757
[email protected]f7022f32014-08-21 16:32:197758 r->Start();
7759 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447760
[email protected]255620da2013-08-19 13:14:297761 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447762
7763 EXPECT_EQ(1, d.response_started_count());
7764 }
7765
7766 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7767 CloseAllConnections();
7768
7769 {
7770 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197771 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367772 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447773
[email protected]f7022f32014-08-21 16:32:197774 r->Start();
7775 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447776
[email protected]255620da2013-08-19 13:14:297777 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447778
7779 // The response will look like;
7780 // insert abc
7781 // lookup abc
7782 // insert xyz
7783 //
7784 // With a newline at the end which makes the split think that there are
7785 // four lines.
7786
7787 EXPECT_EQ(1, d.response_started_count());
7788 std::vector<std::string> lines;
7789 base::SplitString(d.data_received(), '\n', &lines);
7790 ASSERT_EQ(4u, lines.size()) << d.data_received();
7791
7792 std::string session_id;
7793
7794 for (size_t i = 0; i < 2; i++) {
7795 std::vector<std::string> parts;
7796 base::SplitString(lines[i], '\t', &parts);
7797 ASSERT_EQ(2u, parts.size());
7798 if (i == 0) {
7799 EXPECT_EQ("insert", parts[0]);
7800 session_id = parts[1];
7801 } else {
7802 EXPECT_EQ("lookup", parts[0]);
7803 EXPECT_EQ(session_id, parts[1]);
7804 }
7805 }
7806 }
7807}
7808
Adam Langley32352ad2014-10-14 22:31:007809// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7810// the result of fetching "ssl-session-cache" from the test server, indicates
7811// that exactly two different sessions were inserted, with no lookups etc.
7812static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7813 std::vector<std::string> lines;
7814 base::SplitString(session_info, '\n', &lines);
7815 ASSERT_EQ(3u, lines.size()) << session_info;
7816
7817 std::string session_id;
7818 for (size_t i = 0; i < 2; i++) {
7819 std::vector<std::string> parts;
7820 base::SplitString(lines[i], '\t', &parts);
7821 ASSERT_EQ(2u, parts.size());
7822 EXPECT_EQ("insert", parts[0]);
7823 if (i == 0) {
7824 session_id = parts[1];
7825 } else {
7826 EXPECT_NE(session_id, parts[1]);
7827 }
7828 }
7829}
7830
[email protected]316c1e5e2012-09-12 15:17:447831TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7832 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7833 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227834 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447835 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227836 SpawnedTestServer test_server(
7837 SpawnedTestServer::TYPE_HTTPS,
7838 ssl_options,
7839 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447840 ASSERT_TRUE(test_server.Start());
7841
7842 SSLClientSocket::ClearSessionCache();
7843
7844 {
7845 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197846 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367847 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447848
[email protected]f7022f32014-08-21 16:32:197849 r->Start();
7850 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447851
[email protected]255620da2013-08-19 13:14:297852 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447853
7854 EXPECT_EQ(1, d.response_started_count());
7855 }
7856
7857 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7858 HttpNetworkSession::Params params;
7859 params.host_resolver = default_context_.host_resolver();
7860 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117861 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447862 params.proxy_service = default_context_.proxy_service();
7863 params.ssl_config_service = default_context_.ssl_config_service();
7864 params.http_auth_handler_factory =
7865 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417866 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447867 params.http_server_properties = default_context_.http_server_properties();
7868 params.ssl_session_cache_shard = "alternate";
7869
[email protected]cba24642014-08-15 20:49:597870 scoped_ptr<HttpCache> cache(new HttpCache(
7871 new HttpNetworkSession(params),
7872 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447873
7874 default_context_.set_http_transaction_factory(cache.get());
7875
7876 {
7877 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197878 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367879 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447880
[email protected]f7022f32014-08-21 16:32:197881 r->Start();
7882 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447883
[email protected]255620da2013-08-19 13:14:297884 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447885
7886 // The response will look like;
7887 // insert abc
7888 // insert xyz
7889 //
7890 // With a newline at the end which makes the split think that there are
7891 // three lines.
7892
7893 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007894 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447895 }
7896}
7897
davidben8ecc3072014-09-03 23:19:097898#if defined(OS_WIN)
7899
7900namespace {
7901
7902bool IsECDSACipherSuite(uint16_t cipher_suite) {
7903 const char* key_exchange;
7904 const char* cipher;
7905 const char* mac;
7906 bool is_aead;
7907 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7908 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7909}
7910
7911} // namespace
7912
7913// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7914// verified.
davidben9399c952014-10-07 04:09:117915TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097916 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7917 LOG(INFO) << "Skipping test on this version.";
7918 return;
7919 }
7920
7921 SpawnedTestServer test_server(
7922 SpawnedTestServer::TYPE_HTTPS,
7923 SpawnedTestServer::kLocalhost,
7924 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7925 ASSERT_TRUE(test_server.Start());
7926
7927 TestDelegate d;
7928 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367929 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:097930 r->Start();
7931 EXPECT_TRUE(r->is_pending());
7932
7933 base::RunLoop().Run();
7934
7935 EXPECT_EQ(1, d.response_started_count());
7936 std::vector<std::string> lines;
7937 base::SplitString(d.data_received(), '\n', &lines);
7938
7939 for (size_t i = 0; i < lines.size(); i++) {
7940 int cipher_suite;
7941 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7942 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7943 << "ClientHello advertised " << cipher_suite;
7944 }
7945}
7946
7947#endif // OS_WIN
7948
Adam Langley32352ad2014-10-14 22:31:007949class TestSSLConfigService : public SSLConfigService {
7950 public:
7951 TestSSLConfigService(bool ev_enabled,
7952 bool online_rev_checking,
7953 bool rev_checking_required_local_anchors)
7954 : ev_enabled_(ev_enabled),
7955 online_rev_checking_(online_rev_checking),
7956 rev_checking_required_local_anchors_(
7957 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027958 min_version_(kDefaultSSLVersionMin),
7959 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7960
7961 void set_min_version(uint16 version) {
7962 min_version_ = version;
7963 }
Adam Langley32352ad2014-10-14 22:31:007964
7965 void set_fallback_min_version(uint16 version) {
7966 fallback_min_version_ = version;
7967 }
7968
7969 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207970 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007971 *config = SSLConfig();
7972 config->rev_checking_enabled = online_rev_checking_;
7973 config->verify_ev_cert = ev_enabled_;
7974 config->rev_checking_required_local_anchors =
7975 rev_checking_required_local_anchors_;
7976 if (fallback_min_version_) {
7977 config->version_fallback_min = fallback_min_version_;
7978 }
Adam Langleyac6f24b42014-10-31 20:24:027979 if (min_version_) {
7980 config->version_min = min_version_;
7981 }
Adam Langley32352ad2014-10-14 22:31:007982 }
7983
7984 protected:
dchengb03027d2014-10-21 12:00:207985 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007986
7987 private:
7988 const bool ev_enabled_;
7989 const bool online_rev_checking_;
7990 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027991 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007992 uint16 fallback_min_version_;
7993};
7994
7995class FallbackTestURLRequestContext : public TestURLRequestContext {
7996 public:
7997 explicit FallbackTestURLRequestContext(bool delay_initialization)
7998 : TestURLRequestContext(delay_initialization) {}
7999
8000 void set_fallback_min_version(uint16 version) {
8001 TestSSLConfigService *ssl_config_service =
8002 new TestSSLConfigService(true /* check for EV */,
8003 false /* online revocation checking */,
8004 false /* require rev. checking for local
8005 anchors */);
Adam Langley32352ad2014-10-14 22:31:008006 ssl_config_service->set_fallback_min_version(version);
8007 set_ssl_config_service(ssl_config_service);
8008 }
8009};
8010
[email protected]48d2b7c52014-06-27 01:16:558011class HTTPSFallbackTest : public testing::Test {
8012 public:
Adam Langley32352ad2014-10-14 22:31:008013 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298014 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558015
8016 protected:
8017 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8018 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008019 context_.Init();
8020 delegate_.set_allow_certificate_errors(true);
8021
[email protected]48d2b7c52014-06-27 01:16:558022 SpawnedTestServer test_server(
8023 SpawnedTestServer::TYPE_HTTPS,
8024 ssl_options,
8025 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8026 ASSERT_TRUE(test_server.Start());
8027
davidben151423e2015-03-23 18:48:368028 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
8029 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558030 request_->Start();
8031
8032 base::RunLoop().Run();
8033 }
8034
Adam Langley32352ad2014-10-14 22:31:008035 void set_fallback_min_version(uint16 version) {
8036 context_.set_fallback_min_version(version);
8037 }
8038
[email protected]48d2b7c52014-06-27 01:16:558039 void ExpectConnection(int version) {
8040 EXPECT_EQ(1, delegate_.response_started_count());
8041 EXPECT_NE(0, delegate_.bytes_received());
8042 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8043 request_->ssl_info().connection_status));
8044 EXPECT_TRUE(request_->ssl_info().connection_status &
8045 SSL_CONNECTION_VERSION_FALLBACK);
8046 }
8047
8048 void ExpectFailure(int error) {
8049 EXPECT_EQ(1, delegate_.response_started_count());
8050 EXPECT_FALSE(request_->status().is_success());
8051 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8052 EXPECT_EQ(error, request_->status().error());
8053 }
8054
8055 private:
8056 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008057 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:558058 scoped_ptr<URLRequest> request_;
8059};
8060
8061// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
8062// than necessary.
8063TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
8064 SpawnedTestServer::SSLOptions ssl_options(
8065 SpawnedTestServer::SSLOptions::CERT_OK);
8066 ssl_options.tls_intolerant =
8067 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8068
8069 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8070 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8071}
8072
8073// This test is disabled on Android because the remote test server doesn't cause
8074// a TCP reset.
8075#if !defined(OS_ANDROID)
8076// Tests fallback to TLS 1.0 on connection reset.
8077TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
8078 SpawnedTestServer::SSLOptions ssl_options(
8079 SpawnedTestServer::SSLOptions::CERT_OK);
8080 ssl_options.tls_intolerant =
8081 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8082 ssl_options.tls_intolerance_type =
8083 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8084
8085 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8086 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
8087}
8088#endif // !OS_ANDROID
8089
[email protected]12833302014-07-02 01:57:318090// Tests that we don't fallback on handshake failure with servers that implement
8091// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:558092TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:558093 SpawnedTestServer::SSLOptions ssl_options(
8094 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438095 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:558096 // a version fallback.
8097 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438098 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558099 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8100 // connections are rejected.
8101 ssl_options.fallback_scsv_enabled = true;
8102
8103 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8104
8105 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
8106 // intolerance. If the fallback SCSV is processed when the original error
8107 // that caused the fallback should be returned, which should be
8108 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
8109 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8110}
8111
[email protected]12833302014-07-02 01:57:318112// Tests that we don't fallback on connection closed with servers that implement
8113// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:318114TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:318115 SpawnedTestServer::SSLOptions ssl_options(
8116 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:438117 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:318118 // a version fallback.
8119 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:438120 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:318121 ssl_options.tls_intolerance_type =
8122 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8123 // Have the server process TLS_FALLBACK_SCSV so that version fallback
8124 // connections are rejected.
8125 ssl_options.fallback_scsv_enabled = true;
8126
8127 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8128
8129 // The original error should be replayed on rejected fallback.
8130 ExpectFailure(ERR_CONNECTION_CLOSED);
8131}
8132
davidbenb937d6c2015-05-14 04:53:428133// Tests that the SSLv3 fallback doesn't happen.
[email protected]48d2b7c52014-06-27 01:16:558134TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
8135 SpawnedTestServer::SSLOptions ssl_options(
8136 SpawnedTestServer::SSLOptions::CERT_OK);
8137 ssl_options.tls_intolerant =
8138 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8139
8140 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:028141 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:008142}
8143
davidbenb937d6c2015-05-14 04:53:428144// Tests that the TLSv1 fallback triggers on closed connections.
[email protected]48d2b7c52014-06-27 01:16:558145TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8146 SpawnedTestServer::SSLOptions ssl_options(
8147 SpawnedTestServer::SSLOptions::CERT_OK);
8148 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428149 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:558150 ssl_options.tls_intolerance_type =
8151 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
[email protected]48d2b7c52014-06-27 01:16:558152
8153 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb937d6c2015-05-14 04:53:428154 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
[email protected]48d2b7c52014-06-27 01:16:558155}
8156
davidbenb937d6c2015-05-14 04:53:428157// Test that fallback probe connections don't cause sessions to be cached.
8158TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:008159 SpawnedTestServer::SSLOptions ssl_options(
8160 SpawnedTestServer::SSLOptions::CERT_OK);
8161 ssl_options.tls_intolerant =
davidbenb937d6c2015-05-14 04:53:428162 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
Adam Langley32352ad2014-10-14 22:31:008163 ssl_options.tls_intolerance_type =
8164 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8165 ssl_options.record_resume = true;
8166
8167 SpawnedTestServer test_server(
8168 SpawnedTestServer::TYPE_HTTPS,
8169 ssl_options,
8170 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8171 ASSERT_TRUE(test_server.Start());
8172
8173 SSLClientSocket::ClearSessionCache();
8174
davidbenb937d6c2015-05-14 04:53:428175 // Make a connection that does a probe fallback to TLSv1 but fails because
8176 // TLSv1 fallback is disabled. We don't wish a session for this connection to
Adam Langley32352ad2014-10-14 22:31:008177 // be inserted locally.
8178 {
8179 TestDelegate delegate;
8180 FallbackTestURLRequestContext context(true);
8181
davidbenb937d6c2015-05-14 04:53:428182 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_2);
Adam Langley32352ad2014-10-14 22:31:008183 context.Init();
8184 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:368185 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008186 request->Start();
8187
8188 base::RunLoop().Run();
8189
8190 EXPECT_EQ(1, delegate.response_started_count());
8191 EXPECT_FALSE(request->status().is_success());
8192 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8193 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8194 request->status().error());
8195 }
8196
davidbenb937d6c2015-05-14 04:53:428197 // Now allow TLSv1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:008198 {
8199 TestDelegate delegate;
8200 FallbackTestURLRequestContext context(true);
davidbenb937d6c2015-05-14 04:53:428201 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008202
8203 context.Init();
davidben151423e2015-03-23 18:48:368204 scoped_ptr<URLRequest> request(context.CreateRequest(
8205 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:008206 request->Start();
8207
8208 base::RunLoop().Run();
8209
8210 EXPECT_EQ(1, delegate.response_started_count());
8211 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:428212 EXPECT_EQ(
8213 SSL_CONNECTION_VERSION_TLS1,
8214 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:008215 EXPECT_TRUE(request->ssl_info().connection_status &
8216 SSL_CONNECTION_VERSION_FALLBACK);
8217
8218 std::vector<std::string> lines;
8219 // If no sessions were cached then the server should have seen two sessions
8220 // inserted with no lookups.
8221 AssertTwoDistinctSessionsInserted(delegate.data_received());
8222 }
8223}
8224
[email protected]a8fed1742013-12-27 02:14:248225class HTTPSSessionTest : public testing::Test {
8226 public:
8227 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598228 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248229
8230 default_context_.set_network_delegate(&default_network_delegate_);
8231 default_context_.set_cert_verifier(&cert_verifier_);
8232 default_context_.Init();
8233 }
dcheng67be2b1f2014-10-27 21:47:298234 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248235
8236 protected:
8237 MockCertVerifier cert_verifier_;
8238 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8239 TestURLRequestContext default_context_;
8240};
8241
8242// Tests that session resumption is not attempted if an invalid certificate
8243// is presented.
8244TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8245 SpawnedTestServer::SSLOptions ssl_options;
8246 ssl_options.record_resume = true;
8247 SpawnedTestServer test_server(
8248 SpawnedTestServer::TYPE_HTTPS,
8249 ssl_options,
8250 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8251 ASSERT_TRUE(test_server.Start());
8252
8253 SSLClientSocket::ClearSessionCache();
8254
8255 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598256 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248257 {
8258 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198259 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368260 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248261
[email protected]f7022f32014-08-21 16:32:198262 r->Start();
8263 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248264
8265 base::RunLoop().Run();
8266
8267 EXPECT_EQ(1, d.response_started_count());
8268 }
8269
8270 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8271 CloseAllConnections();
8272
8273 // Now change the certificate to be acceptable (so that the response is
8274 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598275 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248276 {
8277 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198278 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368279 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248280
[email protected]f7022f32014-08-21 16:32:198281 r->Start();
8282 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248283
8284 base::RunLoop().Run();
8285
8286 // The response will look like;
8287 // insert abc
8288 // insert xyz
8289 //
8290 // With a newline at the end which makes the split think that there are
8291 // three lines.
8292 //
8293 // If a session was presented (eg: a bug), then the response would look
8294 // like;
8295 // insert abc
8296 // lookup abc
8297 // insert xyz
8298
8299 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008300 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248301 }
8302}
8303
[email protected]dffe8242012-03-20 15:14:278304// This the fingerprint of the "Testing CA" certificate used by the testserver.
8305// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268306static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278307 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8308 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8309
[email protected]51523f52013-07-31 21:57:288310// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8311// testserver.
8312static const SHA256HashValue kOCSPTestCertSPKI = { {
8313 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8314 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8315 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8316 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8317} };
8318
[email protected]dffe8242012-03-20 15:14:278319// This is the policy OID contained in the certificates that testserver
8320// generates.
8321static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8322
8323class HTTPSOCSPTest : public HTTPSRequestTest {
8324 public:
8325 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098326 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088327 ev_test_policy_(
8328 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8329 kOCSPTestCertFingerprint,
8330 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028331 }
8332
dcheng67be2b1f2014-10-27 21:47:298333 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098334 SetupContext(&context_);
8335 context_.Init();
[email protected]dffe8242012-03-20 15:14:278336
[email protected]cba24642014-08-15 20:49:598337 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208338 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428339 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508340 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278341
davidben71f35ff2015-04-17 20:54:488342#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098343 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278344 EnsureNSSHttpIOInit();
8345#endif
8346 }
8347
[email protected]ce7d0cbc2013-05-03 18:57:228348 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278349 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538350 // We always overwrite out_cert_status.
8351 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228352 SpawnedTestServer test_server(
8353 SpawnedTestServer::TYPE_HTTPS,
8354 ssl_options,
8355 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278356 ASSERT_TRUE(test_server.Start());
8357
8358 TestDelegate d;
8359 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198360 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368361 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198362 r->Start();
[email protected]dffe8242012-03-20 15:14:278363
[email protected]255620da2013-08-19 13:14:298364 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278365
8366 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198367 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278368 }
8369
dcheng67be2b1f2014-10-27 21:47:298370 ~HTTPSOCSPTest() override {
davidben71f35ff2015-04-17 20:54:488371#if defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278372 ShutdownNSSHttpIO();
8373#endif
8374 }
8375
[email protected]a13234c2012-03-20 21:45:028376 protected:
8377 // SetupContext configures the URLRequestContext that will be used for making
8378 // connetions to testserver. This can be overridden in test subclasses for
8379 // different behaviour.
8380 virtual void SetupContext(URLRequestContext* context) {
8381 context->set_ssl_config_service(
8382 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208383 true /* online revocation checking */,
8384 false /* require rev. checking for local
8385 anchors */));
[email protected]a13234c2012-03-20 21:45:028386 }
8387
[email protected]dffe8242012-03-20 15:14:278388 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098389 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088390 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278391};
8392
[email protected]a13234c2012-03-20 21:45:028393static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018394#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028395 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8396 // have that ability on other platforms.
8397 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8398#else
8399 return 0;
8400#endif
8401}
8402
[email protected]3a86a712013-07-30 07:16:208403// SystemSupportsHardFailRevocationChecking returns true iff the current
8404// operating system supports revocation checking and can distinguish between
8405// situations where a given certificate lacks any revocation information (eg:
8406// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8407// revocation information cannot be obtained (eg: the CRL was unreachable).
8408// If it does not, then tests which rely on 'hard fail' behaviour should be
8409// skipped.
8410static bool SystemSupportsHardFailRevocationChecking() {
davidben71f35ff2015-04-17 20:54:488411#if defined(OS_WIN) || defined(USE_NSS_CERTS) || defined(OS_IOS)
[email protected]3a86a712013-07-30 07:16:208412 return true;
8413#else
8414 return false;
8415#endif
8416}
8417
[email protected]a13234c2012-03-20 21:45:028418// SystemUsesChromiumEVMetadata returns true iff the current operating system
8419// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8420// several tests are effected because our testing EV certificate won't be
8421// recognised as EV.
8422static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328423#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578424 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8425 return false;
[email protected]e1b2d732014-03-28 16:20:328426#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8427 // On OS X and Android, we use the system to tell us whether a certificate is
8428 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018429 return false;
8430#else
8431 return true;
8432#endif
8433}
8434
[email protected]b6f2de32012-08-17 04:35:088435static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008436#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578437 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8438 return false;
8439#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028440 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8441#elif defined(OS_ANDROID)
8442 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8443 return false;
8444#else
8445 return true;
8446#endif
8447}
8448
davidbend1fb2f12014-11-08 02:51:008449static bool SystemSupportsOCSPStapling() {
davidben71f35ff2015-04-17 20:54:488450#if defined(USE_NSS_CERTS)
davidbend1fb2f12014-11-08 02:51:008451 return true;
8452#elif defined(OS_WIN)
8453 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8454#else
8455 return false;
8456#endif
8457}
8458
[email protected]dffe8242012-03-20 15:14:278459TEST_F(HTTPSOCSPTest, Valid) {
8460 if (!SystemSupportsOCSP()) {
8461 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8462 return;
8463 }
8464
[email protected]ce7d0cbc2013-05-03 18:57:228465 SpawnedTestServer::SSLOptions ssl_options(
8466 SpawnedTestServer::SSLOptions::CERT_AUTO);
8467 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278468
[email protected]924e9f92012-12-16 22:00:538469 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128470 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278471
8472 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8473
[email protected]a13234c2012-03-20 21:45:028474 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8475 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278476
8477 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8478}
8479
8480TEST_F(HTTPSOCSPTest, Revoked) {
8481 if (!SystemSupportsOCSP()) {
8482 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8483 return;
8484 }
8485
[email protected]ce7d0cbc2013-05-03 18:57:228486 SpawnedTestServer::SSLOptions ssl_options(
8487 SpawnedTestServer::SSLOptions::CERT_AUTO);
8488 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278489
8490 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128491 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278492
[email protected]a592c0432012-12-01 18:10:298493#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278494 // Doesn't pass on OS X yet for reasons that need to be investigated.
8495 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8496#endif
8497 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8498 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8499}
8500
8501TEST_F(HTTPSOCSPTest, Invalid) {
8502 if (!SystemSupportsOCSP()) {
8503 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8504 return;
8505 }
8506
[email protected]ce7d0cbc2013-05-03 18:57:228507 SpawnedTestServer::SSLOptions ssl_options(
8508 SpawnedTestServer::SSLOptions::CERT_AUTO);
8509 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278510
[email protected]924e9f92012-12-16 22:00:538511 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128512 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278513
[email protected]a13234c2012-03-20 21:45:028514 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278515 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278516
8517 // Without a positive OCSP response, we shouldn't show the EV status.
8518 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8519 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8520}
[email protected]a13234c2012-03-20 21:45:028521
davidbend1fb2f12014-11-08 02:51:008522TEST_F(HTTPSOCSPTest, ValidStapled) {
8523 if (!SystemSupportsOCSPStapling()) {
8524 LOG(WARNING)
8525 << "Skipping test because system doesn't support OCSP stapling";
8526 return;
8527 }
8528
8529 SpawnedTestServer::SSLOptions ssl_options(
8530 SpawnedTestServer::SSLOptions::CERT_AUTO);
8531 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8532 ssl_options.staple_ocsp_response = true;
8533 ssl_options.ocsp_server_unavailable = true;
8534
8535 CertStatus cert_status;
8536 DoConnection(ssl_options, &cert_status);
8537
8538 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8539
8540 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8541 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8542
8543 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8544}
8545
davidben6c3191b2014-11-21 22:38:048546// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:488547#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:048548#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8549#else
8550#define MAYBE_RevokedStapled RevokedStapled
8551#endif
8552TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008553 if (!SystemSupportsOCSPStapling()) {
8554 LOG(WARNING)
8555 << "Skipping test because system doesn't support OCSP stapling";
8556 return;
8557 }
8558
8559 SpawnedTestServer::SSLOptions ssl_options(
8560 SpawnedTestServer::SSLOptions::CERT_AUTO);
8561 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8562 ssl_options.staple_ocsp_response = true;
8563 ssl_options.ocsp_server_unavailable = true;
8564
8565 CertStatus cert_status;
8566 DoConnection(ssl_options, &cert_status);
8567
8568 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8569 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8570 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8571}
8572
[email protected]3a86a712013-07-30 07:16:208573class HTTPSHardFailTest : public HTTPSOCSPTest {
8574 protected:
dchengb03027d2014-10-21 12:00:208575 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208576 context->set_ssl_config_service(
8577 new TestSSLConfigService(false /* check for EV */,
8578 false /* online revocation checking */,
8579 true /* require rev. checking for local
8580 anchors */));
8581 }
8582};
8583
[email protected]3a86a712013-07-30 07:16:208584TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8585 if (!SystemSupportsOCSP()) {
8586 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8587 return;
8588 }
8589
8590 if (!SystemSupportsHardFailRevocationChecking()) {
8591 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8592 << "revocation checking";
8593 return;
8594 }
8595
8596 SpawnedTestServer::SSLOptions ssl_options(
8597 SpawnedTestServer::SSLOptions::CERT_AUTO);
8598 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8599
8600 CertStatus cert_status;
8601 DoConnection(ssl_options, &cert_status);
8602
8603 EXPECT_EQ(CERT_STATUS_REVOKED,
8604 cert_status & CERT_STATUS_REVOKED);
8605
8606 // Without a positive OCSP response, we shouldn't show the EV status.
8607 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8608}
8609
[email protected]a13234c2012-03-20 21:45:028610class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8611 protected:
dchengb03027d2014-10-21 12:00:208612 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028613 context->set_ssl_config_service(
8614 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208615 false /* online revocation checking */,
8616 false /* require rev. checking for local
8617 anchors */));
[email protected]a13234c2012-03-20 21:45:028618 }
8619};
8620
8621TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8622 if (!SystemSupportsOCSP()) {
8623 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8624 return;
8625 }
8626
[email protected]ce7d0cbc2013-05-03 18:57:228627 SpawnedTestServer::SSLOptions ssl_options(
8628 SpawnedTestServer::SSLOptions::CERT_AUTO);
8629 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028630 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8631
[email protected]924e9f92012-12-16 22:00:538632 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128633 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028634
8635 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8636 cert_status & CERT_STATUS_ALL_ERRORS);
8637
8638 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088639 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8640 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028641}
8642
[email protected]be0fff62013-08-29 23:37:488643TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8644 if (!SystemSupportsOCSP()) {
8645 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8646 return;
8647 }
8648
8649 SpawnedTestServer::SSLOptions ssl_options(
8650 SpawnedTestServer::SSLOptions::CERT_AUTO);
8651 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8652 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8653
8654 CertStatus cert_status;
8655 DoConnection(ssl_options, &cert_status);
8656
8657 // Currently only works for Windows. When using NSS or OS X, it's not
8658 // possible to determine whether the check failed because of actual
8659 // revocation or because there was an OCSP failure.
8660#if defined(OS_WIN)
8661 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8662#else
8663 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8664#endif
8665
8666 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8667 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8668 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8669}
8670
[email protected]a13234c2012-03-20 21:45:028671TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8672 if (!SystemSupportsOCSP()) {
8673 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8674 return;
8675 }
8676
[email protected]ce7d0cbc2013-05-03 18:57:228677 SpawnedTestServer::SSLOptions ssl_options(
8678 SpawnedTestServer::SSLOptions::CERT_AUTO);
8679 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028680 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8681
8682 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128683 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028684
8685 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8686
8687 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8688 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088689 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8690 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028691}
8692
8693TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8694 if (!SystemSupportsOCSP()) {
8695 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8696 return;
8697 }
8698
[email protected]ce7d0cbc2013-05-03 18:57:228699 SpawnedTestServer::SSLOptions ssl_options(
8700 SpawnedTestServer::SSLOptions::CERT_AUTO);
8701 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028702 SSLConfigService::SetCRLSet(
8703 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8704
8705 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128706 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028707
8708 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8709 cert_status & CERT_STATUS_ALL_ERRORS);
8710
8711 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088712 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8713 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028714}
8715
[email protected]51523f52013-07-31 21:57:288716TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8717 if (!SystemSupportsOCSP()) {
8718 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8719 return;
8720 }
8721
8722 SpawnedTestServer::SSLOptions ssl_options(
8723 SpawnedTestServer::SSLOptions::CERT_AUTO);
8724 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8725 SSLConfigService::SetCRLSet(
8726 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8727 false, &kOCSPTestCertSPKI, "")));
8728
8729 CertStatus cert_status;
8730 DoConnection(ssl_options, &cert_status);
8731
8732 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8733 // revocation check for EV.
8734 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8735 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8736 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8737 EXPECT_FALSE(
8738 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8739}
8740
8741TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8742 if (!SystemSupportsOCSP()) {
8743 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8744 return;
8745 }
8746
[email protected]ce7d0cbc2013-05-03 18:57:228747 SpawnedTestServer::SSLOptions ssl_options(
8748 SpawnedTestServer::SSLOptions::CERT_AUTO);
8749 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028750 SSLConfigService::SetCRLSet(
8751 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8752
[email protected]51523f52013-07-31 21:57:288753 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128754 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028755
[email protected]51523f52013-07-31 21:57:288756 // Even with a fresh CRLSet, we should still do online revocation checks when
8757 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8758 // test.
8759 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8760 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028761
[email protected]51523f52013-07-31 21:57:288762 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028763 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288764 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028765}
8766
[email protected]b6f2de32012-08-17 04:35:088767TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8768 // Test that when EV verification is requested, but online revocation
8769 // checking is disabled, and the leaf certificate is not in fact EV, that
8770 // no revocation checking actually happens.
8771 if (!SystemSupportsOCSP()) {
8772 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8773 return;
8774 }
8775
8776 // Unmark the certificate's OID as EV, which should disable revocation
8777 // checking (as per the user preference)
8778 ev_test_policy_.reset();
8779
[email protected]ce7d0cbc2013-05-03 18:57:228780 SpawnedTestServer::SSLOptions ssl_options(
8781 SpawnedTestServer::SSLOptions::CERT_AUTO);
8782 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088783 SSLConfigService::SetCRLSet(
8784 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8785
8786 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128787 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088788
8789 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8790
8791 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8792 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8793}
8794
[email protected]a13234c2012-03-20 21:45:028795class HTTPSCRLSetTest : public HTTPSOCSPTest {
8796 protected:
dchengb03027d2014-10-21 12:00:208797 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028798 context->set_ssl_config_service(
8799 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208800 false /* online revocation checking */,
8801 false /* require rev. checking for local
8802 anchors */));
[email protected]a13234c2012-03-20 21:45:028803 }
8804};
8805
8806TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228807 SpawnedTestServer::SSLOptions ssl_options(
8808 SpawnedTestServer::SSLOptions::CERT_AUTO);
8809 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028810 SSLConfigService::SetCRLSet(
8811 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8812
[email protected]924e9f92012-12-16 22:00:538813 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128814 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028815
8816 // If we're not trying EV verification then, even if the CRLSet has expired,
8817 // we don't fall back to online revocation checks.
8818 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8819 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8820 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8821}
[email protected]51523f52013-07-31 21:57:288822
8823TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308824#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288825 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8826 return;
8827#endif
8828
8829 SpawnedTestServer::SSLOptions ssl_options(
8830 SpawnedTestServer::SSLOptions::CERT_AUTO);
8831 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8832 ssl_options.cert_serial = 10;
8833 SSLConfigService::SetCRLSet(
8834 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8835 false, &kOCSPTestCertSPKI, "\x0a")));
8836
8837 CertStatus cert_status = 0;
8838 DoConnection(ssl_options, &cert_status);
8839
8840 // If the certificate is recorded as revoked in the CRLSet, that should be
8841 // reflected without online revocation checking.
8842 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8843 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8844 EXPECT_FALSE(
8845 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8846}
[email protected]316c1e5e2012-09-12 15:17:448847#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278848
[email protected]316c1e5e2012-09-12 15:17:448849#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:318850class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118851 public:
[email protected]d9fca99a2012-02-24 16:16:208852 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:228853 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:158854 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:118855 }
8856
[email protected]b89ca032009-08-31 21:41:318857 protected:
[email protected]ce7d0cbc2013-05-03 18:57:228858 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318859};
8860
[email protected]d2a133182012-08-05 16:44:088861// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098862TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088863 ASSERT_TRUE(test_server_.Start());
8864
[email protected]9d5730b2012-08-24 17:42:498865 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:348866 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:088867
8868 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088869 job_factory.SetProtocolHandler(
8870 "ftp",
[email protected]e0f35c92013-05-08 16:04:348871 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:088872 default_context_.set_job_factory(&job_factory);
8873
8874 TestDelegate d;
8875 {
davidben151423e2015-03-23 18:48:368876 scoped_ptr<URLRequest> r(
8877 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198878 r->Start();
8879 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088880
[email protected]255620da2013-08-19 13:14:298881 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088882
[email protected]f7022f32014-08-21 16:32:198883 EXPECT_FALSE(r->is_pending());
8884 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8885 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088886 }
8887}
8888
[email protected]5accf7332009-11-24 03:41:388889// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128890TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118891 ASSERT_TRUE(test_server_.Start());
8892
[email protected]a25e90e2009-09-09 17:05:378893 TestDelegate d;
8894 {
[email protected]f7022f32014-08-21 16:32:198895 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368896 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198897 r->Start();
8898 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378899
[email protected]255620da2013-08-19 13:14:298900 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378901
[email protected]f7022f32014-08-21 16:32:198902 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378903 EXPECT_EQ(1, d.response_started_count());
8904 EXPECT_FALSE(d.received_data_before_response());
8905 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198906 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198907 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198908 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198909 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378910 }
8911}
8912
[email protected]7df70012010-02-04 00:09:558913// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128914TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118915 ASSERT_TRUE(test_server_.Start());
8916
[email protected]6cdfd7f2013-02-08 20:40:158917 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278918 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028919 app_path = app_path.AppendASCII("LICENSE");
[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(
davidben151423e2015-03-23 18:48:368923 test_server_.GetURL("/LICENSE"), 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
8929 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498930 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278931
[email protected]f7022f32014-08-21 16:32:198932 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278933 EXPECT_EQ(1, d.response_started_count());
8934 EXPECT_FALSE(d.received_data_before_response());
8935 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:198936 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198937 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198938 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198939 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278940 }
8941}
8942
[email protected]e9ecbd12009-12-20 18:44:408943// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128944TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118945 ASSERT_TRUE(test_server_.Start());
8946
[email protected]6cdfd7f2013-02-08 20:40:158947 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278948 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028949 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278950 TestDelegate d;
8951 {
[email protected]f7022f32014-08-21 16:32:198952 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]95409e12010-08-17 20:07:118953 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:368954 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198955 r->Start();
8956 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278957
[email protected]255620da2013-08-19 13:14:298958 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278959
8960 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498961 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278962
[email protected]f7022f32014-08-21 16:32:198963 EXPECT_FALSE(r->is_pending());
[email protected]6d81b482011-02-22 19:47:198964 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198965 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198966 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198967 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278968 EXPECT_EQ(1, d.response_started_count());
8969 EXPECT_FALSE(d.received_data_before_response());
8970 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:258971
8972 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198973 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258974 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278975 }
8976}
8977
[email protected]49abd652010-08-05 05:04:538978// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128979TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118980 ASSERT_TRUE(test_server_.Start());
8981
[email protected]6cdfd7f2013-02-08 20:40:158982 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278983 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028984 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278985 TestDelegate d;
8986 {
[email protected]f7022f32014-08-21 16:32:198987 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8988 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8989 "wrong_password"),
davidben151423e2015-03-23 18:48:368990 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198991 r->Start();
8992 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278993
[email protected]255620da2013-08-19 13:14:298994 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278995
8996 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498997 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278998
[email protected]f7022f32014-08-21 16:32:198999 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279000 EXPECT_EQ(1, d.response_started_count());
9001 EXPECT_FALSE(d.received_data_before_response());
9002 EXPECT_EQ(d.bytes_received(), 0);
9003 }
9004}
9005
[email protected]cde4e80d2009-10-16 19:58:159006// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129007TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:119008 ASSERT_TRUE(test_server_.Start());
9009
[email protected]6cdfd7f2013-02-08 20:40:159010 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:589011 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9012 app_path = app_path.AppendASCII("LICENSE");
9013 TestDelegate d;
9014 // Set correct login credentials. The delegate will be asked for them when
9015 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589016 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589017 {
[email protected]f7022f32014-08-21 16:32:199018 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9019 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
9020 "wrong_password"),
davidben151423e2015-03-23 18:48:369021 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199022 r->Start();
9023 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589024
[email protected]255620da2013-08-19 13:14:299025 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589026
9027 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499028 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:589029
[email protected]f7022f32014-08-21 16:32:199030 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589031 EXPECT_EQ(1, d.response_started_count());
9032 EXPECT_FALSE(d.received_data_before_response());
9033 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
9034 }
9035}
9036
[email protected]49abd652010-08-05 05:04:539037// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129038TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:119039 ASSERT_TRUE(test_server_.Start());
9040
[email protected]6cdfd7f2013-02-08 20:40:159041 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:279042 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:029043 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:279044 TestDelegate d;
9045 {
davidben151423e2015-03-23 18:48:369046 scoped_ptr<URLRequest> r(
9047 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9048 "/LICENSE", "wrong_user", "chrome"),
9049 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199050 r->Start();
9051 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279052
[email protected]255620da2013-08-19 13:14:299053 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279054
9055 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499056 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:279057
[email protected]f7022f32014-08-21 16:32:199058 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279059 EXPECT_EQ(1, d.response_started_count());
9060 EXPECT_FALSE(d.received_data_before_response());
9061 EXPECT_EQ(d.bytes_received(), 0);
9062 }
9063}
[email protected]8b8a197d2009-08-26 15:57:589064
[email protected]cde4e80d2009-10-16 19:58:159065// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129066TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:119067 ASSERT_TRUE(test_server_.Start());
9068
[email protected]6cdfd7f2013-02-08 20:40:159069 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:589070 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9071 app_path = app_path.AppendASCII("LICENSE");
9072 TestDelegate d;
9073 // Set correct login credentials. The delegate will be asked for them when
9074 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589075 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589076 {
davidben151423e2015-03-23 18:48:369077 scoped_ptr<URLRequest> r(
9078 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
9079 "/LICENSE", "wrong_user", "chrome"),
9080 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199081 r->Start();
9082 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589083
[email protected]255620da2013-08-19 13:14:299084 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589085
9086 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499087 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:589088
[email protected]f7022f32014-08-21 16:32:199089 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589090 EXPECT_EQ(1, d.response_started_count());
9091 EXPECT_FALSE(d.received_data_before_response());
9092 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
9093 }
9094}
[email protected]60a3df52009-09-22 16:13:249095
[email protected]cde4e80d2009-10-16 19:58:159096// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129097TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:119098 ASSERT_TRUE(test_server_.Start());
9099
[email protected]6cdfd7f2013-02-08 20:40:159100 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:249101 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9102 app_path = app_path.AppendASCII("LICENSE");
9103
9104 scoped_ptr<TestDelegate> d(new TestDelegate);
9105 {
9106 // Pass correct login identity in the URL.
[email protected]f7022f32014-08-21 16:32:199107 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:199108 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:369109 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199110 r->Start();
9111 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249112
[email protected]255620da2013-08-19 13:14:299113 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249114
9115 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499116 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249117
[email protected]f7022f32014-08-21 16:32:199118 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249119 EXPECT_EQ(1, d->response_started_count());
9120 EXPECT_FALSE(d->received_data_before_response());
9121 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9122 }
9123
9124 d.reset(new TestDelegate);
9125 {
9126 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:199127 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369128 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199129 r->Start();
9130 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249131
[email protected]255620da2013-08-19 13:14:299132 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249133
9134 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499135 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249136
[email protected]f7022f32014-08-21 16:32:199137 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249138 EXPECT_EQ(1, d->response_started_count());
9139 EXPECT_FALSE(d->received_data_before_response());
9140 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9141 }
9142}
9143
[email protected]cde4e80d2009-10-16 19:58:159144// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:129145TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:119146 ASSERT_TRUE(test_server_.Start());
9147
[email protected]6cdfd7f2013-02-08 20:40:159148 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:249149 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
9150 app_path = app_path.AppendASCII("LICENSE");
9151
9152 scoped_ptr<TestDelegate> d(new TestDelegate);
9153 // Set correct login credentials. The delegate will be asked for them when
9154 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589155 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:249156 {
[email protected]f7022f32014-08-21 16:32:199157 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
9158 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
9159 "wrong_password"),
davidben151423e2015-03-23 18:48:369160 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199161 r->Start();
9162 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249163
[email protected]255620da2013-08-19 13:14:299164 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249165
9166 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499167 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249168
[email protected]f7022f32014-08-21 16:32:199169 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249170 EXPECT_EQ(1, d->response_started_count());
9171 EXPECT_FALSE(d->received_data_before_response());
9172 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9173 }
9174
9175 // Use a new delegate without explicit credentials. The cached ones should be
9176 // used.
9177 d.reset(new TestDelegate);
9178 {
9179 // Don't pass wrong credentials in the URL, they would override valid cached
9180 // ones.
[email protected]f7022f32014-08-21 16:32:199181 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369182 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:199183 r->Start();
9184 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249185
[email protected]255620da2013-08-19 13:14:299186 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249187
9188 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499189 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249190
[email protected]f7022f32014-08-21 16:32:199191 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249192 EXPECT_EQ(1, d->response_started_count());
9193 EXPECT_FALSE(d->received_data_before_response());
9194 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9195 }
9196}
[email protected]316c1e5e2012-09-12 15:17:449197#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519198
ttuttlec0c828492015-05-15 01:25:559199TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
9200 TestDelegate d;
9201 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
9202 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9203 d.set_quit_on_network_start(true);
9204
9205 EXPECT_FALSE(req->response_info().network_accessed);
9206
9207 req->Start();
9208 base::RunLoop().Run();
9209
9210 EXPECT_EQ(1, d.received_before_network_start_count());
9211 EXPECT_EQ(0, d.response_started_count());
9212 EXPECT_FALSE(req->response_info().network_accessed);
9213
9214 req->ResumeNetworkStart();
9215 base::RunLoop().Run();
9216}
9217
9218TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
9219 TestDelegate d;
9220 scoped_ptr<URLRequest> req(
9221 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
9222
9223 EXPECT_FALSE(req->response_info().network_accessed);
9224
9225 req->Start();
9226 base::RunLoop().Run();
9227
9228 EXPECT_EQ(1, default_network_delegate_.completed_requests());
9229 EXPECT_FALSE(req->response_info().network_accessed);
9230}
9231
9232TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
9233 MockHostResolver host_resolver;
9234 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9235 TestURLRequestContext context(true);
9236 context.set_network_delegate(&network_delegate);
9237 context.set_host_resolver(&host_resolver);
9238 host_resolver.rules()->AddSimulatedFailure("*");
9239 context.Init();
9240
9241 TestDelegate d;
9242 scoped_ptr<URLRequest> req(context.CreateRequest(
9243 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
9244
9245 EXPECT_FALSE(req->response_info().network_accessed);
9246
9247 req->Start();
9248 base::RunLoop().Run();
9249 EXPECT_TRUE(req->response_info().network_accessed);
9250}
9251
[email protected]7461a402011-03-24 23:19:519252} // namespace net